zaileys 4.12.0 → 4.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builder/builder.d.ts +1 -1
- package/dist/builder/state.d.ts +3 -1
- package/dist/client/client.d.ts +3 -0
- package/dist/index.cjs +3 -3
- package/dist/index.mjs +3 -3
- package/package.json +1 -1
|
@@ -26,7 +26,7 @@ export declare class MessageBuilder<State extends BuilderState> {
|
|
|
26
26
|
protected readonly socket: BuilderSocketLike;
|
|
27
27
|
protected readonly internal: BuilderInternalState;
|
|
28
28
|
constructor(socket: BuilderSocketLike, internal: BuilderInternalState);
|
|
29
|
-
static create(socket: BuilderSocketLike, recipient: string, resolveRecipient?: (raw: string) => Promise<string>, recordSent?: (message: WAMessage) => void): MessageBuilder<'init'>;
|
|
29
|
+
static create(socket: BuilderSocketLike, recipient: string, resolveRecipient?: (raw: string) => Promise<string>, recordSent?: (message: WAMessage) => void, inheritDisappearing?: (jid: string) => number | undefined): MessageBuilder<'init'>;
|
|
30
30
|
to(this: MessageBuilder<'init'>, recipient: string): MessageBuilder<'init'>;
|
|
31
31
|
text(this: MessageBuilder<'init'>, content: string, opts?: TextOptions): MessageBuilder<'content-set'>;
|
|
32
32
|
image(this: MessageBuilder<'init'>, src: MediaSource, opts?: ImageOptions): MessageBuilder<'content-set'>;
|
package/dist/builder/state.d.ts
CHANGED
|
@@ -12,5 +12,7 @@ export type BuilderInternalState = {
|
|
|
12
12
|
disappearingSeconds?: number;
|
|
13
13
|
resolveRecipient?: (raw: string) => Promise<string>;
|
|
14
14
|
recordSent?: (message: WAMessage) => void;
|
|
15
|
+
/** The chat's own disappearing timer, applied when the caller did not set one. */
|
|
16
|
+
inheritDisappearing?: (jid: string) => number | undefined;
|
|
15
17
|
};
|
|
16
|
-
export declare const createInternalState: (recipient: string, resolveRecipient?: (raw: string) => Promise<string>, recordSent?: (message: WAMessage) => void) => BuilderInternalState;
|
|
18
|
+
export declare const createInternalState: (recipient: string, resolveRecipient?: (raw: string) => Promise<string>, recordSent?: (message: WAMessage) => void, inheritDisappearing?: (jid: string) => number | undefined) => BuilderInternalState;
|
package/dist/client/client.d.ts
CHANGED
|
@@ -37,6 +37,8 @@ export declare class Client extends TypedEventEmitter<ClientEventMap> {
|
|
|
37
37
|
private readonly presenceThrottle;
|
|
38
38
|
private readonly scheduleLimiter;
|
|
39
39
|
private authExhausted;
|
|
40
|
+
/** Each chat's disappearing timer, learned from inbound messages so outbound sends can inherit it. */
|
|
41
|
+
private readonly chatExpiration;
|
|
40
42
|
private _socket;
|
|
41
43
|
private reconnectTimer;
|
|
42
44
|
private listenerCleanup;
|
|
@@ -133,6 +135,7 @@ export declare class Client extends TypedEventEmitter<ClientEventMap> {
|
|
|
133
135
|
private buildCommandContext;
|
|
134
136
|
private detachCommands;
|
|
135
137
|
send(to: string): MessageBuilder<'init'>;
|
|
138
|
+
private rememberChatExpiration;
|
|
136
139
|
edit(key: WAMessageKey): EditBuilder;
|
|
137
140
|
delete(key: WAMessageKey, opts?: DeleteOptions): Promise<void>;
|
|
138
141
|
react(key: WAMessageKey, emoji: string): Promise<WAMessageKey>;
|
package/dist/index.cjs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
`)}:{type:"code",content:u.join(`
|
|
8
8
|
`)});continue}let c=e[i+1];if(o.includes("|")&&c!==void 0&&c.includes("|")&&So.test(c)){s();let u=[hr(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)u.push(hr(e[i])),i++;t.push({type:"table",rows:u});continue}let l=fr.exec(o);if(l){s();let u=[l[1]];for(i++;i<e.length;){let w=fr.exec(e[i]);if(!w)break;u.push(w[1]),i++;}t.push({type:"image",url:u.length===1?u[0]:u});continue}r.push(o),i++;}return s(),t};var vr=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new p("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var Mr=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new p("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await O(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var Sr=(n,e)=>{let t=n instanceof Date?n:new Date(n);if(Number.isNaN(t.getTime()))throw new p("INVALID_OPTIONS",`event() ${e} must be a valid Date or epoch ms`);return new Date(Math.floor(t.getTime()/1e3)*1e3)},br=n=>{if(n==null||typeof n.name!="string"||n.name.trim().length===0)throw new p("INVALID_OPTIONS","event() requires a non-empty name");return {event:{name:n.name,startDate:Sr(n.startAt,"startAt"),...n.description!==void 0?{description:n.description}:{},...n.endAt!==void 0?{endDate:Sr(n.endAt,"endAt")}:{},...n.call!==void 0?{call:n.call}:{},...n.canceled!==void 0?{isCancelled:n.canceled}:{},...n.location!==void 0?{location:{degreesLatitude:n.location.latitude,degreesLongitude:n.location.longitude,...n.location.name!==void 0?{name:n.location.name}:{},...n.location.address!==void 0?{address:n.location.address}:{}}}:{}}}};var Cr=n=>{if(n==null||typeof n.jid!="string"||!n.jid.endsWith("@g.us"))throw new p("INVALID_OPTIONS","groupInvite() requires a group jid ending in @g.us");if(typeof n.code!="string"||n.code.trim().length===0)throw new p("INVALID_OPTIONS","groupInvite() requires an invite code");let e={inviteCode:n.code,inviteExpiration:n.expiresAt??Math.floor(Date.now()/1e3)+3*86400,groupJid:n.jid,groupName:n.subject??"",caption:n.caption??""};return n.thumbnail!==void 0&&(e.jpegThumbnail=n.thumbnail),{[R]:{groupInviteMessage:e}}};var Pr=4294967295,To=/^[0-9a-fA-F]{3}$/,Io=/^[0-9a-fA-F]{6}$/,xo=/^[0-9a-fA-F]{8}$/,kr={system:0,"system-text":1,"fb-script":2,"system-bold":6,morningbreeze:7,calistoga:8,exo2:9,courierprime:10},we=n=>{throw new p("INVALID_OPTIONS",n)},Oo=n=>{if(typeof n=="number"){if(!Number.isInteger(n))return we(`groupStatus() backgroundColor must be an integer, got ${n}`);let t=n<0?Pr+n+1:n;return t<0||t>Pr?we(`groupStatus() backgroundColor is outside the ARGB range, got ${n}`):t}if(typeof n!="string")return we("groupStatus() backgroundColor must be a hex string or an integer");let e=n.trim().replace("#","");if(xo.test(e))return Number.parseInt(e,16);if(Io.test(e))return Number.parseInt(`FF${e}`,16);if(To.test(e)){let t=[...e].map(r=>`${r}${r}`).join("");return Number.parseInt(`FF${t}`,16)}return we(`groupStatus() backgroundColor must be #RGB, #RRGGBB or #AARRGGBB, got ${n}`)},Ro=n=>{if(typeof n=="number")return !Number.isInteger(n)||n<0?we(`groupStatus() font must be a non-negative integer, got ${n}`):n;let e=kr[n];return e===void 0?we(`groupStatus() font must be one of ${Object.keys(kr).join(", ")}, got ${String(n)}`):e},Tr=(n,e)=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","groupStatus() requires a non-empty string");let t={text:n};return e?.backgroundColor!==void 0&&(t.backgroundArgb=Oo(e.backgroundColor)),e?.font!==void 0&&(t.font=Ro(e.font)),Ir({extendedTextMessage:t})},Ir=n=>({[R]:{groupStatusMessageV2:{message:n}},[_e]:"groupStatus()"}),_o=["conversation","extendedTextMessage"],No={imageMessage:"image",videoMessage:"video",audioMessage:"audio"},Er=n=>({[R]:{groupStatusMessageV2:{message:{}}},[_e]:"groupStatus()",[Mt]:n}),Lo=["image","video","audio"],Do=n=>{let e=n;if(typeof e.message=="function"||e.message!==void 0||e.key!==void 0)return null;for(let t of Lo)if(e[t]!==void 0)return {kind:t,src:e[t]};return null},Bo=n=>typeof n.message=="function"?n.message():n,Wo=(n,e,t)=>{let r=dc.proto.Message.decode(dc.proto.Message.encode(n).finish());e==="conversation"&&(r.extendedTextMessage={text:r.conversation},delete r.conversation);let s=r.extendedTextMessage;return delete s.viewOnce,s.contextInfo={},t?.caption!==void 0&&(s.text=t.caption),Ir({extendedTextMessage:s})},xr=async(n,e)=>{let t=Do(n);if(t!==null){let a=n,{buffer:d}=await O(t.src),c={kind:t.kind,buffer:d},l=e?.caption??a.caption;return t.kind!=="audio"&&l!==void 0&&(c.caption=l),t.kind==="audio"&&a.ptt===true&&(c.ptt=true),Er(c)}let r=Bo(n),s=r?.message==null?null:dc.normalizeMessageContent(r.message),i=s==null?void 0:dc.getContentType(s);if(s==null||i===void 0)throw new p("EMPTY_CONTENT","groupStatus() source has no repostable content");let o=No[i];if(o!==void 0){let a=s[i]??{},d;try{let{downloadMediaMessage:u}=await import('baileys');d=await u(r,"buffer",{});}catch(u){throw new p("MEDIA_LOAD_FAILED","groupStatus() could not download the source media",{cause:u})}let c={kind:o,buffer:d},l=e?.caption??a.caption;return o!=="audio"&&l!==void 0&&(c.caption=l),o==="audio"&&a.ptt===true&&(c.ptt=true),Er(c)}if(!_o.includes(i))throw new p("INVALID_OPTIONS",`groupStatus() cannot repost ${i}; supported: text, image, video, audio`);return Wo(s,i,e)};var Or=10,Rr=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new p("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new p("INVALID_OPTIONS","list() requires at least one section");let e=0,t=new Set,r=n.sections.map(a=>{if(!Array.isArray(a.rows)||a.rows.length===0)throw new p("INVALID_OPTIONS","each list section requires at least one row");let d=a.rows.map(c=>{if(typeof c.id!="string"||c.id.length===0)throw new p("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof c.title!="string"||c.title.trim().length===0)throw new p("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(c.id))throw new p("INVALID_OPTIONS",`duplicate list row id: ${c.id}`);return t.add(c.id),e+=1,{header:"",title:c.title,description:c.description??"",id:c.id}});return {title:a.title,highlight_label:"",rows:d}});if(e>Or)throw new p("INVALID_OPTIONS",`list() accepts at most ${Or} rows total`);let s={name:"single_select",buttonParamsJson:JSON.stringify({title:n.buttonText,sections:r})},i={body:{text:n.description&&n.description.length>0?n.description:" "},nativeFlowMessage:{buttons:[s],messageParamsJson:""}};return n.footerText&&n.footerText.length>0&&(i.footer={text:n.footerText}),n.title&&n.title.length>0&&(i.header={title:n.title,subtitle:"",hasMediaAttachment:false}),{[R]:{interactiveMessage:i}}};var _r=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new p("INVALID_OPTIONS",`location() latitude must be within -90..90, got ${String(n)}`);if(typeof e!="number"||Number.isNaN(e)||e<-180||e>180)throw new p("INVALID_OPTIONS",`location() longitude must be within -180..180, got ${String(e)}`);let r={degreesLatitude:n,degreesLongitude:e};return t?.name!==void 0&&(r.name=t.name),t?.address!==void 0&&(r.address=t.address),{location:r}};var Nr=2,Lr=12,Dr=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<Nr)throw new p("INVALID_OPTIONS",`poll() requires a minimum of ${Nr} options`);if(e.length>Lr)throw new p("INVALID_OPTIONS",`poll() accepts a maximum of ${Lr} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new p("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new p("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var Br=async n=>{if(n==null||typeof n.title!="string"||n.title.trim().length===0)throw new p("INVALID_OPTIONS","product() requires a non-empty title");if(typeof n.businessOwnerId!="string"||n.businessOwnerId.length===0)throw new p("INVALID_OPTIONS","product() requires businessOwnerId");let{buffer:e}=await O(n.image),t={productImage:e,title:n.title};n.productId!==void 0&&(t.productId=n.productId),n.description!==void 0&&(t.description=n.description),n.currency!==void 0&&(t.currencyCode=n.currency),n.price!==void 0&&(t.priceAmount1000=Math.round(n.price*1e3)),n.retailerId!==void 0&&(t.retailerId=n.retailerId),n.url!==void 0&&(t.url=n.url);let r={product:t,businessOwnerJid:n.businessOwnerId};return n.body!==void 0&&(r.body=n.body),n.footer!==void 0&&(r.footer=n.footer),r};var Wr=async(n,e)=>{let{buffer:t}=await O(n),r;try{r=await new se(t).sticker.create(e);}catch(i){throw new p("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var Fr=3,jr=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new p("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new p("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>Fr)throw new p("INVALID_OPTIONS",`template() accepts at most ${Fr} buttons`);let t={text:`${n.header&&n.header.length>0?`*${n.header}*
|
|
9
9
|
|
|
10
|
-
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),St(n.buttons,t)};var At=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Ur=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var mn=new WeakSet,qr=n=>{mn.add(n);},Kr=n=>{if(!mn.has(n))return n;mn.delete(n);let e=crypto.randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var Pt="status@broadcast",Jo=[{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,Ur(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=mr(wr(e),t):this.internal.content=At(e),this}image(e,t){return this.internal.pendingContent=fe(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=cr(e,t),this}document(e,t){return this.internal.pendingContent=Mr(e,t),this}sticker(e,t){return this.internal.pendingContent=Wr(e,t),this}buttons(e,t){return this.internal.content=St(e,t),this}carousel(e,t){return this.internal.content=pr(e,t),this}list(e){return this.internal.content=Rr(e),this}poll(e,t,r){return this.internal.content=Dr(e,t,r),this}location(e,t,r){return this.internal.content=_r(e,t,r),this}contact(e){return this.internal.content=vr(e),this}template(e){return this.internal.content=jr(e),this}event(e){return this.internal.content=br(e),this}groupInvite(e){return this.internal.content=Cr(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=Tr(e,t):this.internal.pendingContent=xr(e,t),this}product(e){return this.internal.pendingContent=Br(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!==Pt)throw new p("INVALID_RECIPIENT",`audience() only applies to ${Pt}, not ${this.internal.recipient}`);if(this.internal.albumItems){let c={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(c.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(c.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(c.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(c.disappearingSeconds=this.internal.disappearingSeconds),ir(this.socket,this.internal.recipient,this.internal.albumItems,c)}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 c=s[_e];if(typeof c=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${c} can only be sent to a group jid ending in @g.us`);let l=s[Mt],u=l!==void 0?await this.buildStatusMedia(l):i,w=s[cn],M=s[un];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===Pt&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${Pt} 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 d;try{d=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(c){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:c})}if(!d?.key)throw new p("SEND_FAILED","socket returned no message key");return d.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await O(t.src),s=await dc.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 dc.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=dc.normalizeMessageContent(e),i=s==null?void 0:dc.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 d={userJid:this.socket.user?.id??""},c=this.internal.quoted;c!==void 0&&c.message!=null&&(d.quoted=c),this.internal.disappearingSeconds!==void 0&&(d.ephemeralExpiration=this.internal.disappearingSeconds);let l=dc.generateWAMessageFromContent(this.internal.recipient,e,d);if(s&&l.message!=null&&qr(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:Jo}:{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 Ne=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=At(e),this}image(e,t){return this.pendingContent=fe(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 gn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},fn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},hn=async(n,e,t={})=>{let r=gn(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);},yn=async(n,e,t)=>{let r=gn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return fn(s)},wn=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 fn(i)},kt=async(n,e,t,r={})=>{let s=gn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return fn(o)};var Vo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Le=n=>Vo.test(n),vn=async(n,e,t,r=Ho)=>{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 d=(await n.onWhatsApp(e))?.find(c=>c.exists&&c.jid);if(!d)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,d.jid),d.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Ho=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 De=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 Be=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 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("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 Fe=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 je=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 $r=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new I("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Ue=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=$r(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 $r(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 qe=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 Ke=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 zo=n=>{let e=n[0];return e==="{"||e==="["},Yo=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},Zo=n=>n===" "||n===" "||n===`
|
|
10
|
+
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),St(n.buttons,t)};var At=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Ur=(n,e,t,r)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{},...r?{inheritDisappearing:r}:{}});var mn=new WeakSet,qr=n=>{mn.add(n);},Kr=n=>{if(!mn.has(n))return n;mn.delete(n);let e=crypto.randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var Pt="status@broadcast",Jo=[{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,i){return new n(e,Ur(t,r,s,i))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=mr(wr(e),t):this.internal.content=At(e),this}image(e,t){return this.internal.pendingContent=fe(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=cr(e,t),this}document(e,t){return this.internal.pendingContent=Mr(e,t),this}sticker(e,t){return this.internal.pendingContent=Wr(e,t),this}buttons(e,t){return this.internal.content=St(e,t),this}carousel(e,t){return this.internal.content=pr(e,t),this}list(e){return this.internal.content=Rr(e),this}poll(e,t,r){return this.internal.content=Dr(e,t,r),this}location(e,t,r){return this.internal.content=_r(e,t,r),this}contact(e){return this.internal.content=vr(e),this}template(e){return this.internal.content=jr(e),this}event(e){return this.internal.content=br(e),this}groupInvite(e){return this.internal.content=Cr(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=Tr(e,t):this.internal.pendingContent=xr(e,t),this}product(e){return this.internal.pendingContent=Br(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.disappearingSeconds===void 0){let c=this.internal.inheritDisappearing?.(this.internal.recipient);c!==void 0&&c>0&&(this.internal.disappearingSeconds=c);}if(this.internal.statusJidList!==void 0&&this.internal.recipient!==Pt)throw new p("INVALID_RECIPIENT",`audience() only applies to ${Pt}, not ${this.internal.recipient}`);if(this.internal.albumItems){let c={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(c.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(c.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(c.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(c.disappearingSeconds=this.internal.disappearingSeconds),ir(this.socket,this.internal.recipient,this.internal.albumItems,c)}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 c=s[_e];if(typeof c=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${c} can only be sent to a group jid ending in @g.us`);let l=s[Mt],u=l!==void 0?await this.buildStatusMedia(l):i,w=s[cn],M=s[un];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===Pt&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${Pt} 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 d;try{d=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(c){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:c})}if(!d?.key)throw new p("SEND_FAILED","socket returned no message key");return d.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await O(t.src),s=await dc.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 dc.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=dc.normalizeMessageContent(e),i=s==null?void 0:dc.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 d={userJid:this.socket.user?.id??""},c=this.internal.quoted;c!==void 0&&c.message!=null&&(d.quoted=c),this.internal.disappearingSeconds!==void 0&&(d.ephemeralExpiration=this.internal.disappearingSeconds);let l=dc.generateWAMessageFromContent(this.internal.recipient,e,d);if(s&&l.message!=null&&qr(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:Jo}:{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 Ne=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=At(e),this}image(e,t){return this.pendingContent=fe(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 gn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},fn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},hn=async(n,e,t={})=>{let r=gn(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);},yn=async(n,e,t)=>{let r=gn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return fn(s)},wn=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 fn(i)},kt=async(n,e,t,r={})=>{let s=gn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return fn(o)};var Vo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Le=n=>Vo.test(n),vn=async(n,e,t,r=Ho)=>{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 d=(await n.onWhatsApp(e))?.find(c=>c.exists&&c.jid);if(!d)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,d.jid),d.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Ho=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 De=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 Be=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 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("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 Fe=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 je=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 $r=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new I("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Ue=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=$r(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 $r(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 qe=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 Ke=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 zo=n=>{let e=n[0];return e==="{"||e==="["},Yo=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},Zo=n=>n===" "||n===" "||n===`
|
|
11
11
|
`||n==="\r",Qo=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let d=n[a];if(s){t+=d,s=false,i=true,o=false;continue}if(d==="\\"&&r!==null){s=true;continue}if(r!==null){d===r?r=null:t+=d,o=false;continue}if((d==='"'||d==="'")&&o){r=d,i=true,o=false;continue}if(Zo(d)){i&&(e.push(t),t="",i=false),o=true;continue}t+=d,i=true,o=false;}return i&&e.push(t),e},Xo=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},ea=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function Mn(n,e){let t=Xo(n,e);if(t===null)return ea(n);let r=n.slice(t.length),s=Qo(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 d=s[a];if(d!==void 0){if(d.startsWith("--")){let c=d.slice(2);if(c.length===0){i.args.push(d);continue}let l=c.indexOf("=");if(l!==-1){let w=c.slice(0,l),M=c.slice(l+1);i.flags[w]=M;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[c]=u,a+=1):i.flags[c]=true;continue}if(!o&&zo(d)){let c=Yo(d);c.ok&&(i.json=c.value,o=true);}i.args.push(d);}}return i}var Gr=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},ve=n=>n.join(" "),Jr=n=>[n.name,...n.aliases??[]].join("|"),ta=n=>{let e={};return n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},$e=class{paths=new Map;defs=[];maxDepth=1;register(e,t){let r=typeof e=="string"?e:Jr(e);if(r.trim().length===0)throw new _("INVALID_COMMAND_NAME","command spec must not be empty");let s=r.split("|").map(d=>Gr(d)),i=s[0],o=s.slice(1).map(d=>ve(d)),a={name:ve(i),aliases:o,parts:i,handler:t,meta:typeof e=="string"?{}:ta(e)};for(let d of s){let c=ve(d);if(this.paths.has(c))throw new _("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let d of s)this.paths.set(ve(d),a),d.length>this.maxDepth&&(this.maxDepth=d.length);this.defs.push(a);}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 r=(typeof e=="string"?e:Jr(e)).split("|").map(a=>Gr(a)),s=ve(r[0]),i=this.paths.get(s);if(i===void 0)return;for(let a of [i.parts,...i.aliases.map(d=>d.split(" "))])this.paths.delete(ve(a));let o=this.defs.indexOf(i);o>=0&&this.defs.splice(o,1),this.maxDepth=this.defs.reduce((a,d)=>Math.max(a,d.parts.length),1);}list(){return [...this.defs]}describe(){return this.defs.map(e=>({name:e.name,aliases:[...e.aliases],...e.meta}))}};async function Sn(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(d){throw s.error=d,s.thrown=true,d}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(d){throw s.thrown||d instanceof _?d:new _("MIDDLEWARE_ERROR","middleware threw during execution",{cause:d})}};await i(0);}var bn=new Map,na=(n,e)=>`${n}\0${e}`,ra=()=>{bn.clear();},Cn=async(n,e,t)=>{if((n.group===true||n.admin===true)&&!e.isGroup)return {reason:"group-only"};if(n.private===true&&e.isGroup)return {reason:"private-only"};if(n.admin===true){let s=e.roomId;if(s===null)return {reason:"admin-only"};if(!await t.isAdmin(s,e.senderId))return {reason:"admin-only"}}if(n.cooldown!==void 0&&n.cooldown>0){let s=na(e.command,e.senderId),i=bn.get(s),o=t.now(),a=n.cooldown*1e3;if(i!==void 0&&o-i<a)return {reason:"cooldown",retryIn:Math.ceil((a-(o-i))/1e3)};bn.set(s,o);}return null};function An(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=Mn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0){i.name!==void 0&&i.name.length>0&&n.onNotFound?.(i.name,s);return}let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},d=n.buildContext(a,s);(async()=>{let l=await Cn(o.def.meta,d,{isAdmin:n.isAdmin??(async()=>false),now:()=>Date.now()});if(l!==null){n.onBlocked?.(l,d);return}await Sn(n.middleware,d,()=>o.def.handler(d));})().catch(l=>{let u=l instanceof _?l:new _("HANDLER_ERROR","command handler failed",{cause:l});n.onError?.(u,d)!==true&&n.logger.error(u,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Se=new Map,Hr=n=>n!=null&&typeof n=="object"?n:null,zr=n=>Array.isArray(n.content)?n.content.map(Hr).filter(e=>e!==null):[],Vr=(n,e)=>zr(n).find(t=>t.tag===e),Me=n=>typeof n=="string"&&n.length>0?n:void 0,Pn=n=>{if(n===void 0)return;let e=Number.parseInt(n,10);return Number.isFinite(e)?e:void 0},sa=(n,e)=>{if(Object.keys(e).length!==0){if(Se.size>=64){let t=Se.keys().next().value;t!==void 0&&Se.delete(t);}Se.set(n,e);}},Yr=n=>{let e=Hr(n);if(e===null||e.tag!=="call")return false;let t=zr(e).find(v=>v.tag==="offer"),r=Me(t?.attrs?.["call-id"]);if(t===void 0||r===void 0)return false;let s={},i=Me(e.attrs?.platform),o=Me(e.attrs?.version),a=Me(e.attrs?.notify),d=Me(t.attrs?.caller_country_code),c=Me(t.attrs?.caller_pn);i!==void 0&&(s.platform=i),o!==void 0&&(s.appVersion=o),a!==void 0&&(s.name=a),d!==void 0&&(s.countryCode=d),c!==void 0&&(s.phoneJid=c);let l=Pn(Vr(t,"net")?.attrs?.medium);l!==void 0&&(s.networkMedium=l);let u=Vr(t,"video"),w=Pn(u?.attrs?.screen_width),M=Pn(u?.attrs?.screen_height);return w!==void 0&&M!==void 0&&(s.screen={width:w,height:M}),sa(r,s),true},Zr=n=>{let e=Se.get(n);return e!==void 0&&Se.delete(n),e};var Qr=["text","image","video","audio","document","sticker","reaction","edit","delete","poll-vote","button-click","list-select","mention","mention-all","group-update","group-join","group-leave","member-tag","call-incoming","call-ended","history-sync","limited","presence","newsletter"],Xr=n=>n;var ia=(n,e)=>{let t=oe__default.default.dirname(oe__default.default.resolve(n)),r=e===void 0?void 0:oe__default.default.resolve(e);if(r!==void 0){let i=oe__default.default.relative(r,t);return i.length===0||i.startsWith("..")?void 0:i.split(oe__default.default.sep)[0]}let s=oe__default.default.basename(t);return s.length>0?s:void 0},oa=n=>n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),aa=n=>{let e={name:n.name};return n.aliases!==void 0&&(e.aliases=n.aliases),n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},da=(n,e)=>{let t=n.message;typeof t=="function"&&e.command(aa(n),s=>t(s,e));let r=n;for(let s of Qr){let i=r[oa(s)];typeof i=="function"&&e.on(s,o=>{i(o,e);});}},Ge=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,r){if(typeof e?.name!="string"){this.logger?.warn({file:t},"plugin: invalid shape (needs a name); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let s=[],i=ia(t,r),o={client:this.host,logger:this.logger,pluginDir:oe__default.default.dirname(t),category:i,command:(a,d)=>{let c=typeof a=="string"||a.category!==void 0||i===void 0?a:{...a,category:i};this.host.command(c,d),s.push(()=>this.host.unregisterCommand(c));},use:a=>{this.host.use(a),s.push(()=>{this.host.unuse(a);});},on:(a,d)=>{let c=this.host.on(a,d);return s.push(c),c},once:(a,d)=>{let c=false,l=this.host.on(a,u=>{c||(c=true,l(),d(u));});return s.push(l),l}};try{da(e,o);let a=await e.setup?.(o);typeof a=="function"&&s.push(a);}catch(a){for(let d of [...s].reverse())try{await d();}catch{}this.logger?.error({err:a,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:s});}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 ua=/\.(ts|js|mjs|cjs)$/,pa=/(\.d\.ts$|^_|[/\\]_)/;async function En(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=oe__default.default.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await En(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function ts(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"?s:void 0}catch{return}}var Je=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=oe__default.default.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??ua,this.ignore=e.options.ignore??pa,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await En(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 ts(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,this.dir);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=oe__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 ma=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ae=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??ma;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 ga={"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},fa=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function Tn(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??fa,i={...ga,...n.intervalsMs??{}},o=new Map,a=new Map,d=async(c,l)=>{let u=i[c]??0,w=o.get(c);if(w!==void 0&&u>0){let M=u-(r()-w);M>0&&await s(M);}return o.set(c,r()),l()};return {run(c,l){if(!t)return l();let w=(a.get(c)??Promise.resolve()).then(()=>d(c,l),()=>d(c,l));return a.set(c,w.then(()=>{},()=>{})),w}}}var ha={maxRetries:0,backoffMs:()=>0},ya=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),Ve=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??ha,this.sleep=t.sleep??ya;}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 wa=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function In(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 ae({perSec:i},o),d=r.retry,c=t.sleep?{sleep:t.sleep}:{},l=d?new Ve({concurrency:1,retry:d},c):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:wa(P)}),w+=1,r.onProgress?.(w,u,M,false);}}return s}var va=1e3,He=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??va,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 Sa={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},ba=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",ze=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??Sa,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),ba(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,d)=>{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=d?{recipient:o,content:a,options:d}:{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 ns(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((d,c)=>Number(c.messageTimestamp??0)-Number(d.messageTimestamp??0));for(let d=0;d<a.length;d+=1){let c=a[d],l=Number(c.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,w=e.maxPerChat!==void 0&&d>=e.maxPerChat;(u||w)&&(await n.deleteMessage(c.key),r+=1);}}return r}var Ye=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"?ns(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 rs=n=>(n.split(/[:@]/)[0]??"").replace(/\D/g,""),Ze=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=rs(e);return t.some(s=>s===e||rs(s)===r)}return await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var Ca={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Aa=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Ca[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},Et=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=Aa(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")}},ss=(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 be=n=>typeof n!="string"||n.length===0?null:dc.jidNormalizedUser(n),Z=n=>typeof n=="string"&&n.length>0?n:void 0,Ea=["@s.whatsapp.net","@c.us"],Tt=n=>n.endsWith("@lid"),is=n=>Ea.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 d=i!==null?[r,i]:[r],c=d.find(Tt),l=d.find(is);c!==void 0&&(a.lid=c),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Z(e);return u!==void 0&&(a.pushName=u),a},os=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},Qe=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 Ce=n=>dc.isJidGroup(n)===true,Ae=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,as=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],ds=["groupStatusMessage","groupStatusMessageV2"],cs=(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 as){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 as){let i=g(g(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var us=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},ls=(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},ps=n=>(ls(n).toString(16).padStart(8,"0")+ls(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),ms=n=>ps(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),gs=(n,e)=>ps(`${n??""}|${e}`),fs=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},hs=n=>{let e=dc.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"},Ia=n=>n.trim().endsWith("?"),xa=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Oa=(n,e)=>{if(e.length===0)return false;let t;try{t=dc.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return dc.jidNormalizedUser(r)===t}catch{return r===n}})},Ra=(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)}},_a=0,Na=14,La=1,Da=2,Ba=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===Na,isDeleted:r===_a,isPinned:s===La,isUnPinned:s===Da,isBot:g(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:cs(e,ds)}},xn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Ce(e),r=Ba(n.message),s=d=>n.lidMap!=null&&d.endsWith("@lid")?n.lidMap.get(d)??d:d,i=s(n.sender.pn??n.sender.jid),o=t?e?dc.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(dc.jidNormalizedUser(e)):i,a={uniqueId:ms(n.key),staticId:gs(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(dc.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:hs(n.sender.deviceJid??n.sender.jid),timestamp:fs(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:us(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:Ia(n.text),isPrefix:xa(n.text,n.prefixes),isTagMe:Oa(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:Ra(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"},vs=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},Ms=n=>{let e=g(n.message);if(e==null)return n;let t=Pe(e);return t===e?n:{...n,message:t}},Wa=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(`
|
|
12
12
|
`).trim();return i.length>0?i:null},Fa=n=>{let e=g(n.templateMessage),t=g(e?.hydratedTemplate)??g(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},ja=n=>Q(g(n.pollCreationMessage)?.name,g(n.pollCreationMessageV2)?.name,g(n.pollCreationMessageV3)?.name),Ua=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},qa=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},Ss=n=>Q(n.conversation,g(n.extendedTextMessage)?.text,Wa(n),S(g(g(n.interactiveMessage)?.body)?.text),g(n.buttonsMessage)?.contentText,g(n.listMessage)?.description,Fa(n),ja(n),Ua(n),qa(n)),Ka=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),$a=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=Ae(n);return typeof e=="number"?e:null},Ga=[["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"]],bs=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 d=g(g(n.productMessage)?.product);if(g(n.productMessage)!=null){let m=S(g(n.productMessage)?.businessOwnerJid),f=T(d?.priceAmount1000);return {type:"product",productId:S(d?.productId),title:S(d?.title),description:S(d?.description),price:f!=null?f/1e3:null,currency:S(d?.currencyCode),retailerId:S(d?.retailerId),url:S(d?.url),businessOwnerId:m}}let c=g(n.orderMessage);if(c!=null){let m=T(c.totalAmount1000),f={1:"inquiry",2:"accepted",3:"declined"},b=c.status;return {type:"order",orderId:S(c.orderId),title:S(c.orderTitle),itemCount:T(c.itemCount),total:m!=null?m/1e3:null,currency:S(c.totalCurrencyCode),status:typeof b=="number"?f[b]??null:S(b),message:S(c.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 et=n=>{let e=g(n.message);if(e==null)return null;let t=Pe(e);return Ss(t)??Ka(t)??$a(t)},nt=n=>{let e=g(Ms(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},Ja=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Rn[e]];return r==null||typeof r!="object"?null:r},Va=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},Ha=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,Cs=n=>As(n,nt(n))??void 0,za=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,As=(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},Ya=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},Ps=n=>typeof n=="string"&&n.length>0?n:void 0,Za=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=Ps(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},Qa=n=>{let e=Ps(g(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},de=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 Ga)if(t[r]!=null)return s;return "text"},ys=(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))},Xa=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=et(v)??"",y=ce(v,e,de(v.message),P,tt(v,e),s);if(y!==null)return y}}let a=os(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 d=a.key.participant,c=Ce(t),l=a.sender?.pushName;!c&&(d==null||d.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&ys({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 d=="string"&&(e.selfJid.length>0&&It(d,e.selfJid)||e.selfLid!=null&&It(d,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&&ys(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=et(w)??"";return ce(w,e,de(u),M,tt(w,e),s)}catch{return null}},ks=n=>Qe(nt(n)).mentionedJids,ed=n=>{try{return dc.jidNormalizedUser(n)}catch{return n}},Es=(n,e)=>n.map(t=>{let r=ed(t);return e.lidMap?.get(r)??r}),ws=n=>(n.split("@")[0]??"").split(":")[0]??"",td=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[ws(s),ws(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},ce=(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 d=vs(o);if(d.length===0)return null;let c=nt(n),l=Ce(d),u=d.endsWith("@broadcast"),w=d.endsWith("@newsletter"),M=c?.isForwarded===true||(c?.forwardingScore??0)>0,v=Va(n),P=Ha(n,c),y=e.channelId??"",m=e.receiverId??"",f=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(d):Promise.resolve(null):Promise.resolve(a.pushName??null)),k=e.resolveReceiverName??(()=>Promise.resolve(null)),F=()=>Xa(c,e,d,a,b,o.fromMe===true),tn=d.length>0?d:a.pn??a.jid,nn=(sn,Yi)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(tn,sn,Yi,n),rn=sn=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,sn),Hi=Es(Qe(c).mentionedJids,e),zi=td(r,e.lidMap),Gn=Za(c),Jn=Qa(n),Vn={message:n,key:o,channelId:y,receiverId:m,selfJid:e.selfJid,text:zi,chatType:t,sender:a,mentions:Hi,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:w,isOld:e.isOld===true,prefixes:f,forwardCount:za(c?.forwardingScore,0),ephemeralDuration:As(n,c),addressingMode:o.addressingMode==="lid"?"lid":"pn",mentionedGroups:Ya(c),...Gn!==void 0?{ad:Gn}:{},...Jn!==void 0?{business:Jn}:{},...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:k,resolveReplied:F,reply:nn,react:rn},Hn=s!==void 0?{...Vn,media:s}:Vn;return xn(e.citationConfig!==void 0?{...Hn,citationConfig:e.citationConfig}:Hn)},nd=["image","video","audio","document","sticker"],Ts=(n,e,t)=>{let r=Ms(n),s=Ja(r,e);if(s===null)return null;let i=Et(r,e,t.logger),o=ss(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}},tt=(n,e)=>{let t=g(n.message);if(t==null)return;let r=de(n.message);return nd.includes(r)?Ts(n,r,e)??void 0:bs(Pe(t))??void 0},Is=(n,e)=>{if(g(n.message)==null)return null;let r=de(n.message),s=tt(n,e),i=et(n)??"";return i===""&&s===void 0?null:ce(n,e,r,i,s)},xs=(n,e)=>{let t=g(n.message);if(t==null)return null;let r=Pe(t),s=Ss(r),i=bs(r)??void 0;return s===null&&i===void 0?null:ce(n,e,de(n.message),s??"",i)},rt=(n,e,t)=>{let r=Ts(e,n,t);return r===null?null:ce(e,t,n,r.caption??"",r)},Os=(n,e)=>rt("image",n,e),Rs=(n,e)=>rt("video",n,e),_s=(n,e)=>rt("audio",n,e),Ns=(n,e)=>rt("document",n,e),Ls=(n,e)=>rt("sticker",n,e),It=(n,e)=>{try{return dc.jidNormalizedUser(n)===dc.jidNormalizedUser(e)}catch{return n===e}},Ds=(n,e)=>{if(n.key==null)return null;let r=nt(n),s=Qe(r).mentionedJids;if(s.length===0)return null;let i=Es(s,e);if(!(i.some(u=>It(u,e.selfJid))||e.selfLid!=null&&s.some(u=>It(u,e.selfLid)))||g(n.message)==null)return null;let d=et(n)??"",c=tt(n,e),l=ce(n,e,de(n.message),d,c);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},Bs=(n,e)=>{let t=n.key;if(t==null)return null;let r=vs(t);if(r.length===0||!Ce(r))return null;let{mentionAll:s}=Qe(nt(n));if(!s||g(n.message)==null)return null;let o=et(n)??"",a=tt(n,e),d=ce(n,e,de(n.message),o,a);return d===null?null:{...d,isMentionAll:true,selfJid:e.selfJid}};var le="[zaileys]",rd="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 Fs(n){switch(n.kind){case "connecting":return `${le} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${le} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${le} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${le} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${le} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
|
|
13
13
|
${le} ${rd}`:t}case "disconnect":return n.willReconnect?null:`${le} Disconnected (${n.reason}).`;default:return null}}var Ws=false,sd=["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:"],id=n=>typeof n[0]=="string"&&sd.some(e=>n[0].startsWith(e));function js(){if(Ws)return;Ws=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{id(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 ad="./.zaileys/auth",dd=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),it=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",Ot=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??ad;}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,dc.BufferJSON.reviver);}catch(o){if(it(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],d=this.signalPath(r,o);a===null?t.push(fs$1.promises.unlink(d).catch(c=>{if(!it(c))throw new h("STORE_WRITE_FAILED",`failed to unlink ${d}`,{cause:c})})):a!==void 0&&t.push(this.atomicWrite(d,JSON.stringify(a,dc.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(!it(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,dc.BufferJSON.reviver)}catch(e){if(it(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,dc.BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await fs$1.promises.unlink(this.credsPath());}catch(e){if(!it(e))throw new h("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return oe__default.default.join(this.basePath,"creds.json")}signalDir(e){return oe__default.default.join(this.basePath,"signal",String(e))}signalPath(e,t){return oe__default.default.join(this.signalDir(e),`${dd(t)}.json`)}async atomicWrite(e,t){let r=oe__default.default.join(oe__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 Us(n,e){let t=n.signal,s=dc.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 d={},c={};for(let l of a)c[l]=null;d[o]=c,await s.set(d);},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 qs(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 ld=429;function Ks(n){if(n===ld)return "rate-limited";switch(n){case dc.DisconnectReason.loggedOut:return "logged-out";case dc.DisconnectReason.forbidden:return "forbidden";case dc.DisconnectReason.connectionLost:return "connection-lost";case dc.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case dc.DisconnectReason.connectionClosed:return "connection-closed";case dc.DisconnectReason.connectionReplaced:return "connection-replaced";case dc.DisconnectReason.badSession:return "bad-session";case dc.DisconnectReason.unavailableService:return "unavailable-service";case dc.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function ot(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Rt(n){return n==="rate-limited"}function $s(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function Fg(n){return !ot(n)}var _t={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},ud=3e5;function Gs(n={}){let e=n.enabled??_t.enabled,t=n.maxQrAttempts??_t.maxQrAttempts,r=n.maxPairingAttempts??_t.maxPairingAttempts,s=n.pairingCooldownMs??_t.pairingCooldownMs,i=0,o=0,a=0,d=w=>w<=0?0:Math.min(s*w,ud);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=d(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 pd=/[\s\-()+]/g;function md(n){return typeof n!="string"?"":n.replace(pd,"")}function gd(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=md(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 Js(n){let e=gd(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 hd(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{fd__default.default.generate(n,{small:true},t=>e(t));})}async function Vs(n,e=t=>{process.stdout.write(t);}){let t=await hd(n);e(t+`
|
|
@@ -17,8 +17,8 @@ ${le} ${rd}`:t}case "disconnect":return n.willReconnect?null:`${le} Disconnected
|
|
|
17
17
|
VERSION:3.0
|
|
18
18
|
FN:${i}${o?`
|
|
19
19
|
${o}`:""}
|
|
20
|
-
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Qd=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:X(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Xd=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:Hd(n)??zd(n)??Yd(n)??Zd(n);if(t===null)return null;let r=Qd(t,n),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:X(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},ec=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?X(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},tc=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Ut(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:X(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},nc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Ut(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:X(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},rc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=X(n.from),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ki(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=Vd(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=rc(l,c);if(u){t.push(u);continue}let w=tc(l,c);if(w){i.push(w);continue}let M=nc(l,c);if(M){o.push(M);continue}let v=Xd(l,c);v&&e.push(v);}for(let l of c.statuses??[]){let u=ec(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var Ei=3,Fn=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function Ti(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=Fn(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(w=>({id:w.id??"",title:w.title??"",description:w.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>Ei)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${Ei} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=Fn(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?Fn(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ee=class{ev=new events.EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=jt(e);}get apiVersion(){return this.options.apiVersion??Ft}get baseUrl(){return this.options.baseUrl??Wn}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=Ti(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...V(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...V(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...V(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new C("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new C("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await ge(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ki(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=bi(e,t,r);if(s===null){let d=Ci(t);if(d){let c=await Ai(this.graph,this.options.phoneNumberId,d);s={...V(e,d.kind,r),[d.kind]:Pi(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var ut=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=jt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var ac=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=crypto.createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:crypto.timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function jn(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!ac(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var uc="default",pc="qr",xi=6e4,mc=2,gc=3e3,fc="29829202653362039",hc=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},Oi=class extends Wt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=zs();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:_n(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?Bn(e.cloud):void 0,this.sessionId=e.sessionId??uc,this.logger=_n(e.logger),this.authType=e.authType??pc,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&js(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ot({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Lt,this.reconnectStrategy=Hs(this.reconnectOptions),this.authGuard=Gs(e.authGuard),this.operationGuard=Tn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ae({perSec:t}):void 0,this.commandPrefixes=yc(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new Ze(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&ye.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof dc.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=dc.fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=Fs(e);t&&process.stderr.write(`${t}
|
|
21
|
-
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(new Error('phoneNumber is required when authType is "pairing"'));if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??dc.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,client:this,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r):Y.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:dc.S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var Ri=class{credsBlob;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
20
|
+
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Qd=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:X(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Xd=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:Hd(n)??zd(n)??Yd(n)??Zd(n);if(t===null)return null;let r=Qd(t,n),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:X(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},ec=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?X(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},tc=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Ut(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:X(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},nc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Ut(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:X(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},rc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=X(n.from),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ki(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=Vd(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=rc(l,c);if(u){t.push(u);continue}let w=tc(l,c);if(w){i.push(w);continue}let M=nc(l,c);if(M){o.push(M);continue}let v=Xd(l,c);v&&e.push(v);}for(let l of c.statuses??[]){let u=ec(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var Ei=3,Fn=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function Ti(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=Fn(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(w=>({id:w.id??"",title:w.title??"",description:w.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>Ei)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${Ei} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=Fn(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?Fn(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ee=class{ev=new events.EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=jt(e);}get apiVersion(){return this.options.apiVersion??Ft}get baseUrl(){return this.options.baseUrl??Wn}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=Ti(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...V(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...V(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...V(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new C("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new C("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await ge(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ki(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=bi(e,t,r);if(s===null){let d=Ci(t);if(d){let c=await Ai(this.graph,this.options.phoneNumberId,d);s={...V(e,d.kind,r),[d.kind]:Pi(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var ut=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=jt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var ac=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=crypto.createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:crypto.timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function jn(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!ac(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var uc="default",pc="qr",xi=6e4,mc=2,gc=3e3,fc="29829202653362039",hc=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},Oi=class extends Wt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=zs();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;chatExpiration=new Map;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:_n(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?Bn(e.cloud):void 0,this.sessionId=e.sessionId??uc,this.logger=_n(e.logger),this.authType=e.authType??pc,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&js(),this.on("message",r=>this.rememberChatExpiration(r)),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ot({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Lt,this.reconnectStrategy=Hs(this.reconnectOptions),this.authGuard=Gs(e.authGuard),this.operationGuard=Tn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ae({perSec:t}):void 0,this.commandPrefixes=yc(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new Ze(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&ye.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof dc.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=dc.fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=Fs(e);t&&process.stderr.write(`${t}
|
|
21
|
+
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(new Error('phoneNumber is required when authType is "pairing"'));if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??dc.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,client:this,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r,s):Y.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:dc.S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var Ri=class{credsBlob;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
22
22
|
CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new h("STORE_CONNECTION_FAILED","failed to migrate sqlite schema",{cause:r})}this.db=t,this.prepared={readCreds:t.prepare("SELECT data FROM auth_creds WHERE id = ?"),writeCreds:t.prepare("INSERT INTO auth_creds(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data"),deleteCreds:t.prepare("DELETE FROM auth_creds WHERE id = ?"),writeSignal:t.prepare("INSERT INTO auth_signal(type, id, data) VALUES(?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET data = excluded.data"),deleteSignal:t.prepare("DELETE FROM auth_signal WHERE type = ? AND id = ?"),clearSignal:t.prepare("DELETE FROM auth_signal"),clearCreds:t.prepare("DELETE FROM auth_creds")};}encodeBlob(e){try{return Buffer.from(JSON.stringify(e,dc.BufferJSON.replacer),"utf8")}catch(t){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:t})}}parseBlob(e){try{let t=Buffer.isBuffer(e)?e.toString("utf8"):Buffer.from(e).toString("utf8");return JSON.parse(t,dc.BufferJSON.reviver)}catch(t){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var $t,Mc=async()=>($t||($t=import('pg').then(n=>n).catch(n=>{throw $t=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),$t),Sc="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",bc="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",Wi=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","PostgresAuthStore is closed");if(this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Mc(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(Sc),await e.query(bc);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,d)=>`$${d+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let d=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(d.toString("utf8"),dc.BufferJSON.reviver);}return s}catch(i){throw i instanceof h?i:new h("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a];if(d===null)r.push({kind:"delete",type:String(i),id:a});else if(d!==void 0){let c=Buffer.from(JSON.stringify(d,dc.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:c});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to write signal rows",{cause:i})}finally{s?.release();}},delete:async(e,t)=>{let r=await this.ensureReady();if(t.length!==0)try{let s=t.map((i,o)=>`$${o+2}`).join(", ");await r.query(`DELETE FROM zaileys_auth_signal WHERE type = $1 AND id IN (${s})`,[String(e),...Array.from(t)]);}catch(s){throw new h("STORE_WRITE_FAILED","failed to delete signal rows",{cause:s})}},clear:async()=>{let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_auth_signal"),await t.query("DELETE FROM zaileys_auth_creds"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to clear auth tables",{cause:r})}finally{t?.release();}},close:async()=>{if(this.closed)return;this.closed=true;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};creds={readCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'default'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,dc.BufferJSON.reviver)}catch(t){throw t instanceof h?t:new h("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,dc.BufferJSON.replacer);await t.query("INSERT INTO zaileys_auth_creds(id, data) VALUES ('default', $1::jsonb) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data",[r]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to write creds",{cause:r})}},deleteCreds:async()=>{let e=await this.ensureReady();try{await e.query("DELETE FROM zaileys_auth_creds WHERE id = 'default'");}catch(t){throw new h("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var Cc="zaileys",Ac=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],Pc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Fi=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??Cc,this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let d=i[a];d!=null&&(o[t[a]]=JSON.parse(d,dc.BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a],c=this.signalKey(i,a),l=this.indexKey(i);d===null?(r.del(c),r.sRem(l,a)):d!==void 0&&(r.set(c,JSON.stringify(d,dc.BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of Ac){let s=this.indexKey(r),i=await this.runRead(()=>e.sMembers(s));for(let o of i)t.del(this.signalKey(r,o));t.del(s);}t.del(this.credsKey()),await this.runWrite(()=>t.exec());},close:async()=>{await this.shutdown();}};creds={readCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));if(t!=null)return JSON.parse(t,dc.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,dc.BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));}};credsKey(){return `${this.namespace}:auth:creds`}signalKey(e,t){return `${this.namespace}:auth:signal:${String(e)}:${t}`}indexKey(e){return `${this.namespace}:auth:signal-index:${String(e)}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new h("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Pc(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","redis write failed",{cause:t})}}async shutdown(){if(!this.closed){if(this.closed=true,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","RedisAuthStore is closed")}};var kc="zaileys",pt={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Ec=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Te=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??kc,this.externalClient=e.client,this.url=e.url;}async get(e){if(this.assertOpen(),e.length===0)return new Map;let t=await this.ensureClient(),r=await this.runRead(()=>t.query(pt.get,{namespace:this.namespace,keys:[...e]})),s=new Map;for(let i of r??[])s.set(i.key,i.value);return s}async set(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.set,{namespace:this.namespace,items:[...e]}));}async del(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.clear,e===void 0?{namespace:this.namespace}:{namespace:this.namespace,prefix:e}));}async list(e,t){this.assertOpen();let r=await this.ensureClient(),s={namespace:this.namespace,prefix:e};return typeof t?.before=="number"&&(s.before=t.before),typeof t?.limit=="number"&&(s.limit=t.limit),await this.runRead(()=>r.query(pt.list,s))??[]}close(){this.closed=true,this.client=void 0;}async ensureClient(){if(this.externalClient)return this.externalClient;if(this.client)return this.client;let e="convex/browser",t;try{t=await import(e);}catch(r){throw Ec(r)?new h("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load convex module",{cause:r})}return this.client=new t.ConvexHttpClient(this.url),this.client}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","Convex store is closed")}};var Vt="creds",Tc="signal:",mt=(n,e)=>`${Tc}${n}:${e}`,ji=class{creds;signal;kv;constructor(e){this.kv=new Te(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([Vt])).get(Vt);return s===void 0?void 0:JSON.parse(s,dc.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:Vt,value:JSON.stringify(r,dc.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([Vt]);}},this.signal={async read(r,s){let i=s.map(d=>mt(r,d)),o=await t.get(i),a={};for(let d of s){let c=o.get(mt(r,d));a[d]=c===void 0?void 0:JSON.parse(c,dc.BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let d of Object.keys(a)){let c=a[d];c==null?i.push(mt(o,d)):s.push({key:mt(o,d),value:JSON.stringify(c,dc.BufferJSON.replacer)});}}s.length>0&&await t.set(s),i.length>0&&await t.del(i);},async delete(r,s){await t.del(s.map(i=>mt(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var Ht=null,Ic=async()=>{if(Ht)return Ht;try{return Ht=(await import('better-sqlite3')).default,Ht}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},zt=n=>{try{return Buffer.from(JSON.stringify(n,dc.BufferJSON.replacer),"utf8")}catch(e){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},pe=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,dc.BufferJSON.reviver)}catch(e){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Ui=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;constructor(e){this.options=e;}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe?1:0,o=Number(e.messageTimestamp??0);t.upsertMessage.run(r,s,i,o,zt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?pe(r.data):void 0}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=t?.before;return (typeof i=="number"?r.listMessages.all(e,i,s):r.listMessages.all(e,Number.MAX_SAFE_INTEGER,s)).map(a=>pe(a.data))}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived?1:0;t.upsertChat.run(r,s,zt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?pe(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>pe(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,zt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?pe(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>pe(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,zt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?pe(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
23
23
|
SELECT rowid FROM (
|
|
24
24
|
SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
|
package/dist/index.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import dc,{prepareWAMessageMedia,generateWAMessageContent,normalizeMessageConten
|
|
|
7
7
|
`)}:{type:"code",content:u.join(`
|
|
8
8
|
`)});continue}let c=e[i+1];if(o.includes("|")&&c!==void 0&&c.includes("|")&&So.test(c)){s();let u=[hr(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)u.push(hr(e[i])),i++;t.push({type:"table",rows:u});continue}let l=fr.exec(o);if(l){s();let u=[l[1]];for(i++;i<e.length;){let w=fr.exec(e[i]);if(!w)break;u.push(w[1]),i++;}t.push({type:"image",url:u.length===1?u[0]:u});continue}r.push(o),i++;}return s(),t};var vr=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new p("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var Mr=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new p("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await O(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var Sr=(n,e)=>{let t=n instanceof Date?n:new Date(n);if(Number.isNaN(t.getTime()))throw new p("INVALID_OPTIONS",`event() ${e} must be a valid Date or epoch ms`);return new Date(Math.floor(t.getTime()/1e3)*1e3)},br=n=>{if(n==null||typeof n.name!="string"||n.name.trim().length===0)throw new p("INVALID_OPTIONS","event() requires a non-empty name");return {event:{name:n.name,startDate:Sr(n.startAt,"startAt"),...n.description!==void 0?{description:n.description}:{},...n.endAt!==void 0?{endDate:Sr(n.endAt,"endAt")}:{},...n.call!==void 0?{call:n.call}:{},...n.canceled!==void 0?{isCancelled:n.canceled}:{},...n.location!==void 0?{location:{degreesLatitude:n.location.latitude,degreesLongitude:n.location.longitude,...n.location.name!==void 0?{name:n.location.name}:{},...n.location.address!==void 0?{address:n.location.address}:{}}}:{}}}};var Cr=n=>{if(n==null||typeof n.jid!="string"||!n.jid.endsWith("@g.us"))throw new p("INVALID_OPTIONS","groupInvite() requires a group jid ending in @g.us");if(typeof n.code!="string"||n.code.trim().length===0)throw new p("INVALID_OPTIONS","groupInvite() requires an invite code");let e={inviteCode:n.code,inviteExpiration:n.expiresAt??Math.floor(Date.now()/1e3)+3*86400,groupJid:n.jid,groupName:n.subject??"",caption:n.caption??""};return n.thumbnail!==void 0&&(e.jpegThumbnail=n.thumbnail),{[R]:{groupInviteMessage:e}}};var Pr=4294967295,To=/^[0-9a-fA-F]{3}$/,Io=/^[0-9a-fA-F]{6}$/,xo=/^[0-9a-fA-F]{8}$/,kr={system:0,"system-text":1,"fb-script":2,"system-bold":6,morningbreeze:7,calistoga:8,exo2:9,courierprime:10},we=n=>{throw new p("INVALID_OPTIONS",n)},Oo=n=>{if(typeof n=="number"){if(!Number.isInteger(n))return we(`groupStatus() backgroundColor must be an integer, got ${n}`);let t=n<0?Pr+n+1:n;return t<0||t>Pr?we(`groupStatus() backgroundColor is outside the ARGB range, got ${n}`):t}if(typeof n!="string")return we("groupStatus() backgroundColor must be a hex string or an integer");let e=n.trim().replace("#","");if(xo.test(e))return Number.parseInt(e,16);if(Io.test(e))return Number.parseInt(`FF${e}`,16);if(To.test(e)){let t=[...e].map(r=>`${r}${r}`).join("");return Number.parseInt(`FF${t}`,16)}return we(`groupStatus() backgroundColor must be #RGB, #RRGGBB or #AARRGGBB, got ${n}`)},Ro=n=>{if(typeof n=="number")return !Number.isInteger(n)||n<0?we(`groupStatus() font must be a non-negative integer, got ${n}`):n;let e=kr[n];return e===void 0?we(`groupStatus() font must be one of ${Object.keys(kr).join(", ")}, got ${String(n)}`):e},Tr=(n,e)=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","groupStatus() requires a non-empty string");let t={text:n};return e?.backgroundColor!==void 0&&(t.backgroundArgb=Oo(e.backgroundColor)),e?.font!==void 0&&(t.font=Ro(e.font)),Ir({extendedTextMessage:t})},Ir=n=>({[R]:{groupStatusMessageV2:{message:n}},[_e]:"groupStatus()"}),_o=["conversation","extendedTextMessage"],No={imageMessage:"image",videoMessage:"video",audioMessage:"audio"},Er=n=>({[R]:{groupStatusMessageV2:{message:{}}},[_e]:"groupStatus()",[Mt]:n}),Lo=["image","video","audio"],Do=n=>{let e=n;if(typeof e.message=="function"||e.message!==void 0||e.key!==void 0)return null;for(let t of Lo)if(e[t]!==void 0)return {kind:t,src:e[t]};return null},Bo=n=>typeof n.message=="function"?n.message():n,Wo=(n,e,t)=>{let r=proto.Message.decode(proto.Message.encode(n).finish());e==="conversation"&&(r.extendedTextMessage={text:r.conversation},delete r.conversation);let s=r.extendedTextMessage;return delete s.viewOnce,s.contextInfo={},t?.caption!==void 0&&(s.text=t.caption),Ir({extendedTextMessage:s})},xr=async(n,e)=>{let t=Do(n);if(t!==null){let a=n,{buffer:d}=await O(t.src),c={kind:t.kind,buffer:d},l=e?.caption??a.caption;return t.kind!=="audio"&&l!==void 0&&(c.caption=l),t.kind==="audio"&&a.ptt===true&&(c.ptt=true),Er(c)}let r=Bo(n),s=r?.message==null?null:normalizeMessageContent(r.message),i=s==null?void 0:getContentType(s);if(s==null||i===void 0)throw new p("EMPTY_CONTENT","groupStatus() source has no repostable content");let o=No[i];if(o!==void 0){let a=s[i]??{},d;try{let{downloadMediaMessage:u}=await import('baileys');d=await u(r,"buffer",{});}catch(u){throw new p("MEDIA_LOAD_FAILED","groupStatus() could not download the source media",{cause:u})}let c={kind:o,buffer:d},l=e?.caption??a.caption;return o!=="audio"&&l!==void 0&&(c.caption=l),o==="audio"&&a.ptt===true&&(c.ptt=true),Er(c)}if(!_o.includes(i))throw new p("INVALID_OPTIONS",`groupStatus() cannot repost ${i}; supported: text, image, video, audio`);return Wo(s,i,e)};var Or=10,Rr=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new p("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new p("INVALID_OPTIONS","list() requires at least one section");let e=0,t=new Set,r=n.sections.map(a=>{if(!Array.isArray(a.rows)||a.rows.length===0)throw new p("INVALID_OPTIONS","each list section requires at least one row");let d=a.rows.map(c=>{if(typeof c.id!="string"||c.id.length===0)throw new p("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof c.title!="string"||c.title.trim().length===0)throw new p("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(c.id))throw new p("INVALID_OPTIONS",`duplicate list row id: ${c.id}`);return t.add(c.id),e+=1,{header:"",title:c.title,description:c.description??"",id:c.id}});return {title:a.title,highlight_label:"",rows:d}});if(e>Or)throw new p("INVALID_OPTIONS",`list() accepts at most ${Or} rows total`);let s={name:"single_select",buttonParamsJson:JSON.stringify({title:n.buttonText,sections:r})},i={body:{text:n.description&&n.description.length>0?n.description:" "},nativeFlowMessage:{buttons:[s],messageParamsJson:""}};return n.footerText&&n.footerText.length>0&&(i.footer={text:n.footerText}),n.title&&n.title.length>0&&(i.header={title:n.title,subtitle:"",hasMediaAttachment:false}),{[R]:{interactiveMessage:i}}};var _r=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new p("INVALID_OPTIONS",`location() latitude must be within -90..90, got ${String(n)}`);if(typeof e!="number"||Number.isNaN(e)||e<-180||e>180)throw new p("INVALID_OPTIONS",`location() longitude must be within -180..180, got ${String(e)}`);let r={degreesLatitude:n,degreesLongitude:e};return t?.name!==void 0&&(r.name=t.name),t?.address!==void 0&&(r.address=t.address),{location:r}};var Nr=2,Lr=12,Dr=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<Nr)throw new p("INVALID_OPTIONS",`poll() requires a minimum of ${Nr} options`);if(e.length>Lr)throw new p("INVALID_OPTIONS",`poll() accepts a maximum of ${Lr} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new p("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new p("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var Br=async n=>{if(n==null||typeof n.title!="string"||n.title.trim().length===0)throw new p("INVALID_OPTIONS","product() requires a non-empty title");if(typeof n.businessOwnerId!="string"||n.businessOwnerId.length===0)throw new p("INVALID_OPTIONS","product() requires businessOwnerId");let{buffer:e}=await O(n.image),t={productImage:e,title:n.title};n.productId!==void 0&&(t.productId=n.productId),n.description!==void 0&&(t.description=n.description),n.currency!==void 0&&(t.currencyCode=n.currency),n.price!==void 0&&(t.priceAmount1000=Math.round(n.price*1e3)),n.retailerId!==void 0&&(t.retailerId=n.retailerId),n.url!==void 0&&(t.url=n.url);let r={product:t,businessOwnerJid:n.businessOwnerId};return n.body!==void 0&&(r.body=n.body),n.footer!==void 0&&(r.footer=n.footer),r};var Wr=async(n,e)=>{let{buffer:t}=await O(n),r;try{r=await new se(t).sticker.create(e);}catch(i){throw new p("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var Fr=3,jr=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new p("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new p("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>Fr)throw new p("INVALID_OPTIONS",`template() accepts at most ${Fr} buttons`);let t={text:`${n.header&&n.header.length>0?`*${n.header}*
|
|
9
9
|
|
|
10
|
-
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),St(n.buttons,t)};var At=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Ur=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var mn=new WeakSet,qr=n=>{mn.add(n);},Kr=n=>{if(!mn.has(n))return n;mn.delete(n);let e=randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var Pt="status@broadcast",Jo=[{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,Ur(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=mr(wr(e),t):this.internal.content=At(e),this}image(e,t){return this.internal.pendingContent=fe(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=cr(e,t),this}document(e,t){return this.internal.pendingContent=Mr(e,t),this}sticker(e,t){return this.internal.pendingContent=Wr(e,t),this}buttons(e,t){return this.internal.content=St(e,t),this}carousel(e,t){return this.internal.content=pr(e,t),this}list(e){return this.internal.content=Rr(e),this}poll(e,t,r){return this.internal.content=Dr(e,t,r),this}location(e,t,r){return this.internal.content=_r(e,t,r),this}contact(e){return this.internal.content=vr(e),this}template(e){return this.internal.content=jr(e),this}event(e){return this.internal.content=br(e),this}groupInvite(e){return this.internal.content=Cr(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=Tr(e,t):this.internal.pendingContent=xr(e,t),this}product(e){return this.internal.pendingContent=Br(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!==Pt)throw new p("INVALID_RECIPIENT",`audience() only applies to ${Pt}, not ${this.internal.recipient}`);if(this.internal.albumItems){let c={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(c.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(c.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(c.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(c.disappearingSeconds=this.internal.disappearingSeconds),ir(this.socket,this.internal.recipient,this.internal.albumItems,c)}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 c=s[_e];if(typeof c=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${c} can only be sent to a group jid ending in @g.us`);let l=s[Mt],u=l!==void 0?await this.buildStatusMedia(l):i,w=s[cn],M=s[un];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===Pt&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${Pt} 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 d;try{d=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(c){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:c})}if(!d?.key)throw new p("SEND_FAILED","socket returned no message key");return d.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 d={userJid:this.socket.user?.id??""},c=this.internal.quoted;c!==void 0&&c.message!=null&&(d.quoted=c),this.internal.disappearingSeconds!==void 0&&(d.ephemeralExpiration=this.internal.disappearingSeconds);let l=generateWAMessageFromContent(this.internal.recipient,e,d);if(s&&l.message!=null&&qr(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:Jo}:{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 Ne=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=At(e),this}image(e,t){return this.pendingContent=fe(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 gn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},fn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},hn=async(n,e,t={})=>{let r=gn(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);},yn=async(n,e,t)=>{let r=gn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return fn(s)},wn=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 fn(i)},kt=async(n,e,t,r={})=>{let s=gn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return fn(o)};var Vo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Le=n=>Vo.test(n),vn=async(n,e,t,r=Ho)=>{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 d=(await n.onWhatsApp(e))?.find(c=>c.exists&&c.jid);if(!d)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,d.jid),d.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Ho=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 De=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 Be=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 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("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 Fe=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 je=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 $r=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new I("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Ue=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=$r(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 $r(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 qe=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 Ke=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 zo=n=>{let e=n[0];return e==="{"||e==="["},Yo=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},Zo=n=>n===" "||n===" "||n===`
|
|
10
|
+
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),St(n.buttons,t)};var At=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Ur=(n,e,t,r)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{},...r?{inheritDisappearing:r}:{}});var mn=new WeakSet,qr=n=>{mn.add(n);},Kr=n=>{if(!mn.has(n))return n;mn.delete(n);let e=randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var Pt="status@broadcast",Jo=[{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,i){return new n(e,Ur(t,r,s,i))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=mr(wr(e),t):this.internal.content=At(e),this}image(e,t){return this.internal.pendingContent=fe(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=cr(e,t),this}document(e,t){return this.internal.pendingContent=Mr(e,t),this}sticker(e,t){return this.internal.pendingContent=Wr(e,t),this}buttons(e,t){return this.internal.content=St(e,t),this}carousel(e,t){return this.internal.content=pr(e,t),this}list(e){return this.internal.content=Rr(e),this}poll(e,t,r){return this.internal.content=Dr(e,t,r),this}location(e,t,r){return this.internal.content=_r(e,t,r),this}contact(e){return this.internal.content=vr(e),this}template(e){return this.internal.content=jr(e),this}event(e){return this.internal.content=br(e),this}groupInvite(e){return this.internal.content=Cr(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=Tr(e,t):this.internal.pendingContent=xr(e,t),this}product(e){return this.internal.pendingContent=Br(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.disappearingSeconds===void 0){let c=this.internal.inheritDisappearing?.(this.internal.recipient);c!==void 0&&c>0&&(this.internal.disappearingSeconds=c);}if(this.internal.statusJidList!==void 0&&this.internal.recipient!==Pt)throw new p("INVALID_RECIPIENT",`audience() only applies to ${Pt}, not ${this.internal.recipient}`);if(this.internal.albumItems){let c={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(c.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(c.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(c.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(c.disappearingSeconds=this.internal.disappearingSeconds),ir(this.socket,this.internal.recipient,this.internal.albumItems,c)}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 c=s[_e];if(typeof c=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${c} can only be sent to a group jid ending in @g.us`);let l=s[Mt],u=l!==void 0?await this.buildStatusMedia(l):i,w=s[cn],M=s[un];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===Pt&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${Pt} 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 d;try{d=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(c){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:c})}if(!d?.key)throw new p("SEND_FAILED","socket returned no message key");return d.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 d={userJid:this.socket.user?.id??""},c=this.internal.quoted;c!==void 0&&c.message!=null&&(d.quoted=c),this.internal.disappearingSeconds!==void 0&&(d.ephemeralExpiration=this.internal.disappearingSeconds);let l=generateWAMessageFromContent(this.internal.recipient,e,d);if(s&&l.message!=null&&qr(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:Jo}:{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 Ne=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=At(e),this}image(e,t){return this.pendingContent=fe(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 gn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},fn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},hn=async(n,e,t={})=>{let r=gn(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);},yn=async(n,e,t)=>{let r=gn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return fn(s)},wn=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 fn(i)},kt=async(n,e,t,r={})=>{let s=gn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return fn(o)};var Vo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Le=n=>Vo.test(n),vn=async(n,e,t,r=Ho)=>{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 d=(await n.onWhatsApp(e))?.find(c=>c.exists&&c.jid);if(!d)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,d.jid),d.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Ho=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 De=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 Be=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 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("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 Fe=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 je=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 $r=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new I("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Ue=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=$r(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 $r(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 qe=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 Ke=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 zo=n=>{let e=n[0];return e==="{"||e==="["},Yo=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},Zo=n=>n===" "||n===" "||n===`
|
|
11
11
|
`||n==="\r",Qo=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let d=n[a];if(s){t+=d,s=false,i=true,o=false;continue}if(d==="\\"&&r!==null){s=true;continue}if(r!==null){d===r?r=null:t+=d,o=false;continue}if((d==='"'||d==="'")&&o){r=d,i=true,o=false;continue}if(Zo(d)){i&&(e.push(t),t="",i=false),o=true;continue}t+=d,i=true,o=false;}return i&&e.push(t),e},Xo=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},ea=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function Mn(n,e){let t=Xo(n,e);if(t===null)return ea(n);let r=n.slice(t.length),s=Qo(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 d=s[a];if(d!==void 0){if(d.startsWith("--")){let c=d.slice(2);if(c.length===0){i.args.push(d);continue}let l=c.indexOf("=");if(l!==-1){let w=c.slice(0,l),M=c.slice(l+1);i.flags[w]=M;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[c]=u,a+=1):i.flags[c]=true;continue}if(!o&&zo(d)){let c=Yo(d);c.ok&&(i.json=c.value,o=true);}i.args.push(d);}}return i}var Gr=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},ve=n=>n.join(" "),Jr=n=>[n.name,...n.aliases??[]].join("|"),ta=n=>{let e={};return n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},$e=class{paths=new Map;defs=[];maxDepth=1;register(e,t){let r=typeof e=="string"?e:Jr(e);if(r.trim().length===0)throw new _("INVALID_COMMAND_NAME","command spec must not be empty");let s=r.split("|").map(d=>Gr(d)),i=s[0],o=s.slice(1).map(d=>ve(d)),a={name:ve(i),aliases:o,parts:i,handler:t,meta:typeof e=="string"?{}:ta(e)};for(let d of s){let c=ve(d);if(this.paths.has(c))throw new _("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let d of s)this.paths.set(ve(d),a),d.length>this.maxDepth&&(this.maxDepth=d.length);this.defs.push(a);}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 r=(typeof e=="string"?e:Jr(e)).split("|").map(a=>Gr(a)),s=ve(r[0]),i=this.paths.get(s);if(i===void 0)return;for(let a of [i.parts,...i.aliases.map(d=>d.split(" "))])this.paths.delete(ve(a));let o=this.defs.indexOf(i);o>=0&&this.defs.splice(o,1),this.maxDepth=this.defs.reduce((a,d)=>Math.max(a,d.parts.length),1);}list(){return [...this.defs]}describe(){return this.defs.map(e=>({name:e.name,aliases:[...e.aliases],...e.meta}))}};async function Sn(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(d){throw s.error=d,s.thrown=true,d}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(d){throw s.thrown||d instanceof _?d:new _("MIDDLEWARE_ERROR","middleware threw during execution",{cause:d})}};await i(0);}var bn=new Map,na=(n,e)=>`${n}\0${e}`,ra=()=>{bn.clear();},Cn=async(n,e,t)=>{if((n.group===true||n.admin===true)&&!e.isGroup)return {reason:"group-only"};if(n.private===true&&e.isGroup)return {reason:"private-only"};if(n.admin===true){let s=e.roomId;if(s===null)return {reason:"admin-only"};if(!await t.isAdmin(s,e.senderId))return {reason:"admin-only"}}if(n.cooldown!==void 0&&n.cooldown>0){let s=na(e.command,e.senderId),i=bn.get(s),o=t.now(),a=n.cooldown*1e3;if(i!==void 0&&o-i<a)return {reason:"cooldown",retryIn:Math.ceil((a-(o-i))/1e3)};bn.set(s,o);}return null};function An(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=Mn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0){i.name!==void 0&&i.name.length>0&&n.onNotFound?.(i.name,s);return}let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},d=n.buildContext(a,s);(async()=>{let l=await Cn(o.def.meta,d,{isAdmin:n.isAdmin??(async()=>false),now:()=>Date.now()});if(l!==null){n.onBlocked?.(l,d);return}await Sn(n.middleware,d,()=>o.def.handler(d));})().catch(l=>{let u=l instanceof _?l:new _("HANDLER_ERROR","command handler failed",{cause:l});n.onError?.(u,d)!==true&&n.logger.error(u,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Se=new Map,Hr=n=>n!=null&&typeof n=="object"?n:null,zr=n=>Array.isArray(n.content)?n.content.map(Hr).filter(e=>e!==null):[],Vr=(n,e)=>zr(n).find(t=>t.tag===e),Me=n=>typeof n=="string"&&n.length>0?n:void 0,Pn=n=>{if(n===void 0)return;let e=Number.parseInt(n,10);return Number.isFinite(e)?e:void 0},sa=(n,e)=>{if(Object.keys(e).length!==0){if(Se.size>=64){let t=Se.keys().next().value;t!==void 0&&Se.delete(t);}Se.set(n,e);}},Yr=n=>{let e=Hr(n);if(e===null||e.tag!=="call")return false;let t=zr(e).find(v=>v.tag==="offer"),r=Me(t?.attrs?.["call-id"]);if(t===void 0||r===void 0)return false;let s={},i=Me(e.attrs?.platform),o=Me(e.attrs?.version),a=Me(e.attrs?.notify),d=Me(t.attrs?.caller_country_code),c=Me(t.attrs?.caller_pn);i!==void 0&&(s.platform=i),o!==void 0&&(s.appVersion=o),a!==void 0&&(s.name=a),d!==void 0&&(s.countryCode=d),c!==void 0&&(s.phoneJid=c);let l=Pn(Vr(t,"net")?.attrs?.medium);l!==void 0&&(s.networkMedium=l);let u=Vr(t,"video"),w=Pn(u?.attrs?.screen_width),M=Pn(u?.attrs?.screen_height);return w!==void 0&&M!==void 0&&(s.screen={width:w,height:M}),sa(r,s),true},Zr=n=>{let e=Se.get(n);return e!==void 0&&Se.delete(n),e};var Qr=["text","image","video","audio","document","sticker","reaction","edit","delete","poll-vote","button-click","list-select","mention","mention-all","group-update","group-join","group-leave","member-tag","call-incoming","call-ended","history-sync","limited","presence","newsletter"],Xr=n=>n;var ia=(n,e)=>{let t=oe.dirname(oe.resolve(n)),r=e===void 0?void 0:oe.resolve(e);if(r!==void 0){let i=oe.relative(r,t);return i.length===0||i.startsWith("..")?void 0:i.split(oe.sep)[0]}let s=oe.basename(t);return s.length>0?s:void 0},oa=n=>n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),aa=n=>{let e={name:n.name};return n.aliases!==void 0&&(e.aliases=n.aliases),n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},da=(n,e)=>{let t=n.message;typeof t=="function"&&e.command(aa(n),s=>t(s,e));let r=n;for(let s of Qr){let i=r[oa(s)];typeof i=="function"&&e.on(s,o=>{i(o,e);});}},Ge=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,r){if(typeof e?.name!="string"){this.logger?.warn({file:t},"plugin: invalid shape (needs a name); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let s=[],i=ia(t,r),o={client:this.host,logger:this.logger,pluginDir:oe.dirname(t),category:i,command:(a,d)=>{let c=typeof a=="string"||a.category!==void 0||i===void 0?a:{...a,category:i};this.host.command(c,d),s.push(()=>this.host.unregisterCommand(c));},use:a=>{this.host.use(a),s.push(()=>{this.host.unuse(a);});},on:(a,d)=>{let c=this.host.on(a,d);return s.push(c),c},once:(a,d)=>{let c=false,l=this.host.on(a,u=>{c||(c=true,l(),d(u));});return s.push(l),l}};try{da(e,o);let a=await e.setup?.(o);typeof a=="function"&&s.push(a);}catch(a){for(let d of [...s].reverse())try{await d();}catch{}this.logger?.error({err:a,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:s});}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 ua=/\.(ts|js|mjs|cjs)$/,pa=/(\.d\.ts$|^_|[/\\]_)/;async function En(n,e,t){let r;try{r=await promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=oe.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await En(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function ts(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"?s:void 0}catch{return}}var Je=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=oe.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??ua,this.ignore=e.options.ignore??pa,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await En(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 ts(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,this.dir);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=oe.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 ma=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ae=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??ma;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 ga={"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},fa=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function Tn(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??fa,i={...ga,...n.intervalsMs??{}},o=new Map,a=new Map,d=async(c,l)=>{let u=i[c]??0,w=o.get(c);if(w!==void 0&&u>0){let M=u-(r()-w);M>0&&await s(M);}return o.set(c,r()),l()};return {run(c,l){if(!t)return l();let w=(a.get(c)??Promise.resolve()).then(()=>d(c,l),()=>d(c,l));return a.set(c,w.then(()=>{},()=>{})),w}}}var ha={maxRetries:0,backoffMs:()=>0},ya=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),Ve=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??ha,this.sleep=t.sleep??ya;}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 wa=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function In(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 ae({perSec:i},o),d=r.retry,c=t.sleep?{sleep:t.sleep}:{},l=d?new Ve({concurrency:1,retry:d},c):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:wa(P)}),w+=1,r.onProgress?.(w,u,M,false);}}return s}var va=1e3,He=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??va,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 Sa={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},ba=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",ze=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??Sa,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),ba(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,d)=>{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=d?{recipient:o,content:a,options:d}:{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 ns(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((d,c)=>Number(c.messageTimestamp??0)-Number(d.messageTimestamp??0));for(let d=0;d<a.length;d+=1){let c=a[d],l=Number(c.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,w=e.maxPerChat!==void 0&&d>=e.maxPerChat;(u||w)&&(await n.deleteMessage(c.key),r+=1);}}return r}var Ye=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"?ns(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 rs=n=>(n.split(/[:@]/)[0]??"").replace(/\D/g,""),Ze=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=rs(e);return t.some(s=>s===e||rs(s)===r)}return await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var Ca={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Aa=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Ca[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},Et=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=Aa(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")}},ss=(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 be=n=>typeof n!="string"||n.length===0?null:jidNormalizedUser(n),Z=n=>typeof n=="string"&&n.length>0?n:void 0,Ea=["@s.whatsapp.net","@c.us"],Tt=n=>n.endsWith("@lid"),is=n=>Ea.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 d=i!==null?[r,i]:[r],c=d.find(Tt),l=d.find(is);c!==void 0&&(a.lid=c),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Z(e);return u!==void 0&&(a.pushName=u),a},os=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},Qe=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 Ce=n=>isJidGroup(n)===true,Ae=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,as=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],ds=["groupStatusMessage","groupStatusMessageV2"],cs=(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 as){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 as){let i=g(g(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var us=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},ls=(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},ps=n=>(ls(n).toString(16).padStart(8,"0")+ls(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),ms=n=>ps(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),gs=(n,e)=>ps(`${n??""}|${e}`),fs=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},hs=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"},Ia=n=>n.trim().endsWith("?"),xa=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Oa=(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}})},Ra=(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)}},_a=0,Na=14,La=1,Da=2,Ba=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===Na,isDeleted:r===_a,isPinned:s===La,isUnPinned:s===Da,isBot:g(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:cs(e,ds)}},xn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Ce(e),r=Ba(n.message),s=d=>n.lidMap!=null&&d.endsWith("@lid")?n.lidMap.get(d)??d:d,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:ms(n.key),staticId:gs(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:hs(n.sender.deviceJid??n.sender.jid),timestamp:fs(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:us(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:Ia(n.text),isPrefix:xa(n.text,n.prefixes),isTagMe:Oa(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:Ra(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"},vs=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},Ms=n=>{let e=g(n.message);if(e==null)return n;let t=Pe(e);return t===e?n:{...n,message:t}},Wa=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(`
|
|
12
12
|
`).trim();return i.length>0?i:null},Fa=n=>{let e=g(n.templateMessage),t=g(e?.hydratedTemplate)??g(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},ja=n=>Q(g(n.pollCreationMessage)?.name,g(n.pollCreationMessageV2)?.name,g(n.pollCreationMessageV3)?.name),Ua=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},qa=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},Ss=n=>Q(n.conversation,g(n.extendedTextMessage)?.text,Wa(n),S(g(g(n.interactiveMessage)?.body)?.text),g(n.buttonsMessage)?.contentText,g(n.listMessage)?.description,Fa(n),ja(n),Ua(n),qa(n)),Ka=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),$a=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=Ae(n);return typeof e=="number"?e:null},Ga=[["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"]],bs=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 d=g(g(n.productMessage)?.product);if(g(n.productMessage)!=null){let m=S(g(n.productMessage)?.businessOwnerJid),f=T(d?.priceAmount1000);return {type:"product",productId:S(d?.productId),title:S(d?.title),description:S(d?.description),price:f!=null?f/1e3:null,currency:S(d?.currencyCode),retailerId:S(d?.retailerId),url:S(d?.url),businessOwnerId:m}}let c=g(n.orderMessage);if(c!=null){let m=T(c.totalAmount1000),f={1:"inquiry",2:"accepted",3:"declined"},b=c.status;return {type:"order",orderId:S(c.orderId),title:S(c.orderTitle),itemCount:T(c.itemCount),total:m!=null?m/1e3:null,currency:S(c.totalCurrencyCode),status:typeof b=="number"?f[b]??null:S(b),message:S(c.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 et=n=>{let e=g(n.message);if(e==null)return null;let t=Pe(e);return Ss(t)??Ka(t)??$a(t)},nt=n=>{let e=g(Ms(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},Ja=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Rn[e]];return r==null||typeof r!="object"?null:r},Va=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},Ha=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,Cs=n=>As(n,nt(n))??void 0,za=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,As=(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},Ya=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},Ps=n=>typeof n=="string"&&n.length>0?n:void 0,Za=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=Ps(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},Qa=n=>{let e=Ps(g(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},de=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 Ga)if(t[r]!=null)return s;return "text"},ys=(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))},Xa=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=et(v)??"",y=ce(v,e,de(v.message),P,tt(v,e),s);if(y!==null)return y}}let a=os(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 d=a.key.participant,c=Ce(t),l=a.sender?.pushName;!c&&(d==null||d.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&ys({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 d=="string"&&(e.selfJid.length>0&&It(d,e.selfJid)||e.selfLid!=null&&It(d,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&&ys(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=et(w)??"";return ce(w,e,de(u),M,tt(w,e),s)}catch{return null}},ks=n=>Qe(nt(n)).mentionedJids,ed=n=>{try{return jidNormalizedUser(n)}catch{return n}},Es=(n,e)=>n.map(t=>{let r=ed(t);return e.lidMap?.get(r)??r}),ws=n=>(n.split("@")[0]??"").split(":")[0]??"",td=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[ws(s),ws(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},ce=(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 d=vs(o);if(d.length===0)return null;let c=nt(n),l=Ce(d),u=d.endsWith("@broadcast"),w=d.endsWith("@newsletter"),M=c?.isForwarded===true||(c?.forwardingScore??0)>0,v=Va(n),P=Ha(n,c),y=e.channelId??"",m=e.receiverId??"",f=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(d):Promise.resolve(null):Promise.resolve(a.pushName??null)),k=e.resolveReceiverName??(()=>Promise.resolve(null)),F=()=>Xa(c,e,d,a,b,o.fromMe===true),tn=d.length>0?d:a.pn??a.jid,nn=(sn,Yi)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(tn,sn,Yi,n),rn=sn=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,sn),Hi=Es(Qe(c).mentionedJids,e),zi=td(r,e.lidMap),Gn=Za(c),Jn=Qa(n),Vn={message:n,key:o,channelId:y,receiverId:m,selfJid:e.selfJid,text:zi,chatType:t,sender:a,mentions:Hi,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:w,isOld:e.isOld===true,prefixes:f,forwardCount:za(c?.forwardingScore,0),ephemeralDuration:As(n,c),addressingMode:o.addressingMode==="lid"?"lid":"pn",mentionedGroups:Ya(c),...Gn!==void 0?{ad:Gn}:{},...Jn!==void 0?{business:Jn}:{},...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:k,resolveReplied:F,reply:nn,react:rn},Hn=s!==void 0?{...Vn,media:s}:Vn;return xn(e.citationConfig!==void 0?{...Hn,citationConfig:e.citationConfig}:Hn)},nd=["image","video","audio","document","sticker"],Ts=(n,e,t)=>{let r=Ms(n),s=Ja(r,e);if(s===null)return null;let i=Et(r,e,t.logger),o=ss(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}},tt=(n,e)=>{let t=g(n.message);if(t==null)return;let r=de(n.message);return nd.includes(r)?Ts(n,r,e)??void 0:bs(Pe(t))??void 0},Is=(n,e)=>{if(g(n.message)==null)return null;let r=de(n.message),s=tt(n,e),i=et(n)??"";return i===""&&s===void 0?null:ce(n,e,r,i,s)},xs=(n,e)=>{let t=g(n.message);if(t==null)return null;let r=Pe(t),s=Ss(r),i=bs(r)??void 0;return s===null&&i===void 0?null:ce(n,e,de(n.message),s??"",i)},rt=(n,e,t)=>{let r=Ts(e,n,t);return r===null?null:ce(e,t,n,r.caption??"",r)},Os=(n,e)=>rt("image",n,e),Rs=(n,e)=>rt("video",n,e),_s=(n,e)=>rt("audio",n,e),Ns=(n,e)=>rt("document",n,e),Ls=(n,e)=>rt("sticker",n,e),It=(n,e)=>{try{return jidNormalizedUser(n)===jidNormalizedUser(e)}catch{return n===e}},Ds=(n,e)=>{if(n.key==null)return null;let r=nt(n),s=Qe(r).mentionedJids;if(s.length===0)return null;let i=Es(s,e);if(!(i.some(u=>It(u,e.selfJid))||e.selfLid!=null&&s.some(u=>It(u,e.selfLid)))||g(n.message)==null)return null;let d=et(n)??"",c=tt(n,e),l=ce(n,e,de(n.message),d,c);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},Bs=(n,e)=>{let t=n.key;if(t==null)return null;let r=vs(t);if(r.length===0||!Ce(r))return null;let{mentionAll:s}=Qe(nt(n));if(!s||g(n.message)==null)return null;let o=et(n)??"",a=tt(n,e),d=ce(n,e,de(n.message),o,a);return d===null?null:{...d,isMentionAll:true,selfJid:e.selfJid}};var le="[zaileys]",rd="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 Fs(n){switch(n.kind){case "connecting":return `${le} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${le} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${le} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${le} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${le} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
|
|
13
13
|
${le} ${rd}`:t}case "disconnect":return n.willReconnect?null:`${le} Disconnected (${n.reason}).`;default:return null}}var Ws=false,sd=["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:"],id=n=>typeof n[0]=="string"&&sd.some(e=>n[0].startsWith(e));function js(){if(Ws)return;Ws=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{id(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 ad="./.zaileys/auth",dd=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),it=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",Ot=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??ad;}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(it(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],d=this.signalPath(r,o);a===null?t.push(promises.unlink(d).catch(c=>{if(!it(c))throw new h("STORE_WRITE_FAILED",`failed to unlink ${d}`,{cause:c})})):a!==void 0&&t.push(this.atomicWrite(d,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(!it(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(it(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(!it(e))throw new h("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return oe.join(this.basePath,"creds.json")}signalDir(e){return oe.join(this.basePath,"signal",String(e))}signalPath(e,t){return oe.join(this.signalDir(e),`${dd(t)}.json`)}async atomicWrite(e,t){let r=oe.join(oe.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 Us(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 d={},c={};for(let l of a)c[l]=null;d[o]=c,await s.set(d);},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 qs(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 ld=429;function Ks(n){if(n===ld)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 ot(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Rt(n){return n==="rate-limited"}function $s(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function Fg(n){return !ot(n)}var _t={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},ud=3e5;function Gs(n={}){let e=n.enabled??_t.enabled,t=n.maxQrAttempts??_t.maxQrAttempts,r=n.maxPairingAttempts??_t.maxPairingAttempts,s=n.pairingCooldownMs??_t.pairingCooldownMs,i=0,o=0,a=0,d=w=>w<=0?0:Math.min(s*w,ud);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=d(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 pd=/[\s\-()+]/g;function md(n){return typeof n!="string"?"":n.replace(pd,"")}function gd(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=md(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 Js(n){let e=gd(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 hd(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{fd.generate(n,{small:true},t=>e(t));})}async function Vs(n,e=t=>{process.stdout.write(t);}){let t=await hd(n);e(t+`
|
|
@@ -17,8 +17,8 @@ ${le} ${rd}`:t}case "disconnect":return n.willReconnect?null:`${le} Disconnected
|
|
|
17
17
|
VERSION:3.0
|
|
18
18
|
FN:${i}${o?`
|
|
19
19
|
${o}`:""}
|
|
20
|
-
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Qd=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:X(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Xd=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:Hd(n)??zd(n)??Yd(n)??Zd(n);if(t===null)return null;let r=Qd(t,n),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:X(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},ec=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?X(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},tc=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Ut(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:X(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},nc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Ut(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:X(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},rc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=X(n.from),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ki(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=Vd(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=rc(l,c);if(u){t.push(u);continue}let w=tc(l,c);if(w){i.push(w);continue}let M=nc(l,c);if(M){o.push(M);continue}let v=Xd(l,c);v&&e.push(v);}for(let l of c.statuses??[]){let u=ec(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var Ei=3,Fn=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function Ti(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=Fn(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(w=>({id:w.id??"",title:w.title??"",description:w.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>Ei)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${Ei} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=Fn(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?Fn(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ee=class{ev=new EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=jt(e);}get apiVersion(){return this.options.apiVersion??Ft}get baseUrl(){return this.options.baseUrl??Wn}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=Ti(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...V(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...V(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...V(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new C("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new C("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await ge(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ki(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=bi(e,t,r);if(s===null){let d=Ci(t);if(d){let c=await Ai(this.graph,this.options.phoneNumberId,d);s={...V(e,d.kind,r),[d.kind]:Pi(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var ut=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=jt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var ac=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function jn(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!ac(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var uc="default",pc="qr",xi=6e4,mc=2,gc=3e3,fc="29829202653362039",hc=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},Oi=class extends Wt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=zs();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:_n(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?Bn(e.cloud):void 0,this.sessionId=e.sessionId??uc,this.logger=_n(e.logger),this.authType=e.authType??pc,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&js(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ot({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Lt,this.reconnectStrategy=Hs(this.reconnectOptions),this.authGuard=Gs(e.authGuard),this.operationGuard=Tn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ae({perSec:t}):void 0,this.commandPrefixes=yc(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new Ze(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&ye.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=Fs(e);t&&process.stderr.write(`${t}
|
|
21
|
-
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(new Error('phoneNumber is required when authType is "pairing"'));if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,client:this,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r):Y.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var Ri=class{credsBlob;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
20
|
+
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Qd=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:X(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Xd=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:Hd(n)??zd(n)??Yd(n)??Zd(n);if(t===null)return null;let r=Qd(t,n),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:X(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},ec=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?X(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},tc=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Ut(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:X(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},nc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Ut(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:X(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},rc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=X(n.from),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ki(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=Vd(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=rc(l,c);if(u){t.push(u);continue}let w=tc(l,c);if(w){i.push(w);continue}let M=nc(l,c);if(M){o.push(M);continue}let v=Xd(l,c);v&&e.push(v);}for(let l of c.statuses??[]){let u=ec(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var Ei=3,Fn=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function Ti(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=Fn(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(w=>({id:w.id??"",title:w.title??"",description:w.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>Ei)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${Ei} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=Fn(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?Fn(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ee=class{ev=new EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=jt(e);}get apiVersion(){return this.options.apiVersion??Ft}get baseUrl(){return this.options.baseUrl??Wn}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=Ti(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...V(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...V(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...V(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new C("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new C("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await ge(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ki(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=bi(e,t,r);if(s===null){let d=Ci(t);if(d){let c=await Ai(this.graph,this.options.phoneNumberId,d);s={...V(e,d.kind,r),[d.kind]:Pi(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var ut=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=jt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var ac=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function jn(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!ac(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var uc="default",pc="qr",xi=6e4,mc=2,gc=3e3,fc="29829202653362039",hc=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},Oi=class extends Wt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=zs();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;chatExpiration=new Map;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:_n(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?Bn(e.cloud):void 0,this.sessionId=e.sessionId??uc,this.logger=_n(e.logger),this.authType=e.authType??pc,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&js(),this.on("message",r=>this.rememberChatExpiration(r)),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ot({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Lt,this.reconnectStrategy=Hs(this.reconnectOptions),this.authGuard=Gs(e.authGuard),this.operationGuard=Tn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ae({perSec:t}):void 0,this.commandPrefixes=yc(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new Ze(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&ye.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=Fs(e);t&&process.stderr.write(`${t}
|
|
21
|
+
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(new Error('phoneNumber is required when authType is "pairing"'));if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,client:this,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r,s):Y.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var Ri=class{credsBlob;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
22
22
|
CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new h("STORE_CONNECTION_FAILED","failed to migrate sqlite schema",{cause:r})}this.db=t,this.prepared={readCreds:t.prepare("SELECT data FROM auth_creds WHERE id = ?"),writeCreds:t.prepare("INSERT INTO auth_creds(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data"),deleteCreds:t.prepare("DELETE FROM auth_creds WHERE id = ?"),writeSignal:t.prepare("INSERT INTO auth_signal(type, id, data) VALUES(?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET data = excluded.data"),deleteSignal:t.prepare("DELETE FROM auth_signal WHERE type = ? AND id = ?"),clearSignal:t.prepare("DELETE FROM auth_signal"),clearCreds:t.prepare("DELETE FROM auth_creds")};}encodeBlob(e){try{return Buffer.from(JSON.stringify(e,BufferJSON.replacer),"utf8")}catch(t){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:t})}}parseBlob(e){try{let t=Buffer.isBuffer(e)?e.toString("utf8"):Buffer.from(e).toString("utf8");return JSON.parse(t,BufferJSON.reviver)}catch(t){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var $t,Mc=async()=>($t||($t=import('pg').then(n=>n).catch(n=>{throw $t=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),$t),Sc="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",bc="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",Wi=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","PostgresAuthStore is closed");if(this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Mc(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(Sc),await e.query(bc);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,d)=>`$${d+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let d=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(d.toString("utf8"),BufferJSON.reviver);}return s}catch(i){throw i instanceof h?i:new h("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a];if(d===null)r.push({kind:"delete",type:String(i),id:a});else if(d!==void 0){let c=Buffer.from(JSON.stringify(d,BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:c});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to write signal rows",{cause:i})}finally{s?.release();}},delete:async(e,t)=>{let r=await this.ensureReady();if(t.length!==0)try{let s=t.map((i,o)=>`$${o+2}`).join(", ");await r.query(`DELETE FROM zaileys_auth_signal WHERE type = $1 AND id IN (${s})`,[String(e),...Array.from(t)]);}catch(s){throw new h("STORE_WRITE_FAILED","failed to delete signal rows",{cause:s})}},clear:async()=>{let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_auth_signal"),await t.query("DELETE FROM zaileys_auth_creds"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to clear auth tables",{cause:r})}finally{t?.release();}},close:async()=>{if(this.closed)return;this.closed=true;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};creds={readCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'default'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,BufferJSON.reviver)}catch(t){throw t instanceof h?t:new h("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,BufferJSON.replacer);await t.query("INSERT INTO zaileys_auth_creds(id, data) VALUES ('default', $1::jsonb) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data",[r]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to write creds",{cause:r})}},deleteCreds:async()=>{let e=await this.ensureReady();try{await e.query("DELETE FROM zaileys_auth_creds WHERE id = 'default'");}catch(t){throw new h("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var Cc="zaileys",Ac=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],Pc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Fi=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??Cc,this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let d=i[a];d!=null&&(o[t[a]]=JSON.parse(d,BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a],c=this.signalKey(i,a),l=this.indexKey(i);d===null?(r.del(c),r.sRem(l,a)):d!==void 0&&(r.set(c,JSON.stringify(d,BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of Ac){let s=this.indexKey(r),i=await this.runRead(()=>e.sMembers(s));for(let o of i)t.del(this.signalKey(r,o));t.del(s);}t.del(this.credsKey()),await this.runWrite(()=>t.exec());},close:async()=>{await this.shutdown();}};creds={readCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));if(t!=null)return JSON.parse(t,BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));}};credsKey(){return `${this.namespace}:auth:creds`}signalKey(e,t){return `${this.namespace}:auth:signal:${String(e)}:${t}`}indexKey(e){return `${this.namespace}:auth:signal-index:${String(e)}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new h("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Pc(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","redis write failed",{cause:t})}}async shutdown(){if(!this.closed){if(this.closed=true,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","RedisAuthStore is closed")}};var kc="zaileys",pt={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Ec=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Te=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??kc,this.externalClient=e.client,this.url=e.url;}async get(e){if(this.assertOpen(),e.length===0)return new Map;let t=await this.ensureClient(),r=await this.runRead(()=>t.query(pt.get,{namespace:this.namespace,keys:[...e]})),s=new Map;for(let i of r??[])s.set(i.key,i.value);return s}async set(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.set,{namespace:this.namespace,items:[...e]}));}async del(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.clear,e===void 0?{namespace:this.namespace}:{namespace:this.namespace,prefix:e}));}async list(e,t){this.assertOpen();let r=await this.ensureClient(),s={namespace:this.namespace,prefix:e};return typeof t?.before=="number"&&(s.before=t.before),typeof t?.limit=="number"&&(s.limit=t.limit),await this.runRead(()=>r.query(pt.list,s))??[]}close(){this.closed=true,this.client=void 0;}async ensureClient(){if(this.externalClient)return this.externalClient;if(this.client)return this.client;let e="convex/browser",t;try{t=await import(e);}catch(r){throw Ec(r)?new h("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load convex module",{cause:r})}return this.client=new t.ConvexHttpClient(this.url),this.client}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","Convex store is closed")}};var Vt="creds",Tc="signal:",mt=(n,e)=>`${Tc}${n}:${e}`,ji=class{creds;signal;kv;constructor(e){this.kv=new Te(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([Vt])).get(Vt);return s===void 0?void 0:JSON.parse(s,BufferJSON.reviver)},async writeCreds(r){await t.set([{key:Vt,value:JSON.stringify(r,BufferJSON.replacer)}]);},async deleteCreds(){await t.del([Vt]);}},this.signal={async read(r,s){let i=s.map(d=>mt(r,d)),o=await t.get(i),a={};for(let d of s){let c=o.get(mt(r,d));a[d]=c===void 0?void 0:JSON.parse(c,BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let d of Object.keys(a)){let c=a[d];c==null?i.push(mt(o,d)):s.push({key:mt(o,d),value:JSON.stringify(c,BufferJSON.replacer)});}}s.length>0&&await t.set(s),i.length>0&&await t.del(i);},async delete(r,s){await t.del(s.map(i=>mt(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var Ht=null,Ic=async()=>{if(Ht)return Ht;try{return Ht=(await import('better-sqlite3')).default,Ht}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},zt=n=>{try{return Buffer.from(JSON.stringify(n,BufferJSON.replacer),"utf8")}catch(e){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},pe=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,BufferJSON.reviver)}catch(e){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Ui=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;constructor(e){this.options=e;}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe?1:0,o=Number(e.messageTimestamp??0);t.upsertMessage.run(r,s,i,o,zt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?pe(r.data):void 0}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=t?.before;return (typeof i=="number"?r.listMessages.all(e,i,s):r.listMessages.all(e,Number.MAX_SAFE_INTEGER,s)).map(a=>pe(a.data))}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived?1:0;t.upsertChat.run(r,s,zt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?pe(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>pe(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,zt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?pe(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>pe(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,zt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?pe(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
23
23
|
SELECT rowid FROM (
|
|
24
24
|
SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
|