zaileys 4.11.2 → 4.12.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/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/plugin/types.d.ts +7 -4
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
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
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===`
|
|
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=["message","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.command;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(`
|
|
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+`
|
|
14
14
|
`);}var ke={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function Hs(n,e){let t=n?.enabled??ke.enabled,r=n?.maxAttempts??ke.maxAttempts,s=n?.initialDelayMs??ke.initialDelayMs,i=n?.maxDelayMs??ke.maxDelayMs,o=n?.jitterFactor??ke.jitterFactor,a=n?.rateLimitedDelayMs??ke.rateLimitedDelayMs,d=e?.random??Math.random,c=0;return {next:w=>{if(!t||ot(w))return null;let M=c+1;if(M>r)return null;if(c=M,Rt(w))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),y=1+(d()*2-1)*o,m=P*y,f=Math.min(i,Math.max(0,m));return {attempt:M,delayMs:Math.round(f)}},reset:()=>{c=0;},get attempts(){return c}}}var yd={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function zs(n="idle"){let e=n,t=new Set,r=s=>yd[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var Nt=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Lt=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=Nt(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(Nt(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...d)=>{let l=d[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let u=this.messages.get(Nt(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveChat(l).catch(()=>{});},i=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveContact(l).catch(()=>{});},a=(...d)=>{let c=d[0];if(c?.presences)for(let l of Object.keys(c.presences)){let u=c.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[d,c]of this.listeners)e.ev.on(d,c);}async deleteMessage(e){this.assertOpen();let t=Nt(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let d=this.messages.get(a);d&&i.push(d);}i.sort((a,d)=>Number(d.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,d)=>{let c=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&c<e.olderThan||e.maxPerChat!==void 0&&d>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var vd=["silent","fatal","error","warn","info","debug","trace"];function Md(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":vd.includes(e)?e:"silent"}function Sd(n={}){let e=Md(n.level),t=wd__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Ys=["debug","info","warn","error","fatal"];function bd(n){if(n===null||typeof n!="object")return false;for(let e of Ys)if(typeof n[e]!="function")return false;return true}function at(){}function Cd(n){let e={debug:at,info:at,warn:at,error:at,fatal:at};for(let t of Ys){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function _n(n,e){return n===void 0?e??Sd():bd(n)?n:Cd(n)}var Qg=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),Zs=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var Ad=new Set(["offer","ringing"]),Pd=new Set(["timeout","reject","accept","terminate"]),Qs=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},Xs=n=>{if(typeof n.id!="string"||n.id.length===0||!Ad.has(n.status))return null;let e=Zr(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Qs(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},ei=n=>typeof n.id!="string"||n.id.length===0||!Pd.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Qs(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,kd=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},ti=(n,e,t)=>n.filter(r=>B(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return B(i)&&(s.participantAlt=i),B(e)&&(s.authorPn=e),B(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),ni=n=>B(n?.id)?{groupId:n.id,update:kd(n),timestamp:Date.now()}:null,ri=n=>{if(!B(n?.groupId)||!B(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return B(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},Ed=new Set(["add","invite","invite-link"]),Td=new Set(["remove","leave"]),si=n=>{if(!B(n?.id)||!Ed.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ti(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t},ii=n=>{if(!B(n?.id)||!Td.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ti(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t};var Id=["quick_reply","cta_url","cta_call","button_click"],xd=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,ai=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return $(n.key,e)},di=n=>Ae(n.messageTimestamp)??0,ci=(n,e)=>{if(!J(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},Dt=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},li=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return Nn(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return Nn(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Id.includes(i.name)){let o=ci(i.paramsJson,e.logger);if(!o)return null;let a=Dt(o,["id","button_id"]);return a===void 0?null:Nn(n,a,Dt(o,["display_text"])??null)}return null},Nn=(n,e,t)=>{let r=ai(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:di(n)};return J(t)&&(s.buttonText=t),s},ui=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return oi(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&xd.includes(i.name)){let o=ci(i.paramsJson,e.logger);if(!o)return null;let a=Dt(o,["row_id","id"]);return a===void 0?null:oi(n,a,Dt(o,["title"])??null)}return null},oi=(n,e,t)=>{let r=ai(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:di(n)};return J(t)&&(s.title=t),s};var Od=new Set(["available","unavailable","composing","recording","paused"]),Rd=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,pi=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},Ln=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:Rd(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},mi=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!Od.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},dt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var ue=(n,e)=>{let t=Ae(n);return t===null?e:t},Nd=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(d=>d?.messageText).filter(d=>typeof d=="string"&&d.length>0);if(a.length>0)return a.join(`
|
package/dist/index.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import dc,{prepareWAMessageMedia,generateWAMessageContent,normalizeMessageConten
|
|
|
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
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===`
|
|
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=["message","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.command;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(`
|
|
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+`
|
|
14
14
|
`);}var ke={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function Hs(n,e){let t=n?.enabled??ke.enabled,r=n?.maxAttempts??ke.maxAttempts,s=n?.initialDelayMs??ke.initialDelayMs,i=n?.maxDelayMs??ke.maxDelayMs,o=n?.jitterFactor??ke.jitterFactor,a=n?.rateLimitedDelayMs??ke.rateLimitedDelayMs,d=e?.random??Math.random,c=0;return {next:w=>{if(!t||ot(w))return null;let M=c+1;if(M>r)return null;if(c=M,Rt(w))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),y=1+(d()*2-1)*o,m=P*y,f=Math.min(i,Math.max(0,m));return {attempt:M,delayMs:Math.round(f)}},reset:()=>{c=0;},get attempts(){return c}}}var yd={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function zs(n="idle"){let e=n,t=new Set,r=s=>yd[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var Nt=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Lt=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=Nt(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(Nt(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...d)=>{let l=d[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let u=this.messages.get(Nt(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveChat(l).catch(()=>{});},i=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveContact(l).catch(()=>{});},a=(...d)=>{let c=d[0];if(c?.presences)for(let l of Object.keys(c.presences)){let u=c.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[d,c]of this.listeners)e.ev.on(d,c);}async deleteMessage(e){this.assertOpen();let t=Nt(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let d=this.messages.get(a);d&&i.push(d);}i.sort((a,d)=>Number(d.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,d)=>{let c=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&c<e.olderThan||e.maxPerChat!==void 0&&d>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var vd=["silent","fatal","error","warn","info","debug","trace"];function Md(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":vd.includes(e)?e:"silent"}function Sd(n={}){let e=Md(n.level),t=wd({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Ys=["debug","info","warn","error","fatal"];function bd(n){if(n===null||typeof n!="object")return false;for(let e of Ys)if(typeof n[e]!="function")return false;return true}function at(){}function Cd(n){let e={debug:at,info:at,warn:at,error:at,fatal:at};for(let t of Ys){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function _n(n,e){return n===void 0?e??Sd():bd(n)?n:Cd(n)}var Qg=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),Zs=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var Ad=new Set(["offer","ringing"]),Pd=new Set(["timeout","reject","accept","terminate"]),Qs=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},Xs=n=>{if(typeof n.id!="string"||n.id.length===0||!Ad.has(n.status))return null;let e=Zr(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Qs(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},ei=n=>typeof n.id!="string"||n.id.length===0||!Pd.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Qs(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,kd=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},ti=(n,e,t)=>n.filter(r=>B(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return B(i)&&(s.participantAlt=i),B(e)&&(s.authorPn=e),B(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),ni=n=>B(n?.id)?{groupId:n.id,update:kd(n),timestamp:Date.now()}:null,ri=n=>{if(!B(n?.groupId)||!B(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return B(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},Ed=new Set(["add","invite","invite-link"]),Td=new Set(["remove","leave"]),si=n=>{if(!B(n?.id)||!Ed.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ti(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t},ii=n=>{if(!B(n?.id)||!Td.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ti(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t};var Id=["quick_reply","cta_url","cta_call","button_click"],xd=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,ai=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return $(n.key,e)},di=n=>Ae(n.messageTimestamp)??0,ci=(n,e)=>{if(!J(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},Dt=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},li=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return Nn(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return Nn(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Id.includes(i.name)){let o=ci(i.paramsJson,e.logger);if(!o)return null;let a=Dt(o,["id","button_id"]);return a===void 0?null:Nn(n,a,Dt(o,["display_text"])??null)}return null},Nn=(n,e,t)=>{let r=ai(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:di(n)};return J(t)&&(s.buttonText=t),s},ui=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return oi(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&xd.includes(i.name)){let o=ci(i.paramsJson,e.logger);if(!o)return null;let a=Dt(o,["row_id","id"]);return a===void 0?null:oi(n,a,Dt(o,["title"])??null)}return null},oi=(n,e,t)=>{let r=ai(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:di(n)};return J(t)&&(s.title=t),s};var Od=new Set(["available","unavailable","composing","recording","paused"]),Rd=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,pi=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},Ln=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:Rd(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},mi=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!Od.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},dt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var ue=(n,e)=>{let t=Ae(n);return t===null?e:t},Nd=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(d=>d?.messageText).filter(d=>typeof d=="string"&&d.length>0);if(a.length>0)return a.join(`
|
package/dist/plugin/types.d.ts
CHANGED
|
@@ -15,18 +15,21 @@ export interface PluginContext {
|
|
|
15
15
|
}
|
|
16
16
|
/** `'poll-vote'` reads as `pollVote()` on a plugin, so the method names stay idiomatic. */
|
|
17
17
|
type Camel<S extends string> = S extends `${infer Head}-${infer Tail}` ? `${Head}${Capitalize<Camel<Tail>>}` : S;
|
|
18
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
* One optional method per inbound event, derived so a new event is available here automatically.
|
|
20
|
+
* `message` is excluded — on a plugin that name belongs to the command handler.
|
|
21
|
+
*/
|
|
19
22
|
export type PluginEventHandlers = {
|
|
20
|
-
[E in keyof InboundEventMap as Camel<E>]?: (payload: InboundEventMap[E], ctx: PluginContext) => void | Promise<void>;
|
|
23
|
+
[E in Exclude<keyof InboundEventMap, 'message'> as Camel<E>]?: (payload: InboundEventMap[E], ctx: PluginContext) => void | Promise<void>;
|
|
21
24
|
};
|
|
22
25
|
/** Every inbound event name, in the order their methods are wired up. */
|
|
23
|
-
export declare const INBOUND_EVENTS: readonly ["
|
|
26
|
+
export declare const INBOUND_EVENTS: readonly ["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"];
|
|
24
27
|
export type Plugin = CommandMeta & CommandGuards & PluginEventHandlers & {
|
|
25
28
|
/** Identifies the plugin, and names the command that `command()` handles. */
|
|
26
29
|
name: string;
|
|
27
30
|
aliases?: string[];
|
|
28
31
|
/** Handles the command named after this plugin. The metadata above describes it. */
|
|
29
|
-
|
|
32
|
+
message?: (ctx: Parameters<CommandHandler>[0], plugin: PluginContext) => void | Promise<void>;
|
|
30
33
|
/** Escape hatch for what the methods above cannot express: extra commands, middleware, cleanup. */
|
|
31
34
|
setup?(ctx: PluginContext): void | (() => void) | Promise<void | (() => void)>;
|
|
32
35
|
onUnload?(): void | Promise<void>;
|