zaileys 4.8.6 → 4.8.7

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 CHANGED
@@ -1,30 +1,30 @@
1
- 'use strict';var Mc=require('baileys'),crypto=require('node:crypto'),Ee=require('node:fs/promises'),url=require('node:url'),os$1=require('node:os'),He=require('node:path'),child_process=require('node:child_process'),jimp=require('jimp'),Di=require('node-webpmux'),fs$1=require('node:fs');require('node:stream');var ta=require('qrcode-terminal'),sa=require('pino'),events=require('node:events');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Mc__default=/*#__PURE__*/_interopDefault(Mc);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var He__default=/*#__PURE__*/_interopDefault(He);var Di__default=/*#__PURE__*/_interopDefault(Di);var ta__default=/*#__PURE__*/_interopDefault(ta);var sa__default=/*#__PURE__*/_interopDefault(sa);var ki=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var m=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysBuilderError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var C={OPUS:{CODEC:"libopus",CHANNELS:1,FREQUENCY:48e3,BITRATE:"48k",FORMAT:"ogg"},THUMBNAIL:{SIZE:100,QUALITY:50,TIMESTAMP:"10%"},STICKER:{SIZE:512,MAX_DURATION:6,FPS:10,DEFAULT_QUALITY:60,COMPRESSION_LEVEL:6},MIME:{AUDIO:"audio/",VIDEO:"video/",IMAGE:"image/",GIF:"image/gif",MP4:"video/mp4"}},Un="ffmpeg",qn="ffprobe",Fn=false,tn=async(n=false)=>{if(!(n||Fn)){Fn=true;try{let e=(await import('@ffmpeg-installer/ffmpeg')).default;if(e?.path){Un=e.path;let t=He__default.default.dirname(e.path),r=process.platform==="win32"?";":":",s=process.env.PATH??"";s.split(r).includes(t)||(process.env.PATH=`${t}${r}${s}`);}}catch{}try{let e=(await import('@ffprobe-installer/ffprobe')).default;e?.path&&(qn=e.path);}catch{}}},ut=()=>Date.now().toString(36)+Math.random().toString(36).slice(2,8),N=async n=>{let{fileTypeFromBuffer:e}=await import('file-type');return e(n)},V=class{static generateUniqueId(){return `${Date.now()}_${Math.random().toString(36).slice(2,11)}`}static createTempPath(e,t){return He__default.default.join(os$1.tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>Ee__default.default.unlink(t)));}static async safeReadFile(e){try{return await Ee__default.default.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await Ee__default.default.writeFile(e,t);}catch{throw new Error(`Failed to write file: ${e}`)}}},k=class{static async toBuffer(e){if(Buffer.isBuffer(e))return e;if(e instanceof ArrayBuffer)return Buffer.from(e);if(typeof e=="string")return this.fromString(e);throw new Error("Invalid input type: expected string, Buffer, or ArrayBuffer")}static async fromString(e){if(e.startsWith("http://")||e.startsWith("https://"))return this.fromUrl(e);try{if(await Ee__default.default.stat(e).then(t=>t.isFile()).catch(()=>!1))return await Ee__default.default.readFile(e)}catch{}return Buffer.from(e,"base64")}static async fromUrl(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let r=await t.arrayBuffer();return Buffer.from(r)}catch(t){throw new Error(`Failed to fetch URL: ${t instanceof Error?t.message:String(t)}`)}}static async getExtension(e){let{fileTypeFromBuffer:t}=await import('file-type'),r=await t(e);if(!r)return "tmp";let s=r.ext.toLowerCase();return ["wav","ogg","mp4","gif","jpg","webp","tmp","mp3","png"].includes(s)?s:"tmp"}},L=class{static validate(e,t){if(!e?.mime?.startsWith(t))throw new Error(`Invalid file type: expected ${t}*, got ${e?.mime||"unknown"}`)}static isMedia(e){return e.startsWith(C.MIME.IMAGE)||e.startsWith(C.MIME.VIDEO)}static isAnimated(e){return e===C.MIME.GIF||e.startsWith(C.MIME.VIDEO)}},ee=class{static async process(e){return await tn(),new Promise((t,r)=>{let s=["-y","-i",e.input,...e.options,e.output],i=child_process.spawn(Un,s,{stdio:"ignore"});i.on("close",async o=>{if(o===0)try{await e.onEnd(),t();}catch(a){r(a);}else try{let a=new Error(`FFmpeg exited with code ${o}`);await e.onError(a),r(a);}catch(a){r(a);}}),i.on("error",async o=>{try{await e.onError(o);}finally{r(o);}});})}static async getDuration(e){return new Promise((t,r)=>{let s=child_process.spawn(qn,["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),i="";s.stdout.on("data",o=>i+=o.toString()),s.on("close",o=>{o===0?t(parseFloat(i.trim())||0):r(new Error(`ffprobe exited with code ${o}`));}),s.on("error",r);})}};var xi=3e4,Kn="application/octet-stream",me=async n=>n.byteLength===0?Kn:(await N(n))?.mime??Kn,ke=async n=>({buffer:n,mime:await me(n),size:n.byteLength}),$n=async(n,e)=>{let t=new AbortController,r=setTimeout(()=>t.abort(),e);try{let s=await fetch(n,{signal:t.signal});if(!s.ok)throw new m("MEDIA_LOAD_FAILED",`fetch ${n} failed with status ${s.status}`,{cause:s.status});return Buffer.from(await s.arrayBuffer())}catch(s){throw s instanceof m?s:new m("MEDIA_LOAD_FAILED",`fetch ${n} failed: ${s.message}`,{cause:s})}finally{clearTimeout(r);}},Gn=async n=>{try{return await Ee.readFile(n)}catch(e){throw new m("MEDIA_LOAD_FAILED",`read ${n} failed: ${e.message}`,{cause:e})}},Ri=n=>n.startsWith("http://")||n.startsWith("https://"),x=async(n,e)=>{await tn();let t=e?.timeoutMs??xi;return Buffer.isBuffer(n)?ke(n):n instanceof URL?n.protocol==="file:"?ke(await Gn(url.fileURLToPath(n))):ke(await $n(n.toString(),t)):Ri(n)?ke(await $n(n,t)):ke(await Gn(n))};var ge=async(n,e)=>{let{buffer:t}=await x(n),r={image:t};return e?.caption!==void 0&&(r.caption=e.caption),e?.viewOnce!==void 0&&(r.viewOnce=e.viewOnce),r};var te=async(n,e)=>{let{buffer:t,mime:r}=await x(n);if(!r.startsWith("video/"))throw new m("INVALID_OPTIONS",`video() expects a video source, got mime ${r}`);let s={video:t};return e?.caption!==void 0&&(s.caption=e.caption),e?.gifPlayback!==void 0&&(s.gifPlayback=e.gifPlayback),e?.viewOnce!==void 0&&(s.viewOnce=e.viewOnce),e?.ptv===true&&(s.ptv=true),s};var Jn=2,Vn=30,_i=async n=>{if(n.type==="image")return ge(n.src,n.caption!==void 0?{caption:n.caption}:void 0);if(n.type==="video")return te(n.src,n.caption!==void 0?{caption:n.caption}:void 0);throw new m("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(n.type)}`)},Hn=async(n,e,t,r)=>{if(!Array.isArray(t)||t.length<Jn)throw new m("INVALID_OPTIONS",`album() requires a minimum of ${Jn} items`);if(t.length>Vn)throw new m("INVALID_OPTIONS",`album() accepts a maximum of ${Vn} items`);let s=0,i=0;for(let u of t)if(u.type==="image")s+=1;else if(u.type==="video")i+=1;else throw new m("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(u.type)}`);let o={album:{expectedImageCount:s,expectedVideoCount:i}};r.mentions&&r.mentions.length>0&&(o.mentions=r.mentions),r.mentionAll&&(o.mentionAll=true);let a={};r.quoted&&(a.quoted=r.quoted),r.disappearingSeconds!==void 0&&(a.ephemeralExpiration=r.disappearingSeconds);let c;try{c=await n.sendMessage(e,o,a);}catch(u){throw new m("SEND_FAILED","album parent send rejected",{cause:u})}let d=c?.key;if(!d)throw new m("SEND_FAILED","album parent returned no message key");let l=0;for(let u of t){let y=await _i(u);y.albumParentKey=d;try{await n.sendMessage(e,y);}catch(M){throw new m("SEND_FAILED","album child send rejected",{cause:{parentKey:d,index:l,error:M}})}l+=1;}return d};var U=async(n,e,t,r,s)=>{let i=r.replace(/[^a-z0-9]+/gi,"_").toLowerCase(),o=V.createTempPath(`${i}_in`,e),a=V.createTempPath(`${i}_out`,t);await V.safeWriteFile(o,n);try{let c=typeof s=="function"?await s(o):s;return await ee.process({input:o,output:a,options:c,onEnd:async()=>{},onError:async()=>{}}),await V.safeReadFile(a)}catch(c){throw new Error(`${r} failed: ${c instanceof Error?c.message:String(c)}`)}finally{await V.cleanup([o,a]);}};var pt=64,zn=8e3,ne=class{static async toOpus(e){return this.convert(e,"opus")}static async toMp3(e){return this.convert(e,"mp3")}static async convert(e,t="opus"){let r=await k.toBuffer(e);L.validate(await N(r),C.MIME.AUDIO);let s=await k.getExtension(r),i=t==="opus"?["-vn","-c:a","libopus","-b:a","48k","-ac","1","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","ogg"]:["-vn","-c:a","libmp3lame","-b:a","128k","-ac","2","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","mp3"];return U(r,s,t==="opus"?"ogg":"mp3",`${t.toUpperCase()} conversion`,i)}static async waveform(e){let t=await k.toBuffer(e),r=await k.getExtension(t),s=await U(t,r,"tmp","Waveform generation",["-vn","-ac","1","-ar",String(zn),"-f","s16le"]),i=Math.floor(s.length/2);return {waveform:this.computeWaveform(s),seconds:Math.max(1,Math.round(i/zn))}}static computeWaveform(e){let t=Math.floor(e.length/2),r=new Uint8Array(pt);if(t===0)return r;let s=Math.max(1,Math.floor(t/pt)),i=[];for(let a=0;a<pt;a++){let c=0,d=0;for(let l=0;l<s;l++){let u=(a*s+l)*2;u+1<e.length&&(c+=Math.abs(e.readInt16LE(u)),d+=1);}i.push(d>0?c/d:0);}let o=Math.max(...i)||1;for(let a=0;a<pt;a++)r[a]=Math.floor(i[a]/o*100);return r}};var Li=["-c:v","libx264","-preset","ultrafast","-crf","28","-c:a","aac","-b:a","128k","-movflags","+faststart","-vf","scale=trunc(iw/2)*2:trunc(ih/2)*2","-pix_fmt","yuv420p","-f","mp4"],q=class{static async toMp4(e){let t=await k.toBuffer(e);L.validate(await N(t),C.MIME.VIDEO);let r=await k.getExtension(t);return U(t,r,"mp4","Video re-encoding",Li)}static async thumbnail(e){let t=await k.toBuffer(e);L.validate(await N(t),C.MIME.VIDEO);let r=await k.getExtension(t),s=C.THUMBNAIL.SIZE;return (await U(t,r,"jpg","Thumbnail generation",async o=>{let a=await ee.getDuration(o);return ["-ss",Math.max(0,a*.1).toString(),"-vframes","1","-s",`${s}x${s}`]})).toString("base64")}static async duration(e){return ee.getDuration(e)}};var fe=null,Yn=false;async function Ni(){if(Yn)return fe;Yn=true;let n=e=>{typeof e=="function"&&(fe=e);};try{n(ki("sharp"));}catch{fe=null;}if(!fe)try{let e=await import('sharp');n(e.default??e);}catch{fe=null;}return fe}function Zn(n,e){let t=new Uint8Array(n*n),r=n/2,s=n/2,i=n/10,o=[[i,i],[n-i,i],[i,n-i],[n-i,n-i]];for(let a=0;a<n;a++)for(let c=0;c<n;c++){let d=false;if(e==="circle"){let l=c-r,u=a-s;d=l*l+u*u<=r*r;}else if(e==="rounded"){let l=c>=i&&c<n-i&&a>=0&&a<n,u=c>=0&&c<n&&a>=i&&a<n-i,y=false;for(let M of o){let v=c-M[0],P=a-M[1];if(v*v+P*P<=i*i){y=true;break}}d=l||u||y;}else if(e==="oval"){let l=(c-r)/(n/2),u=(a-s)/(n/3);d=l*l+u*u<=1;}t[a*n+c]=d?255:0;}return t}var nn=class{sharp;constructor(e){this.sharp=e;}async thumbnail(e){let t=this.sharp,r=t(e).resize(C.THUMBNAIL.SIZE,C.THUMBNAIL.SIZE,{fit:"cover"});return (await r.metadata()).format==="gif"&&(r=t(e,{pages:1}).resize(C.THUMBNAIL.SIZE,C.THUMBNAIL.SIZE)),(await r.jpeg({quality:C.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}async resize(e,t,r){return this.sharp(e).resize(t,r,{fit:"cover"}).png().toBuffer()}async toJpeg(e){let t=this.sharp,r=await k.toBuffer(e),s=await t(r).metadata();if(!s.format)throw new Error("Invalid image type: format could not be determined");return s.format==="webp"||s.format==="png"?t(r).jpeg().toBuffer():r}async resizeForSticker(e,t,r="default"){let s=this.sharp,i=C.STICKER.SIZE,o=s(e).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}});if(r!=="default"){let a=Buffer.from(Zn(i,r)),c=s(a,{raw:{width:i,height:i,channels:1}});o=o.joinChannel(await c.png().toBuffer());}return o.webp({quality:t}).toBuffer()}},rn=class{async thumbnail(e){let t=C.THUMBNAIL.SIZE,r=await jimp.Jimp.fromBuffer(e);r.cover({w:t,h:t});let s=await r.getBuffer("image/jpeg",{quality:C.THUMBNAIL.QUALITY});return Buffer.from(s).toString("base64")}async resize(e,t,r){let s=await jimp.Jimp.fromBuffer(e);s.cover({w:t,h:r});let i=await s.getBuffer("image/png");return Buffer.from(i)}async toJpeg(e){let t=await k.toBuffer(e);try{let s=await(await jimp.Jimp.fromBuffer(t)).getBuffer("image/jpeg");return Buffer.from(s)}catch{return t}}async resizeForSticker(e,t,r="default"){let s=C.STICKER.SIZE,i=await jimp.Jimp.fromBuffer(e);if(i.contain({w:s,h:s}),r!=="default"){let c=Zn(s,r),d=new jimp.Jimp({width:s,height:s,color:255});for(let l=0;l<s;l++)for(let u=0;u<s;u++)c[l*s+u]===255&&d.setPixelColor(4294967295,u,l);i.mask(d);}let o=Buffer.from(await i.getBuffer("image/png")),a=Math.max(1,Math.min(100,t));return U(o,"png","webp","Jimp WebP conversion",["-vcodec","libwebp","-q:v",`${a}`,"-preset","default"])}},Ie=null;async function mt(){if(Ie)return Ie;let n=await Ni();return n?Ie=new nn(n):(console.warn("\x1B[33m%s\x1B[0m","[media-process] Jimp is slow. For faster performance, run: npm install sharp"),Ie=new rn),Ie}var F=class{static async thumbnail(e){return (await mt()).thumbnail(e)}static async resize(e,t,r){return (await mt()).resize(e,t,r)}static async toJpeg(e){return (await mt()).toJpeg(e)}static async resizeForSticker(e,t,r="default"){return (await mt()).resizeForSticker(e,t,r)}};var he=class n{static defaultMetadata={packageName:"Zaileys Library",authorName:"https://github.com/zeative/zaileys"};static setDefaultMetadata(e){e&&(n.defaultMetadata={...n.defaultMetadata,...e});}static getDefaultMetadata(){return {...n.defaultMetadata}}static async create(e,t){try{let r=await k.toBuffer(e),s=await N(r);if(!s)throw new Error("Unable to detect file type");let i=t?.quality||C.STICKER.DEFAULT_QUALITY,o=L.isAnimated(s.mime),a=t?.shape||"default",c=s.mime==="image/webp"?r:o?await this.processAnimated(r,s.mime,i):await F.resizeForSticker(r,i,a),d=this.createExifMetadata(t),l=new Di__default.default.Image;await l.load(c),l.exif=d;let u=await l.save(null);return Buffer.isBuffer(u)?u:Buffer.from(u)}catch(r){throw new Error(`Sticker creation failed: ${r instanceof Error?r.message:String(r)}`)}}static createExifMetadata(e){let t=e?.pack??e?.packageName??e?.packname??n.defaultMetadata.pack??n.defaultMetadata.packageName??n.defaultMetadata.packname??"Zaileys Library",r=e?.author??e?.authorName??e?.publisher??n.defaultMetadata.author??n.defaultMetadata.authorName??n.defaultMetadata.publisher??"https://github.com/zeative/zaileys",s={"sticker-pack-id":ut(),"sticker-pack-name":t,"sticker-pack-publisher":r,emojis:["\u{1F913}"],"android-app-store-link":"https://play.google.com/store/apps/details?id=com.marsvard.stickermakerforwhatsapp","ios-app-store-link":"https://itunes.apple.com/app/sticker-maker-studio/id1443326857"},i=Buffer.from([73,73,42,0,8,0,0,0,1,0,65,87,7,0,0,0,0,0,22,0,0,0]),o=Buffer.from(JSON.stringify(s),"utf8"),a=Buffer.concat([i,o]);return a.writeUIntLE(o.length,14,4),a}static async processAnimated(e,t,r){let s=C.STICKER.SIZE,i=C.STICKER.FPS,o=`scale=${s}:${s}:force_original_aspect_ratio=decrease,fps=${i},pad=${s}:${s}:(ow-iw)/2:(oh-ih)/2:color=0x00000000,format=rgba`,a=Math.max(1,Math.min(100,r));return U(e,this.getExtension(t),"webp","Animated sticker processing",async c=>{let d=C.STICKER.MAX_DURATION;try{d=Math.min(await q.duration(c),C.STICKER.MAX_DURATION);}catch{console.warn("Using default duration:",C.STICKER.MAX_DURATION);}return ["-vcodec libwebp",`-vf ${o}`,`-q:v ${a}`,"-loop 0","-preset default","-an","-vsync 0",`-t ${d}`,`-compression_level ${C.STICKER.COMPRESSION_LEVEL}`]})}static getExtension(e){return e===C.MIME.GIF?"gif":e.startsWith(C.MIME.VIDEO)?"mp4":"tmp"}};var gt=class{static async create(e){try{let t=await k.toBuffer(e),r=await N(t);if(!r)throw new Error("Unable to detect file type");let s;return r.mime.startsWith(C.MIME.VIDEO)?s=await q.thumbnail(t):L.isMedia(r.mime)?s=await F.thumbnail(t):s="",{document:t,mimetype:r.mime,ext:r.ext,fileName:ut(),jpegThumbnail:s}}catch(t){throw new Error(`Document creation failed: ${t instanceof Error?t.message:String(t)}`)}}};var re=class{input;constructor(e){this.input=e;}get audio(){return {toOpus:()=>ne.toOpus(this.input),toMp3:()=>ne.toMp3(this.input),convert:(e="opus")=>ne.convert(this.input,e),waveform:()=>ne.waveform(this.input)}}get video(){return {toMp4:()=>q.toMp4(this.input),thumbnail:()=>q.thumbnail(this.input)}}get image(){return {toJpeg:()=>F.toJpeg(this.input),thumbnail:async()=>{let e=await k.toBuffer(this.input);return F.thumbnail(e)},resize:async(e,t)=>{let r=await k.toBuffer(this.input);return F.resize(r,e,t)}}}get sticker(){return {create:e=>he.create(this.input,e)}}get document(){return {create:()=>gt.create(this.input)}}get thumbnail(){return {get:async()=>{let e=await k.toBuffer(this.input),t=await N(e);if(!t||!L.isMedia(t.mime))throw new Error("Invalid media type: expected image or video");return t.mime.startsWith(C.MIME.VIDEO)?q.thumbnail(this.input):F.thumbnail(e)}}}async toBuffer(){return k.toBuffer(this.input)}};var Qn=async(n,e)=>{let{buffer:t}=await x(n),r;try{r=await new re(t).audio.toOpus();}catch(o){throw new m("MEDIA_LOAD_FAILED",`audio() transcode failed: ${o.message}`,{cause:o})}let s=e?.ptt??true,i={audio:r,ptt:s};if(s)try{let{waveform:o,seconds:a}=await new re(t).audio.waveform();i.waveform=o,e?.seconds===void 0&&(i.seconds=a);}catch{}return e?.seconds!==void 0&&(i.seconds=e.seconds),i};var Xn=10,R="__zaileysRelayMessage",sn="__zaileysHeaderMedia",ft="__zaileysRequireGroupJid",H=n=>typeof n=="string"&&n.length>0,Bi=n=>{let e=n.text;if(!H(e)||e.trim().length===0)throw new m("INVALID_OPTIONS","button text must be a non-empty string");return e},Wi=(n,e)=>{let t=n.type??"reply";if(t==="location"){let s=n.text;return {name:"send_location",buttonParamsJson:JSON.stringify(H(s)?{display_text:s}:{})}}let r=Bi(n);if(t==="reply"){let s=n.id;if(!H(s))throw new m("INVALID_OPTIONS","reply button requires a non-empty id");if(e.has(s))throw new m("INVALID_OPTIONS",`duplicate button id: ${s}`);return e.add(s),{name:"quick_reply",buttonParamsJson:JSON.stringify({display_text:r,id:s})}}if(t==="url"){let s=n.url;if(!H(s))throw new m("INVALID_OPTIONS","url button requires a non-empty url");let i=n.webview===true;return {name:"cta_url",buttonParamsJson:JSON.stringify({display_text:r,url:s,merchant_url:s,webview_interaction:i})}}if(t==="copy"){let s=n.code;if(!H(s))throw new m("INVALID_OPTIONS","copy button requires a non-empty code");return {name:"cta_copy",buttonParamsJson:JSON.stringify({display_text:r,id:s,copy_code:s})}}if(t==="call"){let s=n.phone;if(!H(s))throw new m("INVALID_OPTIONS","call button requires a non-empty phone");return {name:"cta_call",buttonParamsJson:JSON.stringify({display_text:r,id:s,phone_number:s})}}if(t==="reminder"||t==="cancel-reminder"){let s=n.id;return {name:t==="reminder"?"cta_reminder":"cta_cancel_reminder",buttonParamsJson:JSON.stringify({display_text:r,id:H(s)?s:r})}}if(t==="address"){let s=n.id;return {name:"address_message",buttonParamsJson:JSON.stringify({display_text:r,id:H(s)?s:r})}}throw new m("INVALID_OPTIONS",`unknown button type: ${String(t)}`)},Fi=n=>{let e={};if(n?.bottomSheet){let t=n.bottomSheet;e.bottom_sheet={...t.buttonsLimit!==void 0?{in_thread_buttons_limit:t.buttonsLimit}:{},...t.dividers!==void 0?{divider_indices:t.dividers}:{},...t.listTitle!==void 0?{list_title:t.listTitle}:{},...t.buttonTitle!==void 0?{button_title:t.buttonTitle}:{}};}if(n?.limitedTimeOffer){let t=n.limitedTimeOffer;e.limited_time_offer={...t.text!==void 0?{text:t.text}:{},...t.url!==void 0?{url:t.url}:{},...t.copyCode!==void 0?{copy_code:t.copyCode}:{},...t.expiresAt!==void 0?{expiration_time:t.expiresAt}:{}};}return Object.keys(e).length>0?JSON.stringify(e):""},on=n=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","buttons() requires at least one button");if(n.length>Xn)throw new m("INVALID_OPTIONS",`buttons() accepts at most ${Xn} buttons`);let e=new Set;return n.map(t=>Wi(t,e))},ht=(n,e)=>{let t=on(n),r={body:{text:e?.text&&e.text.length>0?e.text:" "},nativeFlowMessage:{buttons:t,messageParamsJson:Fi(e)}};e?.footer&&e.footer.length>0&&(r.footer={text:e.footer});let s=e?.image?{kind:"image",src:e.image}:e?.video?{kind:"video",src:e.video}:void 0;return (e?.title&&e.title.length>0||e?.subtitle&&e.subtitle.length>0||s)&&(r.header={title:e?.title??"",subtitle:e?.subtitle??"",hasMediaAttachment:s!==void 0}),s!==void 0?{[R]:{interactiveMessage:r},[sn]:s}:{[R]:{interactiveMessage:r}}};var er=10,an="__zaileysCardsMedia",tr=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","carousel() requires at least one card");if(n.length>er)throw new m("INVALID_OPTIONS",`carousel() accepts at most ${er} cards`);let t=[],r=n.map((o,a)=>{let c={body:{text:o.body&&o.body.length>0?o.body:" "}};o.buttons&&o.buttons.length>0&&(c.nativeFlowMessage={buttons:on(o.buttons),messageParamsJson:""}),o.footer&&o.footer.length>0&&(c.footer={text:o.footer});let d=o.image?{kind:"image",src:o.image}:o.video?{kind:"video",src:o.video}:void 0;return (o.title&&o.title.length>0||o.subtitle&&o.subtitle.length>0||d)&&(c.header={title:o.title??"",subtitle:o.subtitle??"",hasMediaAttachment:d!==void 0}),d&&t.push({...d,index:a}),c}),s={body:{text:e?.text&&e.text.length>0?e.text:" "},carouselMessage:{cards:r}};return t.length>0?{[R]:{interactiveMessage:s},[an]:t}:{[R]:{interactiveMessage:s}}};var Ui=n=>{let e=[],t="",r=0,s=1,i=0,o=0,a=[];for(let c=0;c<n.length;c++)if(n[c]==="["&&n[c-1]!=="\\")a.push(c);else if(n[c]==="]"&&(n[c+1]==="("||n[c+1]==="<")){let d=a.pop();if(d==null)continue;let l=n[c+1],u=l==="("?")":">",y=l==="<",M=c+2,v=1;for(;M<n.length&&v>0;)n[M]===l&&n[M-1]!=="\\"?v++:n[M]===u&&n[M-1]!=="\\"&&v--,M++;if(v>0)continue;let P=n.slice(d+1,c).trim(),w=n.slice(c+2,M-1).trim(),p,g;if(y){let[b="",E="",pe="",Zt="",Qt=""]=P.split("|").map(Xt=>Xt.trim());p=`zaileys_LATEX_${o++}`,g=`{{${p}}}${b||"image"}{{/${p}}}`,e.push({type:"latex",ie:{key:p,text:b,url:w,width:E,height:pe,font_height:Zt,padding:Qt}});}else P?(p=`zaileys_HYPERLINK_${i++}`,g=`{{${p}}}${w}{{/${p}}}`,e.push({type:"hyperlink",ie:{key:p,text:P,url:w}})):(p=`zaileys_CITATION_${s-1}`,g=`{{${p}}}${w}{{/${p}}}`,e.push({type:"citation",ie:{key:p,reference_id:String(s++),url:w}}));t+=n.slice(r,d)+g,r=M,c=M-1;}return t+=n.slice(r),{text:t,ie:e}},qi=n=>n.ie.map(({type:e,ie:t})=>e==="hyperlink"?{key:t.key,metadata:{display_name:t.text,is_trusted:true,url:t.url,__typename:"GenAIInlineLinkItem"}}:e==="latex"?{key:t.key,metadata:{latex_expression:t.text,latex_image:{url:t.url,width:Number(t.width)||100,height:Number(t.height)||100},font_height:Number(t.font_height)||83.33333333333333,padding:Number(t.padding)||15,__typename:"GenAILatexItem"}}:{key:t.key,metadata:{reference_id:Number(t.reference_id),reference_url:t.url,reference_title:t.url,reference_display_name:t.url,sources:[],__typename:"GenAISearchCitationItem"}}),Ki=n=>{if(!Array.isArray(n)||n.length===0||!n.every(i=>Array.isArray(i)))throw new m("INVALID_OPTIONS","table must be a non-empty array of string rows");let[e,...t]=n,r=Math.max(e.length,...t.map(i=>i.length)),s=i=>[...i,...Array(r-i.length).fill("")];return [{is_header:true,cells:s(e)},...t.map(i=>({is_header:false,cells:s(i)}))]},$i={0:"DEFAULT",1:"KEYWORD",2:"METHOD",3:"STR",4:"NUMBER",5:"COMMENT"},yt=new Set(["break","case","catch","continue","debugger","delete","do","else","finally","for","function","if","in","instanceof","new","return","switch","this","throw","try","typeof","var","void","while","with","true","false","null","undefined","class","const","let","super","extends","export","import","from","as","default","yield","static","constructor","async","await","get","set"]),Gi={javascript:yt,js:yt,typescript:yt,ts:yt},Ji=(n,e)=>{let t=Gi[e.toLowerCase()]??new Set,r=[],s=(o,a)=>{if(!o)return;let c=r[r.length-1];c&&c.highlightType===a?c.codeContent+=o:r.push({codeContent:o,highlightType:a});},i=0;for(;i<n.length;){let o=n[i];if(/\s/.test(o)){let a=i;for(;i<n.length&&/\s/.test(n[i]);)i++;s(n.slice(a,i),0);continue}if(o==="/"&&n[i+1]==="/"){let a=i;for(i+=2;i<n.length&&n[i]!==`
2
- `;)i++;s(n.slice(a,i),5);continue}if(o==='"'||o==="'"||o==="`"){let a=i,c=o;for(i++;i<n.length;)if(n[i]==="\\"&&i+1<n.length)i+=2;else if(n[i]===c){i++;break}else i++;s(n.slice(a,i),3);continue}if(/[0-9]/.test(o)){let a=i;for(;i<n.length&&/[0-9.]/.test(n[i]);)i++;s(n.slice(a,i),4);continue}if(/[a-zA-Z_$]/.test(o)){let a=i;for(;i<n.length&&/[a-zA-Z0-9_$]/.test(n[i]);)i++;let c=n.slice(a,i),d=0;if(t.has(c))d=1;else {let l=i;for(;l<n.length&&/\s/.test(n[l]);)l++;n[l]==="("&&(d=2);}s(c,d);continue}s(o,0),i++;}return r},D=(n,e)=>({view_model:{[Array.isArray(e)?"primitives":"primitive"]:e,__typename:`GenAI${n}LayoutViewModel`}}),Vi="https://github.com/zeative/zaileys",nr=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","text({ rich: true }) requires non-empty markdown content");let t=[],r=[];for(let o of n)if(o.type==="text"){let a=Ui(o.text),c=qi(a);r.push({messageType:2,messageText:a.text}),t.push(D("Single",{text:a.text,...c.length>0?{inline_entities:c}:{},__typename:"GenAIMarkdownTextUXPrimitive"}));}else if(o.type==="code"){let a=o.language??"plaintext",c=Ji(o.content,a);r.push({messageType:5,codeMetadata:{codeLanguage:a,codeBlocks:c}}),t.push(D("Single",{language:a,code_blocks:c.map(d=>({content:d.codeContent,type:$i[d.highlightType]})),__typename:"GenAICodeUXPrimitive"}));}else if(o.type==="table"){let a=Ki(o.rows);r.push({messageType:4,tableMetadata:{title:"",rows:a.map(c=>({items:c.cells,...c.is_header?{isHeading:true}:{}}))}}),t.push(D("Single",{rows:a,__typename:"GenATableUXPrimitive"}));}else if(o.type==="image"){let a=Array.isArray(o.url)?o.url:[o.url];if(a.length===0)throw new m("INVALID_OPTIONS","image requires at least one url");r.push({messageType:1,gridImageMetadata:{gridImageUrl:{imagePreviewUrl:a[0]},imageUrls:a.map(c=>({imagePreviewUrl:c,imageHighResUrl:c,sourceUrl:Vi}))}});for(let c of a)t.push(D("Single",{media:{url:c,mime_type:"image/png"},imagine_type:"IMAGE",status:{status:"READY"},__typename:"GenAIImaginePrimitive"}));}else if(o.type==="video"){let a=Array.isArray(o.url)?o.url:[o.url];if(a.length===0)throw new m("INVALID_OPTIONS","video requires at least one url");r.push({messageType:2,messageText:"[ CANNOT_LOAD_VIDEO - zaileys ]"});for(let c of a)t.push(D("Single",{media:{url:c,mime_type:"video/mp4",duration:o.duration??0},imagine_type:"ANIMATE",status:{status:"READY"},__typename:"GenAIImaginePrimitive"}));}else if(o.type==="product"){let a=Array.isArray(o.products),c=a?o.products:[o.products];if(c.length===0)throw new m("INVALID_OPTIONS","product requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_PRODUCT - zaileys ]"});let d=c.map(l=>({title:l.title,brand:l.brand??"",price:l.price??"",sale_price:l.salePrice??"",product_url:l.url??"",image:{url:l.image??""},additional_images:[{url:l.icon??""}],__typename:"GenAIProductItemCardPrimitive"}));t.push(a?D("HScroll",d):D("Single",d[0]));}else if(o.type==="reels"){let a=Array.isArray(o.reels)?o.reels:[o.reels];if(a.length===0)throw new m("INVALID_OPTIONS","reels requires at least one item");r.push({messageType:9,contentItemsMetadata:{contentType:1,itemsMetadata:a.map(c=>({reelItem:{title:c.username??"",profileIconUrl:c.profileUrl??"",thumbnailUrl:c.thumbnail??"",videoUrl:c.url??""}}))}}),t.push(D("HScroll",a.map(c=>({reels_url:c.url??"",thumbnail_url:c.thumbnail??"",creator:c.username??c.title??"",avatar_url:c.profileUrl??"",reels_title:c.title??"",likes_count:c.likes??0,shares_count:c.shares??0,view_count:c.views??0,reel_source:c.source??"IG",is_verified:!!c.verified,__typename:"GenAIReelPrimitive"}))));}else if(o.type==="post"){let a=Array.isArray(o.posts)?o.posts:[o.posts];if(a.length===0)throw new m("INVALID_OPTIONS","post requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_POST - zaileys ]"}),t.push(D("HScroll",a.map(c=>({title:c.title??"",subtitle:c.subtitle??"",username:c.username??"",profile_picture_url:c.profileUrl??"",is_verified:!!c.verified,thumbnail_url:c.thumbnail??"",post_caption:c.caption??"",likes_count:c.likes??0,comments_count:c.comments??0,shares_count:c.shares??0,post_url:c.url??"",post_deeplink:c.deeplink??"",source_app:c.source??"INSTAGRAM",footer_label:c.footer??"",footer_icon:c.icon??"",is_carousel:a.length>1,orientation:c.orientation??"LANDSCAPE",post_type:c.postType??"VIDEO",__typename:"GenAIPostPrimitive"}))));}else if(o.type==="tip")r.push({messageType:2,messageText:o.text}),t.push(D("Single",{text:o.text,__typename:"GenAIMetadataTextPrimitive"}));else {let a=Array.isArray(o.prompts)?o.prompts:[o.prompts];if(a.length===0)throw new m("INVALID_OPTIONS","suggest requires at least one prompt");t.push(D("ActionRow",a.map(c=>({prompt_text:c,prompt_type:"SUGGESTED_PROMPT",__typename:"GenAIFollowUpSuggestionPillPrimitive"}))));}e?.footer&&e.footer.length>0&&t.push(D("Single",{text:e.footer,__typename:"GenAIMetadataTextPrimitive"}));let s=(e?.sources??[]).map(([o,a,c])=>({source_type:"THIRD_PARTY",source_display_name:c??"",source_subtitle:"AI",source_url:a??"",favicon:{url:o??"",mime_type:"image/jpeg",width:16,height:16}})),i={messageContextInfo:{deviceListMetadata:{},deviceListMetadataVersion:2,botMetadata:{messageDisclaimerText:e?.title??"",richResponseSourcesMetadata:{sources:s}}},botForwardedMessage:{message:{richResponseMessage:{messageType:1,submessages:r,unifiedResponse:{data:Buffer.from(JSON.stringify({response_id:crypto.randomUUID(),sections:t})).toString("base64")},contextInfo:{forwardingScore:1,isForwarded:true,forwardedAiBotMessageInfo:{botJid:"0@bot"},forwardOrigin:4}}}}};return {[R]:i}};var Hi=/^:::([a-zA-Z]+)\s*$/,zi=/^:::\s*$/,rr=/^```(\w*)\s*$/,sr=/^!\[[^\]]*\]\(([^)]+)\)\s*$/,Yi=/^\s*\|?\s*:?-{2,}[\s|:-]*$/,wt=n=>n.split("|").map(e=>e.trim()),cn=n=>{let e={};for(let t of wt(n)){let r=t.indexOf(":");if(r===-1)continue;let s=t.slice(0,r).trim().toLowerCase(),i=t.slice(r+1).trim();s.length>0&&(e[s]=i);}return e},se=n=>{if(n===void 0||n.trim().length===0)return;let e=Number(n);return Number.isNaN(e)?void 0:e},or=n=>n==="true"||n==="1"||n==="yes",ir=n=>{let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())},Zi=n=>{let e=cn(n),t=e.title;if(t===void 0||t.length===0)return null;let r={title:t};return e.price&&(r.price=e.price),e.sale&&(r.salePrice=e.sale),e.saleprice&&(r.salePrice=e.saleprice),e.brand&&(r.brand=e.brand),e.url&&(r.url=e.url),e.image&&(r.image=e.image),e.icon&&(r.icon=e.icon),r},Qi=n=>{let e=cn(n),t={};e.user&&(t.username=e.user),e.username&&(t.username=e.username),e.title&&(t.title=e.title),e.profile&&(t.profileUrl=e.profile),e.thumb&&(t.thumbnail=e.thumb),e.url&&(t.url=e.url);let r=se(e.likes);r!==void 0&&(t.likes=r);let s=se(e.shares);s!==void 0&&(t.shares=s);let i=se(e.views);return i!==void 0&&(t.views=i),e.source&&(t.source=e.source),"verified"in e&&(t.verified=or(e.verified)),t},Xi=n=>{let e=cn(n),t={};e.user&&(t.username=e.user),e.username&&(t.username=e.username),e.title&&(t.title=e.title),e.subtitle&&(t.subtitle=e.subtitle),e.profile&&(t.profileUrl=e.profile),e.thumb&&(t.thumbnail=e.thumb),e.caption&&(t.caption=e.caption);let r=se(e.likes);r!==void 0&&(t.likes=r);let s=se(e.comments);s!==void 0&&(t.comments=s);let i=se(e.shares);return i!==void 0&&(t.shares=i),e.url&&(t.url=e.url),e.source&&(t.source=e.source),e.footer&&(t.footer=e.footer),e.icon&&(t.icon=e.icon),"verified"in e&&(t.verified=or(e.verified)),t},eo=(n,e)=>{let t=e.map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(r=>r.length>0);if(n==="suggest"){let r=t.flatMap(s=>wt(s)).filter(s=>s.length>0);return r.length>0?{type:"suggest",prompts:r}:null}if(n==="tip")return t.length>0?{type:"tip",text:t.join(`
3
- `)}:null;if(n==="image")return t.length>0?{type:"image",url:t.length===1?t[0]:t}:null;if(n==="video"){if(t.length===0)return null;let r=t.map(o=>wt(o)[0]??"").filter(o=>o.length>0);if(r.length===0)return null;let s=se(wt(t[0])[1]),i={type:"video",url:r.length===1?r[0]:r};return s!==void 0&&(i.duration=s),i}if(n==="product"){let r=t.map(Zi).filter(s=>s!==null);return r.length>0?{type:"product",products:r.length===1?r[0]:r}:null}if(n==="reels"){let r=t.map(Qi);return r.length>0?{type:"reels",reels:r}:null}if(n==="post"){let r=t.map(Xi);return r.length>0?{type:"post",posts:r}:null}return null},ar=n=>{let e=n.replace(/\r\n/g,`
1
+ 'use strict';var xc=require('baileys'),crypto=require('node:crypto'),ke=require('node:fs/promises'),url=require('node:url'),os$1=require('node:os'),ze=require('node:path'),child_process=require('node:child_process'),jimp=require('jimp'),ji=require('node-webpmux'),fs$1=require('node:fs');require('node:stream');var ua=require('qrcode-terminal'),ga=require('pino'),events=require('node:events');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var xc__default=/*#__PURE__*/_interopDefault(xc);var ke__default=/*#__PURE__*/_interopDefault(ke);var ze__default=/*#__PURE__*/_interopDefault(ze);var ji__default=/*#__PURE__*/_interopDefault(ji);var ua__default=/*#__PURE__*/_interopDefault(ua);var ga__default=/*#__PURE__*/_interopDefault(ga);var Oi=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var p=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysBuilderError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var C={OPUS:{CODEC:"libopus",CHANNELS:1,FREQUENCY:48e3,BITRATE:"48k",FORMAT:"ogg"},THUMBNAIL:{SIZE:100,QUALITY:50,TIMESTAMP:"10%"},STICKER:{SIZE:512,MAX_DURATION:6,FPS:10,DEFAULT_QUALITY:60,COMPRESSION_LEVEL:6},MIME:{AUDIO:"audio/",VIDEO:"video/",IMAGE:"image/",GIF:"image/gif",MP4:"video/mp4"}},Kn="ffmpeg",$n="ffprobe",Un=false,nn=async(n=false)=>{if(!(n||Un)){Un=true;try{let e=(await import('@ffmpeg-installer/ffmpeg')).default;if(e?.path){Kn=e.path;let t=ze__default.default.dirname(e.path),r=process.platform==="win32"?";":":",s=process.env.PATH??"";s.split(r).includes(t)||(process.env.PATH=`${t}${r}${s}`);}}catch{}try{let e=(await import('@ffprobe-installer/ffprobe')).default;e?.path&&($n=e.path);}catch{}}},pt=()=>Date.now().toString(36)+Math.random().toString(36).slice(2,8),N=async n=>{let{fileTypeFromBuffer:e}=await import('file-type');return e(n)},V=class{static generateUniqueId(){return `${Date.now()}_${Math.random().toString(36).slice(2,11)}`}static createTempPath(e,t){return ze__default.default.join(os$1.tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>ke__default.default.unlink(t)));}static async safeReadFile(e){try{return await ke__default.default.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await ke__default.default.writeFile(e,t);}catch{throw new Error(`Failed to write file: ${e}`)}}},E=class{static async toBuffer(e){if(Buffer.isBuffer(e))return e;if(e instanceof ArrayBuffer)return Buffer.from(e);if(typeof e=="string")return this.fromString(e);throw new Error("Invalid input type: expected string, Buffer, or ArrayBuffer")}static async fromString(e){if(e.startsWith("http://")||e.startsWith("https://"))return this.fromUrl(e);try{if(await ke__default.default.stat(e).then(t=>t.isFile()).catch(()=>!1))return await ke__default.default.readFile(e)}catch{}return Buffer.from(e,"base64")}static async fromUrl(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let r=await t.arrayBuffer();return Buffer.from(r)}catch(t){throw new Error(`Failed to fetch URL: ${t instanceof Error?t.message:String(t)}`)}}static async getExtension(e){let{fileTypeFromBuffer:t}=await import('file-type'),r=await t(e);if(!r)return "tmp";let s=r.ext.toLowerCase();return ["wav","ogg","mp4","gif","jpg","webp","tmp","mp3","png"].includes(s)?s:"tmp"}},L=class{static validate(e,t){if(!e?.mime?.startsWith(t))throw new Error(`Invalid file type: expected ${t}*, got ${e?.mime||"unknown"}`)}static isMedia(e){return e.startsWith(C.MIME.IMAGE)||e.startsWith(C.MIME.VIDEO)}static isAnimated(e){return e===C.MIME.GIF||e.startsWith(C.MIME.VIDEO)}},ee=class{static async process(e){return await nn(),new Promise((t,r)=>{let s=["-y","-i",e.input,...e.options,e.output],i=child_process.spawn(Kn,s,{stdio:"ignore"});i.on("close",async o=>{if(o===0)try{await e.onEnd(),t();}catch(a){r(a);}else try{let a=new Error(`FFmpeg exited with code ${o}`);await e.onError(a),r(a);}catch(a){r(a);}}),i.on("error",async o=>{try{await e.onError(o);}finally{r(o);}});})}static async getDuration(e){return new Promise((t,r)=>{let s=child_process.spawn($n,["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),i="";s.stdout.on("data",o=>i+=o.toString()),s.on("close",o=>{o===0?t(parseFloat(i.trim())||0):r(new Error(`ffprobe exited with code ${o}`));}),s.on("error",r);})}};var Ni=3e4,Gn="application/octet-stream",me=async n=>n.byteLength===0?Gn:(await N(n))?.mime??Gn,Ee=async n=>({buffer:n,mime:await me(n),size:n.byteLength}),Jn=async(n,e)=>{let t=new AbortController,r=setTimeout(()=>t.abort(),e);try{let s=await fetch(n,{signal:t.signal});if(!s.ok)throw new p("MEDIA_LOAD_FAILED",`fetch ${n} failed with status ${s.status}`,{cause:s.status});return Buffer.from(await s.arrayBuffer())}catch(s){throw s instanceof p?s:new p("MEDIA_LOAD_FAILED",`fetch ${n} failed: ${s.message}`,{cause:s})}finally{clearTimeout(r);}},Vn=async n=>{try{return await ke.readFile(n)}catch(e){throw new p("MEDIA_LOAD_FAILED",`read ${n} failed: ${e.message}`,{cause:e})}},Di=n=>n.startsWith("http://")||n.startsWith("https://"),O=async(n,e)=>{await nn();let t=e?.timeoutMs??Ni;return Buffer.isBuffer(n)?Ee(n):n instanceof URL?n.protocol==="file:"?Ee(await Vn(url.fileURLToPath(n))):Ee(await Jn(n.toString(),t)):Di(n)?Ee(await Jn(n,t)):Ee(await Vn(n))};var ge=async(n,e)=>{let{buffer:t}=await O(n),r={image:t};return e?.caption!==void 0&&(r.caption=e.caption),e?.viewOnce!==void 0&&(r.viewOnce=e.viewOnce),r};var te=async(n,e)=>{let{buffer:t,mime:r}=await O(n);if(!r.startsWith("video/"))throw new p("INVALID_OPTIONS",`video() expects a video source, got mime ${r}`);let s={video:t};return e?.caption!==void 0&&(s.caption=e.caption),e?.gifPlayback!==void 0&&(s.gifPlayback=e.gifPlayback),e?.viewOnce!==void 0&&(s.viewOnce=e.viewOnce),e?.ptv===true&&(s.ptv=true),s};var Hn=2,zn=30,Bi=async n=>{if(n.type==="image")return ge(n.src,n.caption!==void 0?{caption:n.caption}:void 0);if(n.type==="video")return te(n.src,n.caption!==void 0?{caption:n.caption}:void 0);throw new p("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(n.type)}`)},Yn=async(n,e,t,r)=>{if(!Array.isArray(t)||t.length<Hn)throw new p("INVALID_OPTIONS",`album() requires a minimum of ${Hn} items`);if(t.length>zn)throw new p("INVALID_OPTIONS",`album() accepts a maximum of ${zn} items`);let s=0,i=0;for(let u of t)if(u.type==="image")s+=1;else if(u.type==="video")i+=1;else throw new p("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(u.type)}`);let o={album:{expectedImageCount:s,expectedVideoCount:i}};r.mentions&&r.mentions.length>0&&(o.mentions=r.mentions),r.mentionAll&&(o.mentionAll=true);let a={};r.quoted&&(a.quoted=r.quoted),r.disappearingSeconds!==void 0&&(a.ephemeralExpiration=r.disappearingSeconds);let c;try{c=await n.sendMessage(e,o,a);}catch(u){throw new p("SEND_FAILED","album parent send rejected",{cause:u})}let d=c?.key;if(!d)throw new p("SEND_FAILED","album parent returned no message key");let l=0;for(let u of t){let w=await Bi(u);w.albumParentKey=d;try{await n.sendMessage(e,w);}catch(M){throw new p("SEND_FAILED","album child send rejected",{cause:{parentKey:d,index:l,error:M}})}l+=1;}return d};var U=async(n,e,t,r,s)=>{let i=r.replace(/[^a-z0-9]+/gi,"_").toLowerCase(),o=V.createTempPath(`${i}_in`,e),a=V.createTempPath(`${i}_out`,t);await V.safeWriteFile(o,n);try{let c=typeof s=="function"?await s(o):s;return await ee.process({input:o,output:a,options:c,onEnd:async()=>{},onError:async()=>{}}),await V.safeReadFile(a)}catch(c){throw new Error(`${r} failed: ${c instanceof Error?c.message:String(c)}`)}finally{await V.cleanup([o,a]);}};var mt=64,Zn=8e3,ne=class{static async toOpus(e){return this.convert(e,"opus")}static async toMp3(e){return this.convert(e,"mp3")}static async convert(e,t="opus"){let r=await E.toBuffer(e);L.validate(await N(r),C.MIME.AUDIO);let s=await E.getExtension(r),i=t==="opus"?["-vn","-c:a","libopus","-b:a","48k","-ac","1","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","ogg"]:["-vn","-c:a","libmp3lame","-b:a","128k","-ac","2","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","mp3"];return U(r,s,t==="opus"?"ogg":"mp3",`${t.toUpperCase()} conversion`,i)}static async waveform(e){let t=await E.toBuffer(e),r=await E.getExtension(t),s=await U(t,r,"tmp","Waveform generation",["-vn","-ac","1","-ar",String(Zn),"-f","s16le"]),i=Math.floor(s.length/2);return {waveform:this.computeWaveform(s),seconds:Math.max(1,Math.round(i/Zn))}}static computeWaveform(e){let t=Math.floor(e.length/2),r=new Uint8Array(mt);if(t===0)return r;let s=Math.max(1,Math.floor(t/mt)),i=[];for(let a=0;a<mt;a++){let c=0,d=0;for(let l=0;l<s;l++){let u=(a*s+l)*2;u+1<e.length&&(c+=Math.abs(e.readInt16LE(u)),d+=1);}i.push(d>0?c/d:0);}let o=Math.max(...i)||1;for(let a=0;a<mt;a++)r[a]=Math.floor(i[a]/o*100);return r}};var Wi=["-c:v","libx264","-preset","ultrafast","-crf","28","-c:a","aac","-b:a","128k","-movflags","+faststart","-vf","scale=trunc(iw/2)*2:trunc(ih/2)*2","-pix_fmt","yuv420p","-f","mp4"],q=class{static async toMp4(e){let t=await E.toBuffer(e);L.validate(await N(t),C.MIME.VIDEO);let r=await E.getExtension(t);return U(t,r,"mp4","Video re-encoding",Wi)}static async thumbnail(e){let t=await E.toBuffer(e);L.validate(await N(t),C.MIME.VIDEO);let r=await E.getExtension(t),s=C.THUMBNAIL.SIZE;return (await U(t,r,"jpg","Thumbnail generation",async o=>{let a=await ee.getDuration(o);return ["-ss",Math.max(0,a*.1).toString(),"-vframes","1","-s",`${s}x${s}`]})).toString("base64")}static async duration(e){return ee.getDuration(e)}};var fe=null,Qn=false;async function Fi(){if(Qn)return fe;Qn=true;let n=e=>{typeof e=="function"&&(fe=e);};try{n(Oi("sharp"));}catch{fe=null;}if(!fe)try{let e=await import('sharp');n(e.default??e);}catch{fe=null;}return fe}function Xn(n,e){let t=new Uint8Array(n*n),r=n/2,s=n/2,i=n/10,o=[[i,i],[n-i,i],[i,n-i],[n-i,n-i]];for(let a=0;a<n;a++)for(let c=0;c<n;c++){let d=false;if(e==="circle"){let l=c-r,u=a-s;d=l*l+u*u<=r*r;}else if(e==="rounded"){let l=c>=i&&c<n-i&&a>=0&&a<n,u=c>=0&&c<n&&a>=i&&a<n-i,w=false;for(let M of o){let v=c-M[0],P=a-M[1];if(v*v+P*P<=i*i){w=true;break}}d=l||u||w;}else if(e==="oval"){let l=(c-r)/(n/2),u=(a-s)/(n/3);d=l*l+u*u<=1;}t[a*n+c]=d?255:0;}return t}var rn=class{sharp;constructor(e){this.sharp=e;}async thumbnail(e){let t=this.sharp,r=t(e).resize(C.THUMBNAIL.SIZE,C.THUMBNAIL.SIZE,{fit:"cover"});return (await r.metadata()).format==="gif"&&(r=t(e,{pages:1}).resize(C.THUMBNAIL.SIZE,C.THUMBNAIL.SIZE)),(await r.jpeg({quality:C.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}async resize(e,t,r){return this.sharp(e).resize(t,r,{fit:"cover"}).png().toBuffer()}async toJpeg(e){let t=this.sharp,r=await E.toBuffer(e),s=await t(r).metadata();if(!s.format)throw new Error("Invalid image type: format could not be determined");return s.format==="webp"||s.format==="png"?t(r).jpeg().toBuffer():r}async resizeForSticker(e,t,r="default"){let s=this.sharp,i=C.STICKER.SIZE,o=s(e).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}});if(r!=="default"){let a=Buffer.from(Xn(i,r)),c=s(a,{raw:{width:i,height:i,channels:1}});o=o.joinChannel(await c.png().toBuffer());}return o.webp({quality:t}).toBuffer()}},sn=class{async thumbnail(e){let t=C.THUMBNAIL.SIZE,r=await jimp.Jimp.fromBuffer(e);r.cover({w:t,h:t});let s=await r.getBuffer("image/jpeg",{quality:C.THUMBNAIL.QUALITY});return Buffer.from(s).toString("base64")}async resize(e,t,r){let s=await jimp.Jimp.fromBuffer(e);s.cover({w:t,h:r});let i=await s.getBuffer("image/png");return Buffer.from(i)}async toJpeg(e){let t=await E.toBuffer(e);try{let s=await(await jimp.Jimp.fromBuffer(t)).getBuffer("image/jpeg");return Buffer.from(s)}catch{return t}}async resizeForSticker(e,t,r="default"){let s=C.STICKER.SIZE,i=await jimp.Jimp.fromBuffer(e);if(i.contain({w:s,h:s}),r!=="default"){let c=Xn(s,r),d=new jimp.Jimp({width:s,height:s,color:255});for(let l=0;l<s;l++)for(let u=0;u<s;u++)c[l*s+u]===255&&d.setPixelColor(4294967295,u,l);i.mask(d);}let o=Buffer.from(await i.getBuffer("image/png")),a=Math.max(1,Math.min(100,t));return U(o,"png","webp","Jimp WebP conversion",["-vcodec","libwebp","-q:v",`${a}`,"-preset","default"])}},Ie=null;async function gt(){if(Ie)return Ie;let n=await Fi();return n?Ie=new rn(n):(console.warn("\x1B[33m%s\x1B[0m","[media-process] Jimp is slow. For faster performance, run: npm install sharp"),Ie=new sn),Ie}var F=class{static async thumbnail(e){return (await gt()).thumbnail(e)}static async resize(e,t,r){return (await gt()).resize(e,t,r)}static async toJpeg(e){return (await gt()).toJpeg(e)}static async resizeForSticker(e,t,r="default"){return (await gt()).resizeForSticker(e,t,r)}};var he=class n{static defaultMetadata={packageName:"Zaileys Library",authorName:"https://github.com/zeative/zaileys"};static setDefaultMetadata(e){e&&(n.defaultMetadata={...n.defaultMetadata,...e});}static getDefaultMetadata(){return {...n.defaultMetadata}}static async create(e,t){try{let r=await E.toBuffer(e),s=await N(r);if(!s)throw new Error("Unable to detect file type");let i=t?.quality||C.STICKER.DEFAULT_QUALITY,o=L.isAnimated(s.mime),a=t?.shape||"default",c=s.mime==="image/webp"?r:o?await this.processAnimated(r,s.mime,i):await F.resizeForSticker(r,i,a),d=this.createExifMetadata(t),l=new ji__default.default.Image;await l.load(c),l.exif=d;let u=await l.save(null);return Buffer.isBuffer(u)?u:Buffer.from(u)}catch(r){throw new Error(`Sticker creation failed: ${r instanceof Error?r.message:String(r)}`)}}static createExifMetadata(e){let t=e?.pack??e?.packageName??e?.packname??n.defaultMetadata.pack??n.defaultMetadata.packageName??n.defaultMetadata.packname??"Zaileys Library",r=e?.author??e?.authorName??e?.publisher??n.defaultMetadata.author??n.defaultMetadata.authorName??n.defaultMetadata.publisher??"https://github.com/zeative/zaileys",s={"sticker-pack-id":pt(),"sticker-pack-name":t,"sticker-pack-publisher":r,emojis:["\u{1F913}"],"android-app-store-link":"https://play.google.com/store/apps/details?id=com.marsvard.stickermakerforwhatsapp","ios-app-store-link":"https://itunes.apple.com/app/sticker-maker-studio/id1443326857"},i=Buffer.from([73,73,42,0,8,0,0,0,1,0,65,87,7,0,0,0,0,0,22,0,0,0]),o=Buffer.from(JSON.stringify(s),"utf8"),a=Buffer.concat([i,o]);return a.writeUIntLE(o.length,14,4),a}static async processAnimated(e,t,r){let s=C.STICKER.SIZE,i=C.STICKER.FPS,o=`scale=${s}:${s}:force_original_aspect_ratio=decrease,fps=${i},pad=${s}:${s}:(ow-iw)/2:(oh-ih)/2:color=0x00000000,format=rgba`,a=Math.max(1,Math.min(100,r));return U(e,this.getExtension(t),"webp","Animated sticker processing",async c=>{let d=C.STICKER.MAX_DURATION;try{d=Math.min(await q.duration(c),C.STICKER.MAX_DURATION);}catch{console.warn("Using default duration:",C.STICKER.MAX_DURATION);}return ["-vcodec libwebp",`-vf ${o}`,`-q:v ${a}`,"-loop 0","-preset default","-an","-vsync 0",`-t ${d}`,`-compression_level ${C.STICKER.COMPRESSION_LEVEL}`]})}static getExtension(e){return e===C.MIME.GIF?"gif":e.startsWith(C.MIME.VIDEO)?"mp4":"tmp"}};var ft=class{static async create(e){try{let t=await E.toBuffer(e),r=await N(t);if(!r)throw new Error("Unable to detect file type");let s;return r.mime.startsWith(C.MIME.VIDEO)?s=await q.thumbnail(t):L.isMedia(r.mime)?s=await F.thumbnail(t):s="",{document:t,mimetype:r.mime,ext:r.ext,fileName:pt(),jpegThumbnail:s}}catch(t){throw new Error(`Document creation failed: ${t instanceof Error?t.message:String(t)}`)}}};var re=class{input;constructor(e){this.input=e;}get audio(){return {toOpus:()=>ne.toOpus(this.input),toMp3:()=>ne.toMp3(this.input),convert:(e="opus")=>ne.convert(this.input,e),waveform:()=>ne.waveform(this.input)}}get video(){return {toMp4:()=>q.toMp4(this.input),thumbnail:()=>q.thumbnail(this.input)}}get image(){return {toJpeg:()=>F.toJpeg(this.input),thumbnail:async()=>{let e=await E.toBuffer(this.input);return F.thumbnail(e)},resize:async(e,t)=>{let r=await E.toBuffer(this.input);return F.resize(r,e,t)}}}get sticker(){return {create:e=>he.create(this.input,e)}}get document(){return {create:()=>ft.create(this.input)}}get thumbnail(){return {get:async()=>{let e=await E.toBuffer(this.input),t=await N(e);if(!t||!L.isMedia(t.mime))throw new Error("Invalid media type: expected image or video");return t.mime.startsWith(C.MIME.VIDEO)?q.thumbnail(this.input):F.thumbnail(e)}}}async toBuffer(){return E.toBuffer(this.input)}};var er=async(n,e)=>{let{buffer:t}=await O(n),r;try{r=await new re(t).audio.toOpus();}catch(o){throw new p("MEDIA_LOAD_FAILED",`audio() transcode failed: ${o.message}`,{cause:o})}let s=e?.ptt??true,i={audio:r,ptt:s};if(s)try{let{waveform:o,seconds:a}=await new re(t).audio.waveform();i.waveform=o,e?.seconds===void 0&&(i.seconds=a);}catch{}return e?.seconds!==void 0&&(i.seconds=e.seconds),i};var tr=10,R="__zaileysRelayMessage",on="__zaileysHeaderMedia",xe="__zaileysRequireGroupJid",ht="__zaileysStatusMedia",H=n=>typeof n=="string"&&n.length>0,Ui=n=>{let e=n.text;if(!H(e)||e.trim().length===0)throw new p("INVALID_OPTIONS","button text must be a non-empty string");return e},qi=(n,e)=>{let t=n.type??"reply";if(t==="location"){let s=n.text;return {name:"send_location",buttonParamsJson:JSON.stringify(H(s)?{display_text:s}:{})}}let r=Ui(n);if(t==="reply"){let s=n.id;if(!H(s))throw new p("INVALID_OPTIONS","reply button requires a non-empty id");if(e.has(s))throw new p("INVALID_OPTIONS",`duplicate button id: ${s}`);return e.add(s),{name:"quick_reply",buttonParamsJson:JSON.stringify({display_text:r,id:s})}}if(t==="url"){let s=n.url;if(!H(s))throw new p("INVALID_OPTIONS","url button requires a non-empty url");let i=n.webview===true;return {name:"cta_url",buttonParamsJson:JSON.stringify({display_text:r,url:s,merchant_url:s,webview_interaction:i})}}if(t==="copy"){let s=n.code;if(!H(s))throw new p("INVALID_OPTIONS","copy button requires a non-empty code");return {name:"cta_copy",buttonParamsJson:JSON.stringify({display_text:r,id:s,copy_code:s})}}if(t==="call"){let s=n.phone;if(!H(s))throw new p("INVALID_OPTIONS","call button requires a non-empty phone");return {name:"cta_call",buttonParamsJson:JSON.stringify({display_text:r,id:s,phone_number:s})}}if(t==="reminder"||t==="cancel-reminder"){let s=n.id;return {name:t==="reminder"?"cta_reminder":"cta_cancel_reminder",buttonParamsJson:JSON.stringify({display_text:r,id:H(s)?s:r})}}if(t==="address"){let s=n.id;return {name:"address_message",buttonParamsJson:JSON.stringify({display_text:r,id:H(s)?s:r})}}throw new p("INVALID_OPTIONS",`unknown button type: ${String(t)}`)},Ki=n=>{let e={};if(n?.bottomSheet){let t=n.bottomSheet;e.bottom_sheet={...t.buttonsLimit!==void 0?{in_thread_buttons_limit:t.buttonsLimit}:{},...t.dividers!==void 0?{divider_indices:t.dividers}:{},...t.listTitle!==void 0?{list_title:t.listTitle}:{},...t.buttonTitle!==void 0?{button_title:t.buttonTitle}:{}};}if(n?.limitedTimeOffer){let t=n.limitedTimeOffer;e.limited_time_offer={...t.text!==void 0?{text:t.text}:{},...t.url!==void 0?{url:t.url}:{},...t.copyCode!==void 0?{copy_code:t.copyCode}:{},...t.expiresAt!==void 0?{expiration_time:t.expiresAt}:{}};}return Object.keys(e).length>0?JSON.stringify(e):""},an=n=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","buttons() requires at least one button");if(n.length>tr)throw new p("INVALID_OPTIONS",`buttons() accepts at most ${tr} buttons`);let e=new Set;return n.map(t=>qi(t,e))},yt=(n,e)=>{let t=an(n),r={body:{text:e?.text&&e.text.length>0?e.text:" "},nativeFlowMessage:{buttons:t,messageParamsJson:Ki(e)}};e?.footer&&e.footer.length>0&&(r.footer={text:e.footer});let s=e?.image?{kind:"image",src:e.image}:e?.video?{kind:"video",src:e.video}:void 0;return (e?.title&&e.title.length>0||e?.subtitle&&e.subtitle.length>0||s)&&(r.header={title:e?.title??"",subtitle:e?.subtitle??"",hasMediaAttachment:s!==void 0}),s!==void 0?{[R]:{interactiveMessage:r},[on]:s}:{[R]:{interactiveMessage:r}}};var nr=10,cn="__zaileysCardsMedia",rr=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","carousel() requires at least one card");if(n.length>nr)throw new p("INVALID_OPTIONS",`carousel() accepts at most ${nr} cards`);let t=[],r=n.map((o,a)=>{let c={body:{text:o.body&&o.body.length>0?o.body:" "}};o.buttons&&o.buttons.length>0&&(c.nativeFlowMessage={buttons:an(o.buttons),messageParamsJson:""}),o.footer&&o.footer.length>0&&(c.footer={text:o.footer});let d=o.image?{kind:"image",src:o.image}:o.video?{kind:"video",src:o.video}:void 0;return (o.title&&o.title.length>0||o.subtitle&&o.subtitle.length>0||d)&&(c.header={title:o.title??"",subtitle:o.subtitle??"",hasMediaAttachment:d!==void 0}),d&&t.push({...d,index:a}),c}),s={body:{text:e?.text&&e.text.length>0?e.text:" "},carouselMessage:{cards:r}};return t.length>0?{[R]:{interactiveMessage:s},[cn]:t}:{[R]:{interactiveMessage:s}}};var Gi=n=>{let e=[],t="",r=0,s=1,i=0,o=0,a=[];for(let c=0;c<n.length;c++)if(n[c]==="["&&n[c-1]!=="\\")a.push(c);else if(n[c]==="]"&&(n[c+1]==="("||n[c+1]==="<")){let d=a.pop();if(d==null)continue;let l=n[c+1],u=l==="("?")":">",w=l==="<",M=c+2,v=1;for(;M<n.length&&v>0;)n[M]===l&&n[M-1]!=="\\"?v++:n[M]===u&&n[M-1]!=="\\"&&v--,M++;if(v>0)continue;let P=n.slice(d+1,c).trim(),y=n.slice(c+2,M-1).trim(),m,g;if(w){let[b="",k="",pe="",Qt="",Xt=""]=P.split("|").map(en=>en.trim());m=`zaileys_LATEX_${o++}`,g=`{{${m}}}${b||"image"}{{/${m}}}`,e.push({type:"latex",ie:{key:m,text:b,url:y,width:k,height:pe,font_height:Qt,padding:Xt}});}else P?(m=`zaileys_HYPERLINK_${i++}`,g=`{{${m}}}${y}{{/${m}}}`,e.push({type:"hyperlink",ie:{key:m,text:P,url:y}})):(m=`zaileys_CITATION_${s-1}`,g=`{{${m}}}${y}{{/${m}}}`,e.push({type:"citation",ie:{key:m,reference_id:String(s++),url:y}}));t+=n.slice(r,d)+g,r=M,c=M-1;}return t+=n.slice(r),{text:t,ie:e}},Ji=n=>n.ie.map(({type:e,ie:t})=>e==="hyperlink"?{key:t.key,metadata:{display_name:t.text,is_trusted:true,url:t.url,__typename:"GenAIInlineLinkItem"}}:e==="latex"?{key:t.key,metadata:{latex_expression:t.text,latex_image:{url:t.url,width:Number(t.width)||100,height:Number(t.height)||100},font_height:Number(t.font_height)||83.33333333333333,padding:Number(t.padding)||15,__typename:"GenAILatexItem"}}:{key:t.key,metadata:{reference_id:Number(t.reference_id),reference_url:t.url,reference_title:t.url,reference_display_name:t.url,sources:[],__typename:"GenAISearchCitationItem"}}),Vi=n=>{if(!Array.isArray(n)||n.length===0||!n.every(i=>Array.isArray(i)))throw new p("INVALID_OPTIONS","table must be a non-empty array of string rows");let[e,...t]=n,r=Math.max(e.length,...t.map(i=>i.length)),s=i=>[...i,...Array(r-i.length).fill("")];return [{is_header:true,cells:s(e)},...t.map(i=>({is_header:false,cells:s(i)}))]},Hi={0:"DEFAULT",1:"KEYWORD",2:"METHOD",3:"STR",4:"NUMBER",5:"COMMENT"},wt=new Set(["break","case","catch","continue","debugger","delete","do","else","finally","for","function","if","in","instanceof","new","return","switch","this","throw","try","typeof","var","void","while","with","true","false","null","undefined","class","const","let","super","extends","export","import","from","as","default","yield","static","constructor","async","await","get","set"]),zi={javascript:wt,js:wt,typescript:wt,ts:wt},Yi=(n,e)=>{let t=zi[e.toLowerCase()]??new Set,r=[],s=(o,a)=>{if(!o)return;let c=r[r.length-1];c&&c.highlightType===a?c.codeContent+=o:r.push({codeContent:o,highlightType:a});},i=0;for(;i<n.length;){let o=n[i];if(/\s/.test(o)){let a=i;for(;i<n.length&&/\s/.test(n[i]);)i++;s(n.slice(a,i),0);continue}if(o==="/"&&n[i+1]==="/"){let a=i;for(i+=2;i<n.length&&n[i]!==`
2
+ `;)i++;s(n.slice(a,i),5);continue}if(o==='"'||o==="'"||o==="`"){let a=i,c=o;for(i++;i<n.length;)if(n[i]==="\\"&&i+1<n.length)i+=2;else if(n[i]===c){i++;break}else i++;s(n.slice(a,i),3);continue}if(/[0-9]/.test(o)){let a=i;for(;i<n.length&&/[0-9.]/.test(n[i]);)i++;s(n.slice(a,i),4);continue}if(/[a-zA-Z_$]/.test(o)){let a=i;for(;i<n.length&&/[a-zA-Z0-9_$]/.test(n[i]);)i++;let c=n.slice(a,i),d=0;if(t.has(c))d=1;else {let l=i;for(;l<n.length&&/\s/.test(n[l]);)l++;n[l]==="("&&(d=2);}s(c,d);continue}s(o,0),i++;}return r},D=(n,e)=>({view_model:{[Array.isArray(e)?"primitives":"primitive"]:e,__typename:`GenAI${n}LayoutViewModel`}}),Zi="https://github.com/zeative/zaileys",sr=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","text({ rich: true }) requires non-empty markdown content");let t=[],r=[];for(let o of n)if(o.type==="text"){let a=Gi(o.text),c=Ji(a);r.push({messageType:2,messageText:a.text}),t.push(D("Single",{text:a.text,...c.length>0?{inline_entities:c}:{},__typename:"GenAIMarkdownTextUXPrimitive"}));}else if(o.type==="code"){let a=o.language??"plaintext",c=Yi(o.content,a);r.push({messageType:5,codeMetadata:{codeLanguage:a,codeBlocks:c}}),t.push(D("Single",{language:a,code_blocks:c.map(d=>({content:d.codeContent,type:Hi[d.highlightType]})),__typename:"GenAICodeUXPrimitive"}));}else if(o.type==="table"){let a=Vi(o.rows);r.push({messageType:4,tableMetadata:{title:"",rows:a.map(c=>({items:c.cells,...c.is_header?{isHeading:true}:{}}))}}),t.push(D("Single",{rows:a,__typename:"GenATableUXPrimitive"}));}else if(o.type==="image"){let a=Array.isArray(o.url)?o.url:[o.url];if(a.length===0)throw new p("INVALID_OPTIONS","image requires at least one url");r.push({messageType:1,gridImageMetadata:{gridImageUrl:{imagePreviewUrl:a[0]},imageUrls:a.map(c=>({imagePreviewUrl:c,imageHighResUrl:c,sourceUrl:Zi}))}});for(let c of a)t.push(D("Single",{media:{url:c,mime_type:"image/png"},imagine_type:"IMAGE",status:{status:"READY"},__typename:"GenAIImaginePrimitive"}));}else if(o.type==="video"){let a=Array.isArray(o.url)?o.url:[o.url];if(a.length===0)throw new p("INVALID_OPTIONS","video requires at least one url");r.push({messageType:2,messageText:"[ CANNOT_LOAD_VIDEO - zaileys ]"});for(let c of a)t.push(D("Single",{media:{url:c,mime_type:"video/mp4",duration:o.duration??0},imagine_type:"ANIMATE",status:{status:"READY"},__typename:"GenAIImaginePrimitive"}));}else if(o.type==="product"){let a=Array.isArray(o.products),c=a?o.products:[o.products];if(c.length===0)throw new p("INVALID_OPTIONS","product requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_PRODUCT - zaileys ]"});let d=c.map(l=>({title:l.title,brand:l.brand??"",price:l.price??"",sale_price:l.salePrice??"",product_url:l.url??"",image:{url:l.image??""},additional_images:[{url:l.icon??""}],__typename:"GenAIProductItemCardPrimitive"}));t.push(a?D("HScroll",d):D("Single",d[0]));}else if(o.type==="reels"){let a=Array.isArray(o.reels)?o.reels:[o.reels];if(a.length===0)throw new p("INVALID_OPTIONS","reels requires at least one item");r.push({messageType:9,contentItemsMetadata:{contentType:1,itemsMetadata:a.map(c=>({reelItem:{title:c.username??"",profileIconUrl:c.profileUrl??"",thumbnailUrl:c.thumbnail??"",videoUrl:c.url??""}}))}}),t.push(D("HScroll",a.map(c=>({reels_url:c.url??"",thumbnail_url:c.thumbnail??"",creator:c.username??c.title??"",avatar_url:c.profileUrl??"",reels_title:c.title??"",likes_count:c.likes??0,shares_count:c.shares??0,view_count:c.views??0,reel_source:c.source??"IG",is_verified:!!c.verified,__typename:"GenAIReelPrimitive"}))));}else if(o.type==="post"){let a=Array.isArray(o.posts)?o.posts:[o.posts];if(a.length===0)throw new p("INVALID_OPTIONS","post requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_POST - zaileys ]"}),t.push(D("HScroll",a.map(c=>({title:c.title??"",subtitle:c.subtitle??"",username:c.username??"",profile_picture_url:c.profileUrl??"",is_verified:!!c.verified,thumbnail_url:c.thumbnail??"",post_caption:c.caption??"",likes_count:c.likes??0,comments_count:c.comments??0,shares_count:c.shares??0,post_url:c.url??"",post_deeplink:c.deeplink??"",source_app:c.source??"INSTAGRAM",footer_label:c.footer??"",footer_icon:c.icon??"",is_carousel:a.length>1,orientation:c.orientation??"LANDSCAPE",post_type:c.postType??"VIDEO",__typename:"GenAIPostPrimitive"}))));}else if(o.type==="tip")r.push({messageType:2,messageText:o.text}),t.push(D("Single",{text:o.text,__typename:"GenAIMetadataTextPrimitive"}));else {let a=Array.isArray(o.prompts)?o.prompts:[o.prompts];if(a.length===0)throw new p("INVALID_OPTIONS","suggest requires at least one prompt");t.push(D("ActionRow",a.map(c=>({prompt_text:c,prompt_type:"SUGGESTED_PROMPT",__typename:"GenAIFollowUpSuggestionPillPrimitive"}))));}e?.footer&&e.footer.length>0&&t.push(D("Single",{text:e.footer,__typename:"GenAIMetadataTextPrimitive"}));let s=(e?.sources??[]).map(([o,a,c])=>({source_type:"THIRD_PARTY",source_display_name:c??"",source_subtitle:"AI",source_url:a??"",favicon:{url:o??"",mime_type:"image/jpeg",width:16,height:16}})),i={messageContextInfo:{deviceListMetadata:{},deviceListMetadataVersion:2,botMetadata:{messageDisclaimerText:e?.title??"",richResponseSourcesMetadata:{sources:s}}},botForwardedMessage:{message:{richResponseMessage:{messageType:1,submessages:r,unifiedResponse:{data:Buffer.from(JSON.stringify({response_id:crypto.randomUUID(),sections:t})).toString("base64")},contextInfo:{forwardingScore:1,isForwarded:true,forwardedAiBotMessageInfo:{botJid:"0@bot"},forwardOrigin:4}}}}};return {[R]:i}};var Qi=/^:::([a-zA-Z]+)\s*$/,Xi=/^:::\s*$/,ir=/^```(\w*)\s*$/,or=/^!\[[^\]]*\]\(([^)]+)\)\s*$/,eo=/^\s*\|?\s*:?-{2,}[\s|:-]*$/,vt=n=>n.split("|").map(e=>e.trim()),dn=n=>{let e={};for(let t of vt(n)){let r=t.indexOf(":");if(r===-1)continue;let s=t.slice(0,r).trim().toLowerCase(),i=t.slice(r+1).trim();s.length>0&&(e[s]=i);}return e},se=n=>{if(n===void 0||n.trim().length===0)return;let e=Number(n);return Number.isNaN(e)?void 0:e},cr=n=>n==="true"||n==="1"||n==="yes",ar=n=>{let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())},to=n=>{let e=dn(n),t=e.title;if(t===void 0||t.length===0)return null;let r={title:t};return e.price&&(r.price=e.price),e.sale&&(r.salePrice=e.sale),e.saleprice&&(r.salePrice=e.saleprice),e.brand&&(r.brand=e.brand),e.url&&(r.url=e.url),e.image&&(r.image=e.image),e.icon&&(r.icon=e.icon),r},no=n=>{let e=dn(n),t={};e.user&&(t.username=e.user),e.username&&(t.username=e.username),e.title&&(t.title=e.title),e.profile&&(t.profileUrl=e.profile),e.thumb&&(t.thumbnail=e.thumb),e.url&&(t.url=e.url);let r=se(e.likes);r!==void 0&&(t.likes=r);let s=se(e.shares);s!==void 0&&(t.shares=s);let i=se(e.views);return i!==void 0&&(t.views=i),e.source&&(t.source=e.source),"verified"in e&&(t.verified=cr(e.verified)),t},ro=n=>{let e=dn(n),t={};e.user&&(t.username=e.user),e.username&&(t.username=e.username),e.title&&(t.title=e.title),e.subtitle&&(t.subtitle=e.subtitle),e.profile&&(t.profileUrl=e.profile),e.thumb&&(t.thumbnail=e.thumb),e.caption&&(t.caption=e.caption);let r=se(e.likes);r!==void 0&&(t.likes=r);let s=se(e.comments);s!==void 0&&(t.comments=s);let i=se(e.shares);return i!==void 0&&(t.shares=i),e.url&&(t.url=e.url),e.source&&(t.source=e.source),e.footer&&(t.footer=e.footer),e.icon&&(t.icon=e.icon),"verified"in e&&(t.verified=cr(e.verified)),t},so=(n,e)=>{let t=e.map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(r=>r.length>0);if(n==="suggest"){let r=t.flatMap(s=>vt(s)).filter(s=>s.length>0);return r.length>0?{type:"suggest",prompts:r}:null}if(n==="tip")return t.length>0?{type:"tip",text:t.join(`
3
+ `)}:null;if(n==="image")return t.length>0?{type:"image",url:t.length===1?t[0]:t}:null;if(n==="video"){if(t.length===0)return null;let r=t.map(o=>vt(o)[0]??"").filter(o=>o.length>0);if(r.length===0)return null;let s=se(vt(t[0])[1]),i={type:"video",url:r.length===1?r[0]:r};return s!==void 0&&(i.duration=s),i}if(n==="product"){let r=t.map(to).filter(s=>s!==null);return r.length>0?{type:"product",products:r.length===1?r[0]:r}:null}if(n==="reels"){let r=t.map(no);return r.length>0?{type:"reels",reels:r}:null}if(n==="post"){let r=t.map(ro);return r.length>0?{type:"post",posts:r}:null}return null},dr=n=>{let e=n.replace(/\r\n/g,`
4
4
  `).split(`
5
5
  `),t=[],r=[],s=()=>{let o=r.join(`
6
- `).trim();o.length>0&&t.push({type:"text",text:o}),r=[];},i=0;for(;i<e.length;){let o=e[i],a=Hi.exec(o);if(a){s();let u=[];for(i++;i<e.length&&!zi.test(e[i]);)u.push(e[i]),i++;i++;let y=eo(a[1].toLowerCase(),u);y&&t.push(y);continue}let c=rr.exec(o);if(c){s();let u=[];for(i++;i<e.length&&!rr.test(e[i]);)u.push(e[i]),i++;i++;let y=c[1]&&c[1].length>0?c[1]:void 0;t.push(y?{type:"code",language:y,content:u.join(`
6
+ `).trim();o.length>0&&t.push({type:"text",text:o}),r=[];},i=0;for(;i<e.length;){let o=e[i],a=Qi.exec(o);if(a){s();let u=[];for(i++;i<e.length&&!Xi.test(e[i]);)u.push(e[i]),i++;i++;let w=so(a[1].toLowerCase(),u);w&&t.push(w);continue}let c=ir.exec(o);if(c){s();let u=[];for(i++;i<e.length&&!ir.test(e[i]);)u.push(e[i]),i++;i++;let w=c[1]&&c[1].length>0?c[1]:void 0;t.push(w?{type:"code",language:w,content:u.join(`
7
7
  `)}:{type:"code",content:u.join(`
8
- `)});continue}let d=e[i+1];if(o.includes("|")&&d!==void 0&&d.includes("|")&&Yi.test(d)){s();let u=[ir(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)u.push(ir(e[i])),i++;t.push({type:"table",rows:u});continue}let l=sr.exec(o);if(l){s();let u=[l[1]];for(i++;i<e.length;){let y=sr.exec(e[i]);if(!y)break;u.push(y[1]),i++;}t.push({type:"image",url:u.length===1?u[0]:u});continue}r.push(o),i++;}return s(),t};var cr=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new m("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var dr=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new m("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await x(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var lr=(n,e)=>{let t=n instanceof Date?n:new Date(n);if(Number.isNaN(t.getTime()))throw new m("INVALID_OPTIONS",`event() ${e} must be a valid Date or epoch ms`);return new Date(Math.floor(t.getTime()/1e3)*1e3)},ur=n=>{if(n==null||typeof n.name!="string"||n.name.trim().length===0)throw new m("INVALID_OPTIONS","event() requires a non-empty name");return {event:{name:n.name,startDate:lr(n.startAt,"startAt"),...n.description!==void 0?{description:n.description}:{},...n.endAt!==void 0?{endDate:lr(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 pr=n=>{if(n==null||typeof n.jid!="string"||!n.jid.endsWith("@g.us"))throw new m("INVALID_OPTIONS","groupInvite() requires a group jid ending in @g.us");if(typeof n.code!="string"||n.code.trim().length===0)throw new m("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 gr=4294967295,ro=/^[0-9a-fA-F]{3}$/,so=/^[0-9a-fA-F]{6}$/,io=/^[0-9a-fA-F]{8}$/,fr={system:0,"system-text":1,"fb-script":2,"system-bold":6,morningbreeze:7,calistoga:8,exo2:9,courierprime:10},ye=n=>{throw new m("INVALID_OPTIONS",n)},oo=n=>{if(typeof n=="number"){if(!Number.isInteger(n))return ye(`groupStatus() backgroundColor must be an integer, got ${n}`);let t=n<0?gr+n+1:n;return t<0||t>gr?ye(`groupStatus() backgroundColor is outside the ARGB range, got ${n}`):t}if(typeof n!="string")return ye("groupStatus() backgroundColor must be a hex string or an integer");let e=n.trim().replace("#","");if(io.test(e))return Number.parseInt(e,16);if(so.test(e))return Number.parseInt(`FF${e}`,16);if(ro.test(e)){let t=[...e].map(r=>`${r}${r}`).join("");return Number.parseInt(`FF${t}`,16)}return ye(`groupStatus() backgroundColor must be #RGB, #RRGGBB or #AARRGGBB, got ${n}`)},ao=n=>{if(typeof n=="number")return !Number.isInteger(n)||n<0?ye(`groupStatus() font must be a non-negative integer, got ${n}`):n;let e=fr[n];return e===void 0?ye(`groupStatus() font must be one of ${Object.keys(fr).join(", ")}, got ${String(n)}`):e},yr=(n,e)=>{if(typeof n!="string"||n.trim().length===0)throw new m("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=ao(e.font)),wr({extendedTextMessage:t})},wr=n=>({[R]:{groupStatusMessageV2:{message:n}},[ft]:"groupStatus()"}),hr=["conversation","extendedTextMessage"],co=new Set(["imageMessage","videoMessage","audioMessage","documentMessage","stickerMessage"]),lo=n=>typeof n.message=="function"?n.message():n,vr=(n,e)=>{let t=lo(n),r=t?.message==null?null:Mc.normalizeMessageContent(t.message),s=r==null?void 0:Mc.getContentType(r);if(r==null||s===void 0)throw new m("EMPTY_CONTENT","groupStatus() source has no repostable content");if(co.has(s))throw new m("INVALID_OPTIONS",`groupStatus() cannot repost ${s}: media group status is not verified to render, so it is blocked rather than sent blind`);if(!hr.includes(s))throw new m("INVALID_OPTIONS",`groupStatus() cannot repost ${s}; supported: ${hr.join(", ")}`);let i=Mc.proto.Message.decode(Mc.proto.Message.encode(r).finish());s==="conversation"&&(i.extendedTextMessage={text:i.conversation},delete i.conversation);let o=s==="conversation"?"extendedTextMessage":s,a=i[o];return delete a.viewOnce,a.contextInfo={},e?.caption!==void 0&&(a.text=e.caption),wr({[o]:a})};var Mr=10,Sr=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new m("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new m("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 m("INVALID_OPTIONS","each list section requires at least one row");let c=a.rows.map(d=>{if(typeof d.id!="string"||d.id.length===0)throw new m("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof d.title!="string"||d.title.trim().length===0)throw new m("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(d.id))throw new m("INVALID_OPTIONS",`duplicate list row id: ${d.id}`);return t.add(d.id),e+=1,{header:"",title:d.title,description:d.description??"",id:d.id}});return {title:a.title,highlight_label:"",rows:c}});if(e>Mr)throw new m("INVALID_OPTIONS",`list() accepts at most ${Mr} 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 br=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new m("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 m("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 Ar=2,Cr=12,Pr=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new m("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<Ar)throw new m("INVALID_OPTIONS",`poll() requires a minimum of ${Ar} options`);if(e.length>Cr)throw new m("INVALID_OPTIONS",`poll() accepts a maximum of ${Cr} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new m("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new m("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var Er=async n=>{if(n==null||typeof n.title!="string"||n.title.trim().length===0)throw new m("INVALID_OPTIONS","product() requires a non-empty title");if(typeof n.businessOwnerId!="string"||n.businessOwnerId.length===0)throw new m("INVALID_OPTIONS","product() requires businessOwnerId");let{buffer:e}=await x(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 kr=async(n,e)=>{let{buffer:t}=await x(n),r;try{r=await new re(t).sticker.create(e);}catch(i){throw new m("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var Tr=3,Ir=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new m("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new m("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>Tr)throw new m("INVALID_OPTIONS",`template() accepts at most ${Tr} buttons`);let t={text:`${n.header&&n.header.length>0?`*${n.header}*
8
+ `)});continue}let d=e[i+1];if(o.includes("|")&&d!==void 0&&d.includes("|")&&eo.test(d)){s();let u=[ar(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)u.push(ar(e[i])),i++;t.push({type:"table",rows:u});continue}let l=or.exec(o);if(l){s();let u=[l[1]];for(i++;i<e.length;){let w=or.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 lr=(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 ur=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 pr=(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)},mr=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:pr(n.startAt,"startAt"),...n.description!==void 0?{description:n.description}:{},...n.endAt!==void 0?{endDate:pr(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 gr=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 hr=4294967295,ao=/^[0-9a-fA-F]{3}$/,co=/^[0-9a-fA-F]{6}$/,lo=/^[0-9a-fA-F]{8}$/,yr={system:0,"system-text":1,"fb-script":2,"system-bold":6,morningbreeze:7,calistoga:8,exo2:9,courierprime:10},ye=n=>{throw new p("INVALID_OPTIONS",n)},uo=n=>{if(typeof n=="number"){if(!Number.isInteger(n))return ye(`groupStatus() backgroundColor must be an integer, got ${n}`);let t=n<0?hr+n+1:n;return t<0||t>hr?ye(`groupStatus() backgroundColor is outside the ARGB range, got ${n}`):t}if(typeof n!="string")return ye("groupStatus() backgroundColor must be a hex string or an integer");let e=n.trim().replace("#","");if(lo.test(e))return Number.parseInt(e,16);if(co.test(e))return Number.parseInt(`FF${e}`,16);if(ao.test(e)){let t=[...e].map(r=>`${r}${r}`).join("");return Number.parseInt(`FF${t}`,16)}return ye(`groupStatus() backgroundColor must be #RGB, #RRGGBB or #AARRGGBB, got ${n}`)},po=n=>{if(typeof n=="number")return !Number.isInteger(n)||n<0?ye(`groupStatus() font must be a non-negative integer, got ${n}`):n;let e=yr[n];return e===void 0?ye(`groupStatus() font must be one of ${Object.keys(yr).join(", ")}, got ${String(n)}`):e},vr=(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=uo(e.backgroundColor)),e?.font!==void 0&&(t.font=po(e.font)),Mr({extendedTextMessage:t})},Mr=n=>({[R]:{groupStatusMessageV2:{message:n}},[xe]:"groupStatus()"}),mo=["conversation","extendedTextMessage"],go={imageMessage:"image",videoMessage:"video",audioMessage:"audio"},wr=n=>({[R]:{groupStatusMessageV2:{message:{}}},[xe]:"groupStatus()",[ht]:n}),fo=["image","video","audio"],ho=n=>{let e=n;if(typeof e.message=="function"||e.message!==void 0||e.key!==void 0)return null;for(let t of fo)if(e[t]!==void 0)return {kind:t,src:e[t]};return null},yo=n=>typeof n.message=="function"?n.message():n,wo=(n,e,t)=>{let r=xc.proto.Message.decode(xc.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),Mr({extendedTextMessage:s})},Sr=async(n,e)=>{let t=ho(n);if(t!==null){let a=n,{buffer:c}=await O(t.src),d={kind:t.kind,buffer:c},l=e?.caption??a.caption;return t.kind!=="audio"&&l!==void 0&&(d.caption=l),t.kind==="audio"&&a.ptt===true&&(d.ptt=true),wr(d)}let r=yo(n),s=r?.message==null?null:xc.normalizeMessageContent(r.message),i=s==null?void 0:xc.getContentType(s);if(s==null||i===void 0)throw new p("EMPTY_CONTENT","groupStatus() source has no repostable content");let o=go[i];if(o!==void 0){let a=s[i]??{},c;try{let{downloadMediaMessage:u}=await import('baileys');c=await u(r,"buffer",{});}catch(u){throw new p("MEDIA_LOAD_FAILED","groupStatus() could not download the source media",{cause:u})}let d={kind:o,buffer:c},l=e?.caption??a.caption;return o!=="audio"&&l!==void 0&&(d.caption=l),o==="audio"&&a.ptt===true&&(d.ptt=true),wr(d)}if(!mo.includes(i))throw new p("INVALID_OPTIONS",`groupStatus() cannot repost ${i}; supported: text, image, video, audio`);return wo(s,i,e)};var br=10,Ar=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 c=a.rows.map(d=>{if(typeof d.id!="string"||d.id.length===0)throw new p("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof d.title!="string"||d.title.trim().length===0)throw new p("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(d.id))throw new p("INVALID_OPTIONS",`duplicate list row id: ${d.id}`);return t.add(d.id),e+=1,{header:"",title:d.title,description:d.description??"",id:d.id}});return {title:a.title,highlight_label:"",rows:c}});if(e>br)throw new p("INVALID_OPTIONS",`list() accepts at most ${br} 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 Cr=(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 Pr=2,kr=12,Er=(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<Pr)throw new p("INVALID_OPTIONS",`poll() requires a minimum of ${Pr} options`);if(e.length>kr)throw new p("INVALID_OPTIONS",`poll() accepts a maximum of ${kr} 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 Tr=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 Ir=async(n,e)=>{let{buffer:t}=await O(n),r;try{r=await new re(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 xr=3,Or=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>xr)throw new p("INVALID_OPTIONS",`template() accepts at most ${xr} buttons`);let t={text:`${n.header&&n.header.length>0?`*${n.header}*
9
9
 
10
- `:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),ht(n.buttons,t)};var vt=n=>{if(typeof n!="string"||n.trim().length===0)throw new m("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Or=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var ho=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],z=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,Or(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=nr(ar(e),t):this.internal.content=vt(e),this}image(e,t){return this.internal.pendingContent=ge(e,t),this}videoNote(e,t){return this.internal.pendingContent=te(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=te(e,t),this}audio(e,t){return this.internal.pendingContent=Qn(e,t),this}document(e,t){return this.internal.pendingContent=dr(e,t),this}sticker(e,t){return this.internal.pendingContent=kr(e,t),this}buttons(e,t){return this.internal.content=ht(e,t),this}carousel(e,t){return this.internal.content=tr(e,t),this}list(e){return this.internal.content=Sr(e),this}poll(e,t,r){return this.internal.content=Pr(e,t,r),this}location(e,t,r){return this.internal.content=br(e,t,r),this}contact(e){return this.internal.content=cr(e),this}template(e){return this.internal.content=Ir(e),this}event(e){return this.internal.content=ur(e),this}groupInvite(e){return this.internal.content=pr(e),this}groupStatus(e,t){return this.internal.content=typeof e=="string"?yr(e,t):vr(e,t),this}product(e){return this.internal.pendingContent=Er(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 m("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 m("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new m("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}disappearing(e){if(!Number.isInteger(e)||e<=0)throw new m("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.albumItems){let d={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(d.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(d.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(d.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(d.disappearingSeconds=this.internal.disappearingSeconds),Hn(this.socket,this.internal.recipient,this.internal.albumItems,d)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new m("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[R];if(i!==void 0){let d=s[ft];if(typeof d=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new m("INVALID_RECIPIENT",`${d} can only be sent to a group jid ending in @g.us`);let l=s[sn],u=s[an];return this.sendRelay(i,l,u)}let o=this.internal.content;this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds);let c;try{c=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(d){throw new m("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new m("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await x(t.src),s=await Mc.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);}applyRelayMentions(e){let t=this.internal.mentions,r=this.internal.mentionAll===true;if((t===void 0||t.length===0)&&!r)return;let s=Mc.normalizeMessageContent(e),i=s==null?void 0:Mc.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){let s=this.socket.relayMessage;if(typeof s!="function")throw new m("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let y=e.interactiveMessage?.header;t!==void 0&&y&&await this.uploadHeaderMedia(y,t);let M=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&M)for(let v of r){let P=M[v.index]?.header;P&&await this.uploadHeaderMedia(P,v);}}catch(y){throw new m("SEND_FAILED","interactive media upload failed",{cause:y})}let i=e;i.messageContextInfo?.messageSecret==null&&(i.messageContextInfo={...i.messageContextInfo,messageSecret:crypto.randomBytes(32)}),this.applyRelayMentions(e);let a={userJid:this.socket.user?.id??""},c=this.internal.quoted;c!==void 0&&c.message!=null&&(a.quoted=c),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds);let d=Mc.generateWAMessageFromContent(this.internal.recipient,e,a);if(typeof d.key?.id!="string")throw new m("SEND_FAILED","failed to generate relay message key");let u="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:d.key.id,additionalNodes:ho}:{messageId:d.key.id};try{await s(this.internal.recipient,d.message,u);}catch(y){throw new m("SEND_FAILED","socket relayMessage rejected",{cause:y})}return this.internal.recordSent?.(d),d.key}};var Oe=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=vt(e),this}image(e,t){return this.pendingContent=ge(e,t),this}video(e,t){return this.pendingContent=te(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 m("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new m("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 m("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new m("SEND_FAILED","socket returned no message key");return r.key}};var dn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new m("INVALID_OPTIONS","message key is missing remoteJid");return e},ln=n=>{if(!n?.key)throw new m("SEND_FAILED","socket returned no message key");return n.key},un=async(n,e,t={})=>{let r=dn(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new m("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},pn=async(n,e,t)=>{let r=dn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return ln(s)},mn=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new m("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return ln(i)},Mt=async(n,e,t,r={})=>{let s=dn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return ln(o)};var yo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,xe=n=>yo.test(n),gn=async(n,e,t,r=wo)=>{if(xe(e))return e;let s=t.get(e);if(s!==void 0)return s;let i=r.get(e);if(i!==void 0)return i;let o=(async()=>{let c=(await n.onWhatsApp(e))?.find(d=>d.exists&&d.jid);if(!c)throw new m("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,c.jid),c.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},wo=new Map;var T=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 Re=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 T("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new T("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 T("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 _e=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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);}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);}};var Le=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 T("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 Ne=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 De=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 vo=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new T("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Be=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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=vo(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 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 We=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 Fe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 Mo=n=>{let e=n[0];return e==="{"||e==="["},So=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},bo=n=>n===" "||n===" "||n===`
11
- `||n==="\r",Ao=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let c=n[a];if(s){t+=c,s=false,i=true,o=false;continue}if(c==="\\"&&r!==null){s=true;continue}if(r!==null){c===r?r=null:t+=c,o=false;continue}if((c==='"'||c==="'")&&o){r=c,i=true,o=false;continue}if(bo(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},Co=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},Po=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function fn(n,e){let t=Co(n,e);if(t===null)return Po(n);let r=n.slice(t.length),s=Ao(r),i={matched:true,args:[],flags:{},json:void 0,raw:n};if(s.length===0)return i.name="",i;i.name=(s[0]??"").toLowerCase();let o=false;for(let a=1;a<s.length;a+=1){let c=s[a];if(c!==void 0){if(c.startsWith("--")){let d=c.slice(2);if(d.length===0){i.args.push(c);continue}let l=d.indexOf("=");if(l!==-1){let y=d.slice(0,l),M=d.slice(l+1);i.flags[y]=M;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[d]=u,a+=1):i.flags[d]=true;continue}if(!o&&Mo(c)){let d=So(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var xr=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new _("INVALID_COMMAND_NAME","empty command segment in spec");return e},we=n=>n.join(" "),je=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new _("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>xr(a)),s=r[0],i=r.slice(1).map(a=>we(a)),o={name:we(s),aliases:i,parts:s,handler:t};for(let a of r){let c=we(a);if(this.paths.has(c))throw new _("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set(we(a),o),a.length>this.maxDepth&&(this.maxDepth=a.length);this.defs.push(o);}resolve(e){if(!e.matched||e.name===void 0||e.name.length===0)return;let t=[e.name.toLowerCase(),...e.args.map(s=>s.toLowerCase())],r=Math.min(this.maxDepth,t.length);for(let s=r;s>=1;s-=1){let i=t.slice(0,s).join(" "),o=this.paths.get(i);if(o!==void 0)return {def:o,args:e.args.slice(s-1)}}}unregister(e){let t=e.split("|").map(o=>xr(o)),r=we(t[0]),s=this.paths.get(r);if(s===void 0)return;for(let o of [s.parts,...s.aliases.map(a=>a.split(" "))])this.paths.delete(we(o));let i=this.defs.indexOf(s);i>=0&&this.defs.splice(i,1),this.maxDepth=this.defs.reduce((o,a)=>Math.max(o,a.parts.length),1);}list(){return [...this.defs]}};async function hn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new _("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(c){throw s.error=c,s.thrown=true,c}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(c){throw s.thrown||c instanceof _?c:new _("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function yn(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=fn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0)return;let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},c=n.buildContext(a,s);Promise.resolve(hn(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let l=d instanceof _?d:new _("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(l,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Rr=n=>n;var Ue=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t){if(typeof e?.name!="string"||typeof e?.setup!="function"){this.logger?.warn({file:t},"plugin: invalid shape (need name + setup); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let r=[],s={client:this.host,logger:this.logger,pluginDir:He__default.default.dirname(t),command:(i,o)=>{this.host.command(i,o),r.push(()=>this.host.unregisterCommand(i));},use:i=>{this.host.use(i),r.push(()=>{this.host.unuse(i);});},on:(i,o)=>{let a=this.host.on(i,o);return r.push(a),a},once:(i,o)=>{let a=false,c=this.host.on(i,d=>{a||(a=true,c(),o(d));});return r.push(c),c}};try{let i=await e.setup(s);typeof i=="function"&&r.push(i);}catch(i){for(let o of [...r].reverse())try{await o();}catch{}this.logger?.error({err:i,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:r});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Io=/\.(ts|js|mjs|cjs)$/,Oo=/(\.d\.ts$|^_|[/\\]_)/;async function vn(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=He__default.default.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await vn(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function Lr(n,e){try{let r=await import(url.pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"&&typeof s.setup=="function"?s:void 0}catch{return}}var qe=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=He__default.default.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Io,this.ignore=e.options.ignore??Oo,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await vn(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 Lr(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=fs$1.watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=He__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 I=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 xo=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ie=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new I("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new I("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new I("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??xo;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 Ro={"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},_o=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function Mn(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??_o,i={...Ro,...n.intervalsMs??{}},o=new Map,a=new Map,c=async(d,l)=>{let u=i[d]??0,y=o.get(d);if(y!==void 0&&u>0){let M=u-(r()-y);M>0&&await s(M);}return o.set(d,r()),l()};return {run(d,l){if(!t)return l();let y=(a.get(d)??Promise.resolve()).then(()=>c(d,l),()=>c(d,l));return a.set(d,y.then(()=>{},()=>{})),y}}}var Lo={maxRetries:0,backoffMs:()=>0},No=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),Ke=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??Lo,this.sleep=t.sleep??No;}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 Do=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function Sn(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 ie({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},l=c?new Ke({concurrency:1,retry:c},d):void 0,u=n.length,y=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),y+=1,r.onProgress?.(y,u,M,!0);}catch(P){s.failed.push({jid:M,error:Do(P)}),y+=1,r.onProgress?.(y,u,M,false);}}return s}var Bo=1e3,$e=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??Bo,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new Map;requireSocket(){let e=this.getSocket();if(!e)throw new I("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 I("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 Fo={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},jo=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",Ge=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??Fo,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new I("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),jo(e.payload))try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed; retaining job for retry");return}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,c)=>{if(r+=1,r>1)throw new I("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=c?{recipient:o,content:a,options:c}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new I("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=z.create(s,"");try{await e(i);}catch(o){throw o instanceof I?o:new I("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new I("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function Nr(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((c,d)=>Number(d.messageTimestamp??0)-Number(c.messageTimestamp??0));for(let c=0;c<a.length;c+=1){let d=a[c],l=Number(d.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,y=e.maxPerChat!==void 0&&c>=e.maxPerChat;(u||y)&&(await n.deleteMessage(d.key),r+=1);}}return r}var Je=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"?Nr(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 Dr=n=>(n.split(/[:@]/)[0]??"").replace(/\D/g,""),Ve=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 I("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=Dr(e);return t.some(s=>s===e||Dr(s)===r)}return await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var Uo={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},qo=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Uo[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},St=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=qo(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")}},Br=(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 oe="[zaileys]",Ko="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 Fr(n){switch(n.kind){case "connecting":return `${oe} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${oe} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${oe} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${oe} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${oe} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
12
- ${oe} ${Ko}`:t}case "disconnect":return n.willReconnect?null:`${oe} Disconnected (${n.reason}).`;default:return null}}var Wr=false,$o=["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:"],Go=n=>typeof n[0]=="string"&&$o.some(e=>n[0].startsWith(e));function jr(){if(Wr)return;Wr=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{Go(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 Vo="./.zaileys/auth",Ho=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),ze=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",At=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??Vo;}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,Mc.BufferJSON.reviver);}catch(o){if(ze(o))return;throw new h("STORE_READ_FAILED",`failed to read ${i}`,{cause:o})}})),r},write:async e=>{this.assertOpen();let t=[];for(let r of Object.keys(e)){let s=e[r];if(!s)continue;let i=this.signalDir(r);await fs$1.promises.mkdir(i,{recursive:true});for(let o of Object.keys(s)){let a=s[o],c=this.signalPath(r,o);a===null?t.push(fs$1.promises.unlink(c).catch(d=>{if(!ze(d))throw new h("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,Mc.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(!ze(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,Mc.BufferJSON.reviver)}catch(e){if(ze(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,Mc.BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await fs$1.promises.unlink(this.credsPath());}catch(e){if(!ze(e))throw new h("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return He__default.default.join(this.basePath,"creds.json")}signalDir(e){return He__default.default.join(this.basePath,"signal",String(e))}signalPath(e,t){return He__default.default.join(this.signalDir(e),`${Ho(t)}.json`)}async atomicWrite(e,t){let r=He__default.default.join(He__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 Ur(n,e){let t=n.signal,s=Mc.makeCacheableSignalKeyStore({get:(o,a)=>t.read(o,a),set:o=>t.write(o),clear:()=>t.clear()},e?.logger??void 0),i={read:async(o,a)=>await s.get(o,[...a]),write:async o=>{await s.set(o);},delete:async(o,a)=>{await t.delete(o,a);let c={},d={};for(let l of a)d[l]=null;c[o]=d,await s.set(c);},clear:async()=>{let o=s.clear;typeof o=="function"?await o.call(s):await t.clear();},close:()=>t.close()};return {creds:n.creds,signal:i}}function qr(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 Yo=429;function Kr(n){if(n===Yo)return "rate-limited";switch(n){case Mc.DisconnectReason.loggedOut:return "logged-out";case Mc.DisconnectReason.forbidden:return "forbidden";case Mc.DisconnectReason.connectionLost:return "connection-lost";case Mc.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case Mc.DisconnectReason.connectionClosed:return "connection-closed";case Mc.DisconnectReason.connectionReplaced:return "connection-replaced";case Mc.DisconnectReason.badSession:return "bad-session";case Mc.DisconnectReason.unavailableService:return "unavailable-service";case Mc.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function Ye(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Ct(n){return n==="rate-limited"}function $r(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function km(n){return !Ye(n)}var Pt={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},Zo=3e5;function Gr(n={}){let e=n.enabled??Pt.enabled,t=n.maxQrAttempts??Pt.maxQrAttempts,r=n.maxPairingAttempts??Pt.maxPairingAttempts,s=n.pairingCooldownMs??Pt.pairingCooldownMs,i=0,o=0,a=0,c=y=>y<=0?0:Math.min(s*y,Zo);return {evaluate:(y,M)=>{if(!e)return {allowed:true,waitMs:0,attempts:y==="pairing"?o:i,max:Number.POSITIVE_INFINITY};if(y==="pairing"){if(o>=r)return {allowed:false,reason:"budget-exhausted",waitMs:0,attempts:o,max:r};let v=c(o),P=M-a;return o>0&&P<v?{allowed:false,reason:"cooldown",waitMs:v-P,attempts:o,max:r}:{allowed:true,waitMs:0,attempts:o,max:r}}return i>=t?{allowed:false,reason:"budget-exhausted",waitMs:0,attempts:i,max:t}:{allowed:true,waitMs:0,attempts:i,max:t}},record:(y,M)=>{y==="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 Qo=/[\s\-()+]/g;function Xo(n){return typeof n!="string"?"":n.replace(Qo,"")}function ea(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=Xo(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 Jr(n){let e=ea(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 na(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{ta__default.default.generate(n,{small:true},t=>e(t));})}async function Vr(n,e=t=>{process.stdout.write(t);}){let t=await na(n);e(t+`
13
- `);}var ve={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function Hr(n,e){let t=n?.enabled??ve.enabled,r=n?.maxAttempts??ve.maxAttempts,s=n?.initialDelayMs??ve.initialDelayMs,i=n?.maxDelayMs??ve.maxDelayMs,o=n?.jitterFactor??ve.jitterFactor,a=n?.rateLimitedDelayMs??ve.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:y=>{if(!t||Ye(y))return null;let M=d+1;if(M>r)return null;if(d=M,Ct(y))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),w=1+(c()*2-1)*o,p=P*w,g=Math.min(i,Math.max(0,p));return {attempt:M,delayMs:Math.round(g)}},reset:()=>{d=0;},get attempts(){return d}}}var ra={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 zr(n="idle"){let e=n,t=new Set,r=s=>ra[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 Et=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,kt=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=Et(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(Et(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(Et(l.key));if(u){let y={...u,...l.update};this.saveMessage(y).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let y={...this.chats.get(l.id)??{},...l};this.saveChat(y).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=Et(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var ia=["silent","fatal","error","warn","info","debug","trace"];function oa(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":ia.includes(e)?e:"silent"}function aa(n={}){let e=oa(n.level),t=sa__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Yr=["debug","info","warn","error","fatal"];function ca(n){if(n===null||typeof n!="object")return false;for(let e of Yr)if(typeof n[e]!="function")return false;return true}function Ze(){}function da(n){let e={debug:Ze,info:Ze,warn:Ze,error:Ze,fatal:Ze};for(let t of Yr){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function bn(n,e){return n===void 0?e??aa():ca(n)?n:da(n)}var jm=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),Zr=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 la=new Set(["offer","ringing"]),ua=new Set(["timeout","reject","accept","terminate"]),Qr=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},Xr=n=>typeof n.id!="string"||n.id.length===0||!la.has(n.status)?null:{kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Qr(n.date),status:n.status},es=n=>typeof n.id!="string"||n.id.length===0||!ua.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Qr(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,pa=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},ts=(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}),ns=n=>B(n?.id)?{groupId:n.id,update:pa(n),timestamp:Date.now()}:null,rs=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},ma=new Set(["add","invite","invite-link"]),ga=new Set(["remove","leave"]),ss=n=>{if(!B(n?.id)||!ma.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ts(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},is=n=>{if(!B(n?.id)||!ga.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ts(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 Me=n=>typeof n!="string"||n.length===0?null:Mc.jidNormalizedUser(n),Y=n=>typeof n=="string"&&n.length>0?n:void 0,ya=["@s.whatsapp.net","@c.us"],Tt=n=>n.endsWith("@lid"),os=n=>ya.some(e=>n.endsWith(e)),K=(n,e)=>{if(!n)return null;let t=Y(n.participant)??n.remoteJid,r=Me(t);if(r===null)return null;let s=Y(n.participantAlt)??Y(n.remoteJidAlt),i=s!=null?Me(s):null,o=Y(n.participantUsername)??Y(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(Tt),l=c.find(os);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Y(e);return u!==void 0&&(a.pushName=u),a},as=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=Y(n.participant),r=Y(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=K(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 Se=n=>Mc.isJidGroup(n)===true,be=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},f=n=>n!=null&&typeof n=="object"?n:null,cs=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],ds=["groupStatusMessage","groupStatusMessageV2"],ls=(n,e)=>{let t=n;for(let r=0;r<5&&t!=null;r++){if(e.some(i=>t?.[i]!=null))return true;let s=null;for(let i of cs){let o=f(f(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Ae=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of cs){let i=f(f(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var wa=["quick_reply","cta_url","cta_call","button_click"],va=["list_select","single_select"],G=n=>typeof n=="string"&&n.length>0,ps=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return K(n.key,e)},ms=n=>be(n.messageTimestamp)??0,gs=(n,e)=>{if(!G(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}},It=(n,e)=>{for(let t of e){let r=n[t];if(G(r))return r}},fs=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&G(r.selectedButtonId))return An(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&G(s.selectedId))return An(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&G(i.name)&&wa.includes(i.name)){let o=gs(i.paramsJson,e.logger);if(!o)return null;let a=It(o,["id","button_id"]);return a===void 0?null:An(n,a,It(o,["display_text"])??null)}return null},An=(n,e,t)=>{let r=ps(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:ms(n)};return G(t)&&(s.buttonText=t),s},hs=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(G(s))return us(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&G(i.name)&&va.includes(i.name)){let o=gs(i.paramsJson,e.logger);if(!o)return null;let a=It(o,["row_id","id"]);return a===void 0?null:us(n,a,It(o,["title"])??null)}return null},us=(n,e,t)=>{let r=ps(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:ms(n)};return G(t)&&(s.title=t),s};var Ma=new Set(["available","unavailable","composing","recording","paused"]),Sa=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,ys=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},Cn=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:Sa(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},ws=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"||!Ma.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},Xe=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 Ms=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},vs=(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},Ss=n=>(vs(n).toString(16).padStart(8,"0")+vs(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),bs=n=>Ss(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),As=(n,e)=>Ss(`${n??""}|${e}`),Cs=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},Ps=n=>{let e=Mc.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"},Aa=n=>n.trim().endsWith("?"),Ca=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Pa=(n,e)=>{if(e.length===0)return false;let t;try{t=Mc.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return Mc.jidNormalizedUser(r)===t}catch{return r===n}})},Ea=(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)}},ka=0,Ta=14,Ia=1,Oa=2,xa=n=>{let e=f(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=f(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof f(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Ta,isDeleted:r===ka,isPinned:s===Ia,isUnPinned:s===Oa,isBot:f(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:ls(e,ds)}},Pn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Se(e),r=xa(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?Mc.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(Mc.jidNormalizedUser(e)):i,a={uniqueId:bs(n.key),staticId:As(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(Mc.jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderDevice:Ps(n.sender.deviceJid??n.sender.jid),timestamp:Cs(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Ms(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isQuestion:Aa(n.text),isPrefix:Ca(n.text,n.prefixes),isTagMe:Pa(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:Ea(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var xt={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Ts=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},S=n=>typeof n=="string"&&n.length>0?n:null,Z=(...n)=>{for(let e of n){let t=S(e);if(t!=null)return t}return null},Is=n=>{let e=f(n.message);if(e==null)return n;let t=Ae(e);return t===e?n:{...n,message:t}},Ra=n=>{let t=f(f(f(n.botForwardedMessage)?.message)?.richResponseMessage)??f(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(f(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
14
- `).trim();return i.length>0?i:null},_a=n=>{let e=f(n.templateMessage),t=f(e?.hydratedTemplate)??f(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},La=n=>Z(f(n.pollCreationMessage)?.name,f(n.pollCreationMessageV2)?.name,f(n.pollCreationMessageV3)?.name),Na=n=>{let e=f(n.locationMessage)??f(n.liveLocationMessage);if(e==null)return null;let t=Z(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},Da=n=>{let e=S(f(n.contactMessage)?.displayName);if(e!=null)return e;let t=f(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(f(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},Os=n=>Z(n.conversation,f(n.extendedTextMessage)?.text,Ra(n),S(f(f(n.interactiveMessage)?.body)?.text),f(n.buttonsMessage)?.contentText,f(n.listMessage)?.description,_a(n),La(n),Na(n),Da(n)),Ba=n=>Z(f(n.buttonsResponseMessage)?.selectedDisplayText,f(n.buttonsResponseMessage)?.selectedButtonId,f(n.templateButtonReplyMessage)?.selectedDisplayText,f(n.templateButtonReplyMessage)?.selectedId,f(n.listResponseMessage)?.title,f(f(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,f(f(n.interactiveResponseMessage)?.body)?.text),Wa=n=>Z(f(n.imageMessage)?.caption,f(n.videoMessage)?.caption,f(n.documentMessage)?.caption,f(n.documentMessage)?.fileName),O=n=>{if(typeof n=="number")return n;let e=be(n);return typeof e=="number"?e:null},Fa=[["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"]],xs=n=>{let e=f(n.pollCreationMessage)??f(n.pollCreationMessageV2)??f(n.pollCreationMessageV3);if(e!=null){let p=Array.isArray(e.options)?e.options:[];return {type:"poll",name:S(e.name),options:p.map(g=>S(f(g)?.optionName)).filter(g=>g!=null),selectableCount:O(e.selectableOptionsCount)??0}}let t=f(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=f(n.contactsArrayMessage);if(r!=null){let p=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:S(r.displayName),vcard:null,contacts:p.map(g=>({displayName:S(f(g)?.displayName),vcard:S(f(g)?.vcard)}))}}let s=f(n.locationMessage);if(s!=null)return {type:"location",latitude:O(s.degreesLatitude),longitude:O(s.degreesLongitude),name:S(s.name),address:S(s.address),accuracy:O(s.accuracyInMeters),speed:O(s.speedInMps),caption:S(s.comment)};let i=f(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:O(i.degreesLatitude),longitude:O(i.degreesLongitude),name:null,address:null,accuracy:O(i.accuracyInMeters),speed:O(i.speedInMps),caption:S(i.caption)};let o=f(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:O(o.expectedImageCount),expectedVideoCount:O(o.expectedVideoCount)};let a=f(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:O(a.inviteExpiration)};let c=f(f(n.productMessage)?.product);if(f(n.productMessage)!=null){let p=S(f(n.productMessage)?.businessOwnerJid),g=O(c?.priceAmount1000);return {type:"product",productId:S(c?.productId),title:S(c?.title),description:S(c?.description),price:g!=null?g/1e3:null,currency:S(c?.currencyCode),retailerId:S(c?.retailerId),url:S(c?.url),businessOwnerId:p}}let d=f(n.orderMessage);if(d!=null){let p=O(d.totalAmount1000),g={1:"inquiry",2:"accepted",3:"declined"},b=d.status;return {type:"order",orderId:S(d.orderId),title:S(d.orderTitle),itemCount:O(d.itemCount),total:p!=null?p/1e3:null,currency:S(d.totalCurrencyCode),status:typeof b=="number"?g[b]??null:S(b),message:S(d.message)}}let l=f(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||f(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||f(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let p=f(l.node),g=O(p?.amount1000),b=f(p?.noteMessage);return {type:"payment",kind:l.kind,amount:g!=null?g/1e3:null,currency:S(p?.currencyCodeIso4217),note:Z(b?.conversation,f(b?.extendedTextMessage)?.text),expiresAt:O(p?.expiryTimestamp)}}let u=f(n.eventMessage);if(u!=null){let p=f(u.location);return {type:"event",name:S(u.name),description:S(u.description),location:p!=null?Z(p.name,p.address):null,startTime:O(u.startTime),endTime:O(u.endTime),isCanceled:u.isCanceled===true}}let y=f(n.buttonsMessage);if(y!=null){let p=Array.isArray(y.buttons)?y.buttons:[];return {type:"buttons",contentText:S(y.contentText),footerText:S(y.footerText),buttons:p.map(g=>({id:S(f(g)?.buttonId),text:S(f(f(g)?.buttonText)?.displayText)}))}}let M=f(n.listMessage);if(M!=null){let p=Array.isArray(M.sections)?M.sections:[];return {type:"list",title:S(M.title),description:S(M.description),buttonText:S(M.buttonText),sections:p.map(g=>{let b=Array.isArray(f(g)?.rows)?f(g).rows:[];return {title:S(f(g)?.title),rows:b.map(E=>({id:S(f(E)?.rowId),title:S(f(E)?.title),description:S(f(E)?.description)}))}})}}let v=f(n.interactiveMessage);if(v!=null){let p=f(v.nativeFlowMessage),g=Array.isArray(p?.buttons)?p.buttons:[];return {type:"interactive",title:S(f(v.header)?.title),body:S(f(v.body)?.text),footer:S(f(v.footer)?.text),buttons:g.map(b=>({name:S(f(b)?.name),params:S(f(b)?.buttonParamsJson)}))}}let P=f(n.templateMessage);if(P!=null){let p=f(P.hydratedTemplate)??f(P.hydratedFourRowTemplate),g=Array.isArray(p?.hydratedButtons)?p.hydratedButtons:[];return {type:"template",text:S(p?.hydratedContentText),buttons:g.map(b=>{let E=f(b),pe=f(E?.quickReplyButton)??f(E?.urlButton)??f(E?.callButton);return {id:S(pe?.id),text:S(pe?.displayText)}})}}let w=f(n.extendedTextMessage);if(w!=null){let p=Z(w.canonicalUrl,w.matchedText),g=S(w.title),b=S(w.description);if(p!=null&&(g!=null||b!=null))return {type:"link",url:p,title:g,description:b}}return null};var tt=n=>{let e=f(n.message);if(e==null)return null;let t=Ae(e);return Os(t)??Ba(t)??Wa(t)},Rt=n=>{let e=f(Is(n).message);if(e==null)return null;let t=f(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(xt)){let s=e[r];if(s!=null&&typeof s=="object"){let i=s.contextInfo;if(i!=null)return i}}return null},ja=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[xt[e]];return r==null||typeof r!="object"?null:r},Ua=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(xt)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},qa=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,ae=n=>{let e=f(n);if(e==null)return "text";let t=Ae(e);for(let r of Object.values(xt))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of Fa)if(t[r]!=null)return s;return "text"},Es=(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))},Ka=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=tt(v)??"",w=ce(v,e,ae(v.message),P,nt(v,e),s);if(w!==null)return w}}let a=as(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let c=a.key.participant,d=Se(t),l=a.sender?.pushName;!d&&(c==null||c.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&Es({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof c=="string"&&(e.selfJid.length>0&&Ot(c,e.selfJid)||e.selfLid!=null&&Ot(c,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&Es(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,y=Object.assign({key:a.key,message:u??null},l!=null?{pushName:l}:{}),M=tt(y)??"";return ce(y,e,ae(u),M,nt(y,e),s)}catch{return null}},Rs=n=>Qe(Rt(n)).mentionedJids,$a=n=>{try{return Mc.jidNormalizedUser(n)}catch{return n}},_s=(n,e)=>n.map(t=>{let r=$a(t);return e.lidMap?.get(r)??r}),ks=n=>(n.split("@")[0]??"").split(":")[0]??"",Ga=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[ks(s),ks(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},ce=(n,e,t,r,s,i)=>{let o=n.key;if(o==null)return null;let a=K(o,n.pushName??void 0);if(a===null)return null;let c=Ts(o);if(c.length===0)return null;let d=Rt(n),l=Se(c),u=c.endsWith("@broadcast"),y=c.endsWith("@newsletter"),M=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=Ua(n),P=qa(n,d),w=e.channelId??"",p=e.receiverId??"",g=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),E=e.resolveReceiverName??(()=>Promise.resolve(null)),pe=()=>Ka(d,e,c,a,b,o.fromMe===true),Zt=c.length>0?c:a.pn??a.jid,Qt=(en,Ei)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(Zt,en,Ei,n),Xt=en=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,en),Ci=_s(Qe(d).mentionedJids,e),Pi=Ga(r,e.lidMap),Dn={message:n,key:o,channelId:w,receiverId:p,selfJid:e.selfJid,text:Pi,chatType:t,sender:a,mentions:Ci,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:y,prefixes:g,...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:E,resolveReplied:pe,reply:Qt,react:Xt},Bn=s!==void 0?{...Dn,media:s}:Dn;return Pn(e.citationConfig!==void 0?{...Bn,citationConfig:e.citationConfig}:Bn)},Ja=["image","video","audio","document","sticker"],Ls=(n,e,t)=>{let r=Is(n),s=ja(r,e);if(s===null)return null;let i=St(r,e,t.logger),o=Br(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:O(s.fileLength),ptt:s.ptt===true,buffer:async()=>(await i()).buffer,stream:o}},nt=(n,e)=>{let t=f(n.message);if(t==null)return;let r=ae(n.message);return Ja.includes(r)?Ls(n,r,e)??void 0:xs(Ae(t))??void 0},Ns=(n,e)=>{if(f(n.message)==null)return null;let r=ae(n.message),s=nt(n,e),i=tt(n)??"";return i===""&&s===void 0?null:ce(n,e,r,i,s)},Ds=(n,e)=>{let t=f(n.message);if(t==null)return null;let r=Ae(t),s=Os(r),i=xs(r)??void 0;return s===null&&i===void 0?null:ce(n,e,ae(n.message),s??"",i)},rt=(n,e,t)=>{let r=Ls(e,n,t);return r===null?null:ce(e,t,n,r.caption??"",r)},Bs=(n,e)=>rt("image",n,e),Ws=(n,e)=>rt("video",n,e),Fs=(n,e)=>rt("audio",n,e),js=(n,e)=>rt("document",n,e),Us=(n,e)=>rt("sticker",n,e),Ot=(n,e)=>{try{return Mc.jidNormalizedUser(n)===Mc.jidNormalizedUser(e)}catch{return n===e}},qs=(n,e)=>{if(n.key==null)return null;let r=Rt(n),s=Qe(r).mentionedJids;if(s.length===0)return null;let i=_s(s,e);if(!(i.some(u=>Ot(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Ot(u,e.selfLid)))||f(n.message)==null)return null;let c=tt(n)??"",d=nt(n,e),l=ce(n,e,ae(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},Ks=(n,e)=>{let t=n.key;if(t==null)return null;let r=Ts(t);if(r.length===0||!Se(r))return null;let{mentionAll:s}=Qe(Rt(n));if(!s||f(n.message)==null)return null;let o=tt(n)??"",a=nt(n,e),c=ce(n,e,ae(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var de=(n,e)=>{let t=be(n);return t===null?e:t},Va=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
15
- `)}return ""},Ha=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],Gs=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=K(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:de(t.senderTimestampMs,0)}},Js=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Mc.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=K(n.key,e.pushName);return s===null?null:{key:r,newContent:Va(t.editedMessage),editedAt:de(n.update.messageTimestamp,0),sender:s}},Vs=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Mc.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=K(n.key,e.pushName);if(s===null)return null;let i=Me(n.key.remoteJid),o=Me(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:de(n.update.messageTimestamp,0)}},Hs=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=K(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;return i?{pollKey:i,selectedOptions:Ha(t.vote?.selectedOptions),voter:s,timestamp:de(t.senderTimestampMs,de(n.update.messageTimestamp,0))}:null}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:de(r.senderTimestampMs,de(n.update.messageTimestamp,0))}:null}return null};var _t=n=>Array.isArray(n)?n:[],za=3e3,Ya=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),Za=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function kn(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?w=>{let p=s.get(w);if(p!==void 0)return p;let g=t.groupMetadata;if(g==null)return Promise.resolve(null);let b=g(w).then(E=>E?.subject??null).catch(()=>null);return s.set(w,b),b}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid},d=(w,p)=>{let g=(...b)=>{try{p(b[0]);}catch(E){t.logger?.warn(E,`inbound pipeline: handler for ${w} threw`);}};e.ev.on(w,g),r.push(()=>e.ev.off(w,g));},l=(w,p)=>{v(()=>Ns(w,p),g=>n.emit("message",g)),v(()=>Ds(w,p),g=>n.emit("text",g)),v(()=>Bs(w,p),g=>n.emit("image",g)),v(()=>Ws(w,p),g=>n.emit("video",g)),v(()=>Fs(w,p),g=>n.emit("audio",g)),v(()=>js(w,p),g=>n.emit("document",g)),v(()=>Us(w,p),g=>n.emit("sticker",g)),v(()=>qs(w,p),g=>n.emit("mention",g)),v(()=>Ks(w,p),g=>n.emit("mention-all",g)),v(()=>fs(w,a),g=>n.emit("button-click",g)),v(()=>hs(w,a),g=>n.emit("list-select",g));},u=w=>{if(typeof w!="string"||w.length===0)return null;let p;try{p=Mc.jidNormalizedUser(w);}catch{p=w;}return Tt(p)?p:null},y=w=>{let p=new Set;for(let g of [w.key?.participant,w.key?.remoteJid,t.selfJid,...Rs(w)]){let b=u(g);b!=null&&p.add(b);}return [...p]},M=async w=>{let p=t.resolveLidToPn;if(p==null||w.length===0)return;let g=new Map;return await Promise.all(w.map(async b=>{try{let E=await Ya(Promise.resolve(p(b)),za);if(E!=null&&E.length>0)try{g.set(b,Mc.jidNormalizedUser(E));}catch{g.set(b,E);}}catch(E){t.logger?.warn(E,"inbound pipeline: lid->pn resolve threw");}})),g.size>0?g:void 0},v=(w,p)=>{let g;try{g=w();}catch(b){t.logger?.warn(b,"inbound pipeline: decoder threw");return}g!=null&&p(g);};d("messages.upsert",w=>{let p=Zr(w);for(let g of p.messages){if(t.ignoreMe===!0&&g.key?.fromMe===!0)continue;let b=t.resolveLidToPn!=null?y(g):[];if(b.length===0){l(g,o);continue}M(b).then(E=>l(g,E!=null?{...o,lidMap:E}:o)).catch(E=>{t.logger?.warn(E,"inbound pipeline: deferred lid resolve emit failed"),l(g,o);});}}),d("messages.update",w=>{for(let p of _t(w))v(()=>Js(p,c),g=>n.emit("edit",g)),v(()=>Vs(p,c),g=>n.emit("delete",g)),v(()=>Hs(p,c),g=>n.emit("poll-vote",g));}),d("messages.reaction",w=>{for(let p of _t(w))v(()=>Gs(p,c),g=>n.emit("reaction",g));}),d("groups.update",w=>{for(let p of _t(w))v(()=>ns(p),g=>n.emit("group-update",g));}),d("group-participants.update",w=>{let p=w;v(()=>ss(p),g=>n.emit("group-join",g)),v(()=>is(p),g=>n.emit("group-leave",g));}),d("group.member-tag.update",w=>{v(()=>rs(w),p=>n.emit("member-tag",p));}),d("call",w=>{for(let p of _t(w))v(()=>Xr(p),g=>n.emit("call-incoming",g)),v(()=>es(p),g=>n.emit("call-ended",g));}),d("messaging-history.status",w=>{v(()=>ys(w),p=>n.emit("history-sync",p));}),d("presence.update",w=>{let p=(()=>{try{return ws(w)}catch(g){return t.logger?.warn(g,"inbound pipeline: decodePresence threw"),[]}})();for(let g of p)n.emit("presence",g);}),d("connection.update",w=>{let p=Za(w);p!==null&&v(()=>Cn({source:"connection-update",reachoutTimeLock:p}),g=>n.emit("limited",g));}),d("message-capping.update",w=>{v(()=>Cn({source:"message-capping",capInfo:w}),p=>n.emit("limited",p));}),d("newsletter.reaction",w=>{v(()=>Xe({source:"reaction",payload:w}),p=>n.emit("newsletter",p));}),d("newsletter.view",w=>{v(()=>Xe({source:"view",payload:w}),p=>n.emit("newsletter",p));}),d("newsletter-participants.update",w=>{v(()=>Xe({source:"participants",payload:w}),p=>n.emit("newsletter",p));}),d("newsletter-settings.update",w=>{v(()=>Xe({source:"settings",payload:w}),p=>n.emit("newsletter",p));});let P=false;return {detach(){if(!P){P=true;for(let w of r)w();r.length=0;}}}}var Lt=class{inner=new events.EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=Xa,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Xa=Symbol("zaileys.typed-ee.tag");var st=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},A=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function Tn(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var Nt="v23.0",In="https://graph.facebook.com",Ys=3,ec=500,tc=n=>new Promise(e=>setTimeout(e,n));function Dt(n,e){let t=n.baseUrl??In,r=n.apiVersion??Nt,s=tc,i=a=>`${t}/${r}/${a}`,o=async(a,c)=>{let d;for(let l=1;l<=Ys;l++){let u;try{u=await fetch(i(a),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(p){throw new A("REQUEST_FAILED","graph request failed (network)",{cause:p})}if(u.ok)return await u.json().catch(()=>({}));let y=await u.json().catch(()=>({})),M=y.error?.message??`http ${u.status}`,v=y.error?` (code ${y.error.code??"?"}${y.error.error_subcode?`/${y.error.error_subcode}`:""})`:"";if(u.status===401||u.status===403)throw new A("AUTH",`graph auth rejected: ${M}${v}`);let P=u.status===429||u.status>=500,w=u.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(d=new A(w,`graph request failed: ${M}${v}`),!P)throw d;l<Ys&&await s(ec*2**(l-1));}throw d??new A("REQUEST_FAILED","graph request failed")};return {url:i,get:a=>o(a,{method:"GET"}),post:(a,c)=>o(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(a,c)=>o(a,{method:"POST",body:c}),delete:(a,c)=>o(a,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var Zs=n=>n.split("@")[0]??n,Q=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,J=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:Zs(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function Qs(n,e,t){let r=e;if(typeof r.text=="string")return {...J(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...J(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...J(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(c=>typeof c.vcard=="string"?nc(c.vcard):null).filter(c=>c!==null);if(a.length>0)return {...J(n,"contacts",t),contacts:a}}return null}function nc(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let c=a.slice(2).split(";");s=(c[0]??"").trim(),r=(c[1]??"").trim();}if(a.startsWith("TEL")){let c=a.indexOf(":");if(c>0){let d=a.slice(c+1).trim(),l=/waid=([0-9]+)/.exec(a);d.length>0&&i.push({phone:d,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function it(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:Q(Zs(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var rc=["image","video","audio","document","sticker"];function Xs(n){let e=n;for(let t of rc){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function ei(n,e,t){let r=t.mimetype??await me(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new A("REQUEST_FAILED","media upload returned no id");return i.id}function ti(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var sc=["image","video","audio","document","sticker"],ic=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},Bt=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,oc=n=>{for(let e of sc){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},ac=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},cc=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},dc=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
10
+ `:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),yt(n.buttons,t)};var Mt=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Rr=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var ln=new WeakSet,_r=n=>{ln.add(n);},Lr=n=>{if(!ln.has(n))return n;ln.delete(n);let e=crypto.randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var ko=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],z=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,Rr(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=sr(dr(e),t):this.internal.content=Mt(e),this}image(e,t){return this.internal.pendingContent=ge(e,t),this}videoNote(e,t){return this.internal.pendingContent=te(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=te(e,t),this}audio(e,t){return this.internal.pendingContent=er(e,t),this}document(e,t){return this.internal.pendingContent=ur(e,t),this}sticker(e,t){return this.internal.pendingContent=Ir(e,t),this}buttons(e,t){return this.internal.content=yt(e,t),this}carousel(e,t){return this.internal.content=rr(e,t),this}list(e){return this.internal.content=Ar(e),this}poll(e,t,r){return this.internal.content=Er(e,t,r),this}location(e,t,r){return this.internal.content=Cr(e,t,r),this}contact(e){return this.internal.content=lr(e),this}template(e){return this.internal.content=Or(e),this}event(e){return this.internal.content=mr(e),this}groupInvite(e){return this.internal.content=gr(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=vr(e,t):this.internal.pendingContent=Sr(e,t),this}product(e){return this.internal.pendingContent=Tr(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}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.albumItems){let d={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(d.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(d.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(d.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(d.disappearingSeconds=this.internal.disappearingSeconds),Yn(this.socket,this.internal.recipient,this.internal.albumItems,d)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new p("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[R];if(i!==void 0){let d=s[xe];if(typeof d=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${d} can only be sent to a group jid ending in @g.us`);let l=s[ht],u=l!==void 0?await this.buildStatusMedia(l):i,w=s[on],M=s[cn];return this.sendRelay(u,w,M,l!==void 0)}let o=this.internal.content;this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds);let c;try{c=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(d){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new p("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await O(t.src),s=await xc.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 xc.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=xc.normalizeMessageContent(e),i=s==null?void 0:xc.getContentType(s);if(s==null||i===void 0)return;let o=s[i];if(o==null||typeof o!="object")return;let a=o.contextInfo??{};t!==void 0&&t.length>0&&(a.mentionedJid=t),r&&(a.nonJidMentions=1),o.contextInfo=a;}async sendRelay(e,t,r,s=false){let i=this.socket.relayMessage;if(typeof i!="function")throw new p("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let M=e.interactiveMessage?.header;t!==void 0&&M&&await this.uploadHeaderMedia(M,t);let v=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&v)for(let P of r){let y=v[P.index]?.header;y&&await this.uploadHeaderMedia(y,P);}}catch(M){throw new p("SEND_FAILED","interactive media upload failed",{cause:M})}let o=e;!s&&o.messageContextInfo?.messageSecret==null&&(o.messageContextInfo={...o.messageContextInfo,messageSecret:crypto.randomBytes(32)}),this.applyRelayMentions(e);let c={userJid:this.socket.user?.id??""},d=this.internal.quoted;d!==void 0&&d.message!=null&&(c.quoted=d),this.internal.disappearingSeconds!==void 0&&(c.ephemeralExpiration=this.internal.disappearingSeconds);let l=xc.generateWAMessageFromContent(this.internal.recipient,e,c);if(s&&l.message!=null&&_r(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:ko}:{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 Oe=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=Mt(e),this}image(e,t){return this.pendingContent=ge(e,t),this}video(e,t){return this.pendingContent=te(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 un=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},pn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},mn=async(n,e,t={})=>{let r=un(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);},gn=async(n,e,t)=>{let r=un(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return pn(s)},fn=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 pn(i)},St=async(n,e,t,r={})=>{let s=un(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return pn(o)};var Eo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Re=n=>Eo.test(n),hn=async(n,e,t,r=To)=>{if(Re(e))return e;let s=t.get(e);if(s!==void 0)return s;let i=r.get(e);if(i!==void 0)return i;let o=(async()=>{let c=(await n.onWhatsApp(e))?.find(d=>d.exists&&d.jid);if(!c)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,c.jid),c.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},To=new Map;var T=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 _e=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 T("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new T("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 T("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 Le=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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);}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);}};var Ne=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 T("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 De=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 Be=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 Io=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new T("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},We=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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=Io(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 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 Fe=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 je=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new T("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 xo=n=>{let e=n[0];return e==="{"||e==="["},Oo=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},Ro=n=>n===" "||n===" "||n===`
11
+ `||n==="\r",_o=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let c=n[a];if(s){t+=c,s=false,i=true,o=false;continue}if(c==="\\"&&r!==null){s=true;continue}if(r!==null){c===r?r=null:t+=c,o=false;continue}if((c==='"'||c==="'")&&o){r=c,i=true,o=false;continue}if(Ro(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},Lo=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},No=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function yn(n,e){let t=Lo(n,e);if(t===null)return No(n);let r=n.slice(t.length),s=_o(r),i={matched:true,args:[],flags:{},json:void 0,raw:n};if(s.length===0)return i.name="",i;i.name=(s[0]??"").toLowerCase();let o=false;for(let a=1;a<s.length;a+=1){let c=s[a];if(c!==void 0){if(c.startsWith("--")){let d=c.slice(2);if(d.length===0){i.args.push(c);continue}let l=d.indexOf("=");if(l!==-1){let w=d.slice(0,l),M=d.slice(l+1);i.flags[w]=M;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[d]=u,a+=1):i.flags[d]=true;continue}if(!o&&xo(c)){let d=Oo(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var Nr=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new _("INVALID_COMMAND_NAME","empty command segment in spec");return e},we=n=>n.join(" "),Ue=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new _("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>Nr(a)),s=r[0],i=r.slice(1).map(a=>we(a)),o={name:we(s),aliases:i,parts:s,handler:t};for(let a of r){let c=we(a);if(this.paths.has(c))throw new _("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set(we(a),o),a.length>this.maxDepth&&(this.maxDepth=a.length);this.defs.push(o);}resolve(e){if(!e.matched||e.name===void 0||e.name.length===0)return;let t=[e.name.toLowerCase(),...e.args.map(s=>s.toLowerCase())],r=Math.min(this.maxDepth,t.length);for(let s=r;s>=1;s-=1){let i=t.slice(0,s).join(" "),o=this.paths.get(i);if(o!==void 0)return {def:o,args:e.args.slice(s-1)}}}unregister(e){let t=e.split("|").map(o=>Nr(o)),r=we(t[0]),s=this.paths.get(r);if(s===void 0)return;for(let o of [s.parts,...s.aliases.map(a=>a.split(" "))])this.paths.delete(we(o));let i=this.defs.indexOf(s);i>=0&&this.defs.splice(i,1),this.maxDepth=this.defs.reduce((o,a)=>Math.max(o,a.parts.length),1);}list(){return [...this.defs]}};async function wn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new _("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(c){throw s.error=c,s.thrown=true,c}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(c){throw s.thrown||c instanceof _?c:new _("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function vn(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=yn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0)return;let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},c=n.buildContext(a,s);Promise.resolve(wn(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let l=d instanceof _?d:new _("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(l,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Dr=n=>n;var qe=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t){if(typeof e?.name!="string"||typeof e?.setup!="function"){this.logger?.warn({file:t},"plugin: invalid shape (need name + setup); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let r=[],s={client:this.host,logger:this.logger,pluginDir:ze__default.default.dirname(t),command:(i,o)=>{this.host.command(i,o),r.push(()=>this.host.unregisterCommand(i));},use:i=>{this.host.use(i),r.push(()=>{this.host.unuse(i);});},on:(i,o)=>{let a=this.host.on(i,o);return r.push(a),a},once:(i,o)=>{let a=false,c=this.host.on(i,d=>{a||(a=true,c(),o(d));});return r.push(c),c}};try{let i=await e.setup(s);typeof i=="function"&&r.push(i);}catch(i){for(let o of [...r].reverse())try{await o();}catch{}this.logger?.error({err:i,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:r});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Fo=/\.(ts|js|mjs|cjs)$/,jo=/(\.d\.ts$|^_|[/\\]_)/;async function Sn(n,e,t){let r;try{r=await fs$1.promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=ze__default.default.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await Sn(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function Wr(n,e){try{let r=await import(url.pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"&&typeof s.setup=="function"?s:void 0}catch{return}}var Ke=class{dir;pattern;ignore;watchEnabled;onError;registry;logger;watcher;fileToName=new Map;bust=0;debounce;pending=new Set;flushChain=Promise.resolve();constructor(e){this.registry=e.registry,this.logger=e.logger,this.dir=ze__default.default.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Fo,this.ignore=e.options.ignore??jo,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await Sn(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 Wr(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=fs$1.watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=ze__default.default.join(this.dir,t.toString());this.ignore.test(t.toString())||!this.pattern.test(t.toString())||(this.pending.add(r),this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{this.flushChain=this.flushChain.then(()=>this.flush());},150),this.debounce.unref?.());});}catch(e){this.logger?.warn({err:e,dir:this.dir},"plugin: watch unavailable; hot-reload disabled");}}async flush(){let e=[...this.pending];this.pending.clear(),this.bust+=1;for(let t of e){let r=this.fileToName.get(t);r&&(await this.registry.unload(r),this.fileToName.delete(t));let s=true;try{await fs$1.promises.access(t);}catch{s=false;}s&&await this.loadFile(t);}}};var I=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 Uo=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ie=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new I("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new I("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new I("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??Uo;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 qo={"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},Ko=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function bn(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??Ko,i={...qo,...n.intervalsMs??{}},o=new Map,a=new Map,c=async(d,l)=>{let u=i[d]??0,w=o.get(d);if(w!==void 0&&u>0){let M=u-(r()-w);M>0&&await s(M);}return o.set(d,r()),l()};return {run(d,l){if(!t)return l();let w=(a.get(d)??Promise.resolve()).then(()=>c(d,l),()=>c(d,l));return a.set(d,w.then(()=>{},()=>{})),w}}}var $o={maxRetries:0,backoffMs:()=>0},Go=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),$e=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??$o,this.sleep=t.sleep??Go;}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 Jo=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function An(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 ie({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},l=c?new $e({concurrency:1,retry:c},d):void 0,u=n.length,w=0;for(let M of n){await a.acquire(M);let v=()=>e(t.sendTo(M)).then(()=>{});try{l?await l.add(v):await v(),s.sent.push(M),w+=1,r.onProgress?.(w,u,M,!0);}catch(P){s.failed.push({jid:M,error:Jo(P)}),w+=1,r.onProgress?.(w,u,M,false);}}return s}var Vo=1e3,Ge=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??Vo,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new Map;requireSocket(){let e=this.getSocket();if(!e)throw new I("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 I("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 zo={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},Yo=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",Je=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??zo,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new I("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),Yo(e.payload))try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed; retaining job for retry");return}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,c)=>{if(r+=1,r>1)throw new I("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=c?{recipient:o,content:a,options:c}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new I("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=z.create(s,"");try{await e(i);}catch(o){throw o instanceof I?o:new I("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new I("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function Fr(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((c,d)=>Number(d.messageTimestamp??0)-Number(c.messageTimestamp??0));for(let c=0;c<a.length;c+=1){let d=a[c],l=Number(d.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,w=e.maxPerChat!==void 0&&c>=e.maxPerChat;(u||w)&&(await n.deleteMessage(d.key),r+=1);}}return r}var Ve=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"?Fr(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 jr=n=>(n.split(/[:@]/)[0]??"").replace(/\D/g,""),He=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 I("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=jr(e);return t.some(s=>s===e||jr(s)===r)}return await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var Zo={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Qo=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Zo[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},bt=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=Qo(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")}},Ur=(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 oe="[zaileys]",Xo="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 Kr(n){switch(n.kind){case "connecting":return `${oe} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${oe} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${oe} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${oe} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${oe} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
12
+ ${oe} ${Xo}`:t}case "disconnect":return n.willReconnect?null:`${oe} Disconnected (${n.reason}).`;default:return null}}var qr=false,ea=["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:"],ta=n=>typeof n[0]=="string"&&ea.some(e=>n[0].startsWith(e));function $r(){if(qr)return;qr=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{ta(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 ra="./.zaileys/auth",sa=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),Ye=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",Ct=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??ra;}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,xc.BufferJSON.reviver);}catch(o){if(Ye(o))return;throw new h("STORE_READ_FAILED",`failed to read ${i}`,{cause:o})}})),r},write:async e=>{this.assertOpen();let t=[];for(let r of Object.keys(e)){let s=e[r];if(!s)continue;let i=this.signalDir(r);await fs$1.promises.mkdir(i,{recursive:true});for(let o of Object.keys(s)){let a=s[o],c=this.signalPath(r,o);a===null?t.push(fs$1.promises.unlink(c).catch(d=>{if(!Ye(d))throw new h("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,xc.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(!Ye(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,xc.BufferJSON.reviver)}catch(e){if(Ye(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,xc.BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await fs$1.promises.unlink(this.credsPath());}catch(e){if(!Ye(e))throw new h("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return ze__default.default.join(this.basePath,"creds.json")}signalDir(e){return ze__default.default.join(this.basePath,"signal",String(e))}signalPath(e,t){return ze__default.default.join(this.signalDir(e),`${sa(t)}.json`)}async atomicWrite(e,t){let r=ze__default.default.join(ze__default.default.dirname(e),`tmp-${crypto.randomBytes(8).toString("hex")}`);try{await fs$1.promises.writeFile(r,t,"utf8"),await fs$1.promises.rename(r,e);}catch(s){throw await fs$1.promises.unlink(r).catch(()=>{}),new h("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:s})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","FileAuthStore is closed")}};function Gr(n,e){let t=n.signal,s=xc.makeCacheableSignalKeyStore({get:(o,a)=>t.read(o,a),set:o=>t.write(o),clear:()=>t.clear()},e?.logger??void 0),i={read:async(o,a)=>await s.get(o,[...a]),write:async o=>{await s.set(o);},delete:async(o,a)=>{await t.delete(o,a);let c={},d={};for(let l of a)d[l]=null;c[o]=d,await s.set(c);},clear:async()=>{let o=s.clear;typeof o=="function"?await o.call(s):await t.clear();},close:()=>t.close()};return {creds:n.creds,signal:i}}function Jr(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 oa=429;function Vr(n){if(n===oa)return "rate-limited";switch(n){case xc.DisconnectReason.loggedOut:return "logged-out";case xc.DisconnectReason.forbidden:return "forbidden";case xc.DisconnectReason.connectionLost:return "connection-lost";case xc.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case xc.DisconnectReason.connectionClosed:return "connection-closed";case xc.DisconnectReason.connectionReplaced:return "connection-replaced";case xc.DisconnectReason.badSession:return "bad-session";case xc.DisconnectReason.unavailableService:return "unavailable-service";case xc.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function Ze(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Pt(n){return n==="rate-limited"}function Hr(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function Um(n){return !Ze(n)}var kt={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},aa=3e5;function zr(n={}){let e=n.enabled??kt.enabled,t=n.maxQrAttempts??kt.maxQrAttempts,r=n.maxPairingAttempts??kt.maxPairingAttempts,s=n.pairingCooldownMs??kt.pairingCooldownMs,i=0,o=0,a=0,c=w=>w<=0?0:Math.min(s*w,aa);return {evaluate:(w,M)=>{if(!e)return {allowed:true,waitMs:0,attempts:w==="pairing"?o:i,max:Number.POSITIVE_INFINITY};if(w==="pairing"){if(o>=r)return {allowed:false,reason:"budget-exhausted",waitMs:0,attempts:o,max:r};let v=c(o),P=M-a;return o>0&&P<v?{allowed:false,reason:"cooldown",waitMs:v-P,attempts:o,max:r}:{allowed:true,waitMs:0,attempts:o,max:r}}return i>=t?{allowed:false,reason:"budget-exhausted",waitMs:0,attempts:i,max:t}:{allowed:true,waitMs:0,attempts:i,max:t}},record:(w,M)=>{w==="pairing"?(o+=1,a=M):i+=1;},reset:()=>{i=0,o=0,a=0;},get enabled(){return e},get qrAttempts(){return i},get pairingAttempts(){return o}}}var ca=/[\s\-()+]/g;function da(n){return typeof n!="string"?"":n.replace(ca,"")}function la(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=da(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 Yr(n){let e=la(n.phoneNumber),t=n.ttlMs??6e4;return {phoneNumber:e,async requestCode(r){let s;try{s=await r.requestPairingCode(e);}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`failed to request pairing code: ${o}`)}return {code:s,expiresAt:Date.now()+t}}}}function pa(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{ua__default.default.generate(n,{small:true},t=>e(t));})}async function Zr(n,e=t=>{process.stdout.write(t);}){let t=await pa(n);e(t+`
13
+ `);}var ve={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function Qr(n,e){let t=n?.enabled??ve.enabled,r=n?.maxAttempts??ve.maxAttempts,s=n?.initialDelayMs??ve.initialDelayMs,i=n?.maxDelayMs??ve.maxDelayMs,o=n?.jitterFactor??ve.jitterFactor,a=n?.rateLimitedDelayMs??ve.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:w=>{if(!t||Ze(w))return null;let M=d+1;if(M>r)return null;if(d=M,Pt(w))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),y=1+(c()*2-1)*o,m=P*y,g=Math.min(i,Math.max(0,m));return {attempt:M,delayMs:Math.round(g)}},reset:()=>{d=0;},get attempts(){return d}}}var ma={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 Xr(n="idle"){let e=n,t=new Set,r=s=>ma[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 Et=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Tt=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=Et(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(Et(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(Et(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=Et(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var fa=["silent","fatal","error","warn","info","debug","trace"];function ha(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":fa.includes(e)?e:"silent"}function ya(n={}){let e=ha(n.level),t=ga__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var es=["debug","info","warn","error","fatal"];function wa(n){if(n===null||typeof n!="object")return false;for(let e of es)if(typeof n[e]!="function")return false;return true}function Qe(){}function va(n){let e={debug:Qe,info:Qe,warn:Qe,error:Qe,fatal:Qe};for(let t of es){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function Cn(n,e){return n===void 0?e??ya():wa(n)?n:va(n)}var eg=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),ts=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 Ma=new Set(["offer","ringing"]),Sa=new Set(["timeout","reject","accept","terminate"]),ns=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},rs=n=>typeof n.id!="string"||n.id.length===0||!Ma.has(n.status)?null:{kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:ns(n.date),status:n.status},ss=n=>typeof n.id!="string"||n.id.length===0||!Sa.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:ns(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,ba=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},is=(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}),os=n=>B(n?.id)?{groupId:n.id,update:ba(n),timestamp:Date.now()}:null,as=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},Aa=new Set(["add","invite","invite-link"]),Ca=new Set(["remove","leave"]),cs=n=>{if(!B(n?.id)||!Aa.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=is(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},ds=n=>{if(!B(n?.id)||!Ca.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=is(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 Me=n=>typeof n!="string"||n.length===0?null:xc.jidNormalizedUser(n),Y=n=>typeof n=="string"&&n.length>0?n:void 0,Ea=["@s.whatsapp.net","@c.us"],It=n=>n.endsWith("@lid"),ls=n=>Ea.some(e=>n.endsWith(e)),K=(n,e)=>{if(!n)return null;let t=Y(n.participant)??n.remoteJid,r=Me(t);if(r===null)return null;let s=Y(n.participantAlt)??Y(n.remoteJidAlt),i=s!=null?Me(s):null,o=Y(n.participantUsername)??Y(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(It),l=c.find(ls);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Y(e);return u!==void 0&&(a.pushName=u),a},us=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=Y(n.participant),r=Y(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=K(s);return o&&(i.sender=o),i},Xe=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 Se=n=>xc.isJidGroup(n)===true,be=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},f=n=>n!=null&&typeof n=="object"?n:null,ps=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],ms=["groupStatusMessage","groupStatusMessageV2"],gs=(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 ps){let o=f(f(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Ae=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of ps){let i=f(f(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var Ta=["quick_reply","cta_url","cta_call","button_click"],Ia=["list_select","single_select"],G=n=>typeof n=="string"&&n.length>0,hs=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return K(n.key,e)},ys=n=>be(n.messageTimestamp)??0,ws=(n,e)=>{if(!G(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}},xt=(n,e)=>{for(let t of e){let r=n[t];if(G(r))return r}},vs=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&G(r.selectedButtonId))return Pn(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&G(s.selectedId))return Pn(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&G(i.name)&&Ta.includes(i.name)){let o=ws(i.paramsJson,e.logger);if(!o)return null;let a=xt(o,["id","button_id"]);return a===void 0?null:Pn(n,a,xt(o,["display_text"])??null)}return null},Pn=(n,e,t)=>{let r=hs(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:ys(n)};return G(t)&&(s.buttonText=t),s},Ms=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(G(s))return fs(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&G(i.name)&&Ia.includes(i.name)){let o=ws(i.paramsJson,e.logger);if(!o)return null;let a=xt(o,["row_id","id"]);return a===void 0?null:fs(n,a,xt(o,["title"])??null)}return null},fs=(n,e,t)=>{let r=hs(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:ys(n)};return G(t)&&(s.title=t),s};var xa=new Set(["available","unavailable","composing","recording","paused"]),Oa=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,Ss=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},kn=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:Oa(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},bs=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"||!xa.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},et=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 Cs=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},As=(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=>(As(n).toString(16).padStart(8,"0")+As(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),ks=n=>Ps(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),Es=(n,e)=>Ps(`${n??""}|${e}`),Ts=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},Is=n=>{let e=xc.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"},_a=n=>n.trim().endsWith("?"),La=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Na=(n,e)=>{if(e.length===0)return false;let t;try{t=xc.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return xc.jidNormalizedUser(r)===t}catch{return r===n}})},Da=(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)}},Ba=0,Wa=14,Fa=1,ja=2,Ua=n=>{let e=f(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=f(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof f(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Wa,isDeleted:r===Ba,isPinned:s===Fa,isUnPinned:s===ja,isBot:f(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:gs(e,ms)}},En=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Se(e),r=Ua(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?xc.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(xc.jidNormalizedUser(e)):i,a={uniqueId:ks(n.key),staticId:Es(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(xc.jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderDevice:Is(n.sender.deviceJid??n.sender.jid),timestamp:Ts(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Cs(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isQuestion:_a(n.text),isPrefix:La(n.text,n.prefixes),isTagMe:Na(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:Da(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var Rt={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Rs=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},S=n=>typeof n=="string"&&n.length>0?n:null,Z=(...n)=>{for(let e of n){let t=S(e);if(t!=null)return t}return null},_s=n=>{let e=f(n.message);if(e==null)return n;let t=Ae(e);return t===e?n:{...n,message:t}},qa=n=>{let t=f(f(f(n.botForwardedMessage)?.message)?.richResponseMessage)??f(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(f(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
14
+ `).trim();return i.length>0?i:null},Ka=n=>{let e=f(n.templateMessage),t=f(e?.hydratedTemplate)??f(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},$a=n=>Z(f(n.pollCreationMessage)?.name,f(n.pollCreationMessageV2)?.name,f(n.pollCreationMessageV3)?.name),Ga=n=>{let e=f(n.locationMessage)??f(n.liveLocationMessage);if(e==null)return null;let t=Z(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},Ja=n=>{let e=S(f(n.contactMessage)?.displayName);if(e!=null)return e;let t=f(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(f(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},Ls=n=>Z(n.conversation,f(n.extendedTextMessage)?.text,qa(n),S(f(f(n.interactiveMessage)?.body)?.text),f(n.buttonsMessage)?.contentText,f(n.listMessage)?.description,Ka(n),$a(n),Ga(n),Ja(n)),Va=n=>Z(f(n.buttonsResponseMessage)?.selectedDisplayText,f(n.buttonsResponseMessage)?.selectedButtonId,f(n.templateButtonReplyMessage)?.selectedDisplayText,f(n.templateButtonReplyMessage)?.selectedId,f(n.listResponseMessage)?.title,f(f(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,f(f(n.interactiveResponseMessage)?.body)?.text),Ha=n=>Z(f(n.imageMessage)?.caption,f(n.videoMessage)?.caption,f(n.documentMessage)?.caption,f(n.documentMessage)?.fileName),x=n=>{if(typeof n=="number")return n;let e=be(n);return typeof e=="number"?e:null},za=[["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"]],Ns=n=>{let e=f(n.pollCreationMessage)??f(n.pollCreationMessageV2)??f(n.pollCreationMessageV3);if(e!=null){let m=Array.isArray(e.options)?e.options:[];return {type:"poll",name:S(e.name),options:m.map(g=>S(f(g)?.optionName)).filter(g=>g!=null),selectableCount:x(e.selectableOptionsCount)??0}}let t=f(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=f(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(g=>({displayName:S(f(g)?.displayName),vcard:S(f(g)?.vcard)}))}}let s=f(n.locationMessage);if(s!=null)return {type:"location",latitude:x(s.degreesLatitude),longitude:x(s.degreesLongitude),name:S(s.name),address:S(s.address),accuracy:x(s.accuracyInMeters),speed:x(s.speedInMps),caption:S(s.comment)};let i=f(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:x(i.degreesLatitude),longitude:x(i.degreesLongitude),name:null,address:null,accuracy:x(i.accuracyInMeters),speed:x(i.speedInMps),caption:S(i.caption)};let o=f(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:x(o.expectedImageCount),expectedVideoCount:x(o.expectedVideoCount)};let a=f(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:x(a.inviteExpiration)};let c=f(f(n.productMessage)?.product);if(f(n.productMessage)!=null){let m=S(f(n.productMessage)?.businessOwnerJid),g=x(c?.priceAmount1000);return {type:"product",productId:S(c?.productId),title:S(c?.title),description:S(c?.description),price:g!=null?g/1e3:null,currency:S(c?.currencyCode),retailerId:S(c?.retailerId),url:S(c?.url),businessOwnerId:m}}let d=f(n.orderMessage);if(d!=null){let m=x(d.totalAmount1000),g={1:"inquiry",2:"accepted",3:"declined"},b=d.status;return {type:"order",orderId:S(d.orderId),title:S(d.orderTitle),itemCount:x(d.itemCount),total:m!=null?m/1e3:null,currency:S(d.totalCurrencyCode),status:typeof b=="number"?g[b]??null:S(b),message:S(d.message)}}let l=f(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||f(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||f(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let m=f(l.node),g=x(m?.amount1000),b=f(m?.noteMessage);return {type:"payment",kind:l.kind,amount:g!=null?g/1e3:null,currency:S(m?.currencyCodeIso4217),note:Z(b?.conversation,f(b?.extendedTextMessage)?.text),expiresAt:x(m?.expiryTimestamp)}}let u=f(n.eventMessage);if(u!=null){let m=f(u.location);return {type:"event",name:S(u.name),description:S(u.description),location:m!=null?Z(m.name,m.address):null,startTime:x(u.startTime),endTime:x(u.endTime),isCanceled:u.isCanceled===true}}let w=f(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(g=>({id:S(f(g)?.buttonId),text:S(f(f(g)?.buttonText)?.displayText)}))}}let M=f(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(g=>{let b=Array.isArray(f(g)?.rows)?f(g).rows:[];return {title:S(f(g)?.title),rows:b.map(k=>({id:S(f(k)?.rowId),title:S(f(k)?.title),description:S(f(k)?.description)}))}})}}let v=f(n.interactiveMessage);if(v!=null){let m=f(v.nativeFlowMessage),g=Array.isArray(m?.buttons)?m.buttons:[];return {type:"interactive",title:S(f(v.header)?.title),body:S(f(v.body)?.text),footer:S(f(v.footer)?.text),buttons:g.map(b=>({name:S(f(b)?.name),params:S(f(b)?.buttonParamsJson)}))}}let P=f(n.templateMessage);if(P!=null){let m=f(P.hydratedTemplate)??f(P.hydratedFourRowTemplate),g=Array.isArray(m?.hydratedButtons)?m.hydratedButtons:[];return {type:"template",text:S(m?.hydratedContentText),buttons:g.map(b=>{let k=f(b),pe=f(k?.quickReplyButton)??f(k?.urlButton)??f(k?.callButton);return {id:S(pe?.id),text:S(pe?.displayText)}})}}let y=f(n.extendedTextMessage);if(y!=null){let m=Z(y.canonicalUrl,y.matchedText),g=S(y.title),b=S(y.description);if(m!=null&&(g!=null||b!=null))return {type:"link",url:m,title:g,description:b}}return null};var nt=n=>{let e=f(n.message);if(e==null)return null;let t=Ae(e);return Ls(t)??Va(t)??Ha(t)},_t=n=>{let e=f(_s(n).message);if(e==null)return null;let t=f(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(Rt)){let s=e[r];if(s!=null&&typeof s=="object"){let i=s.contextInfo;if(i!=null)return i}}return null},Ya=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Rt[e]];return r==null||typeof r!="object"?null:r},Za=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(Rt)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},Qa=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,ae=n=>{let e=f(n);if(e==null)return "text";let t=Ae(e);for(let r of Object.values(Rt))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of za)if(t[r]!=null)return s;return "text"},xs=(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=nt(v)??"",y=ce(v,e,ae(v.message),P,rt(v,e),s);if(y!==null)return y}}let a=us(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let c=a.key.participant,d=Se(t),l=a.sender?.pushName;!d&&(c==null||c.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&xs({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof c=="string"&&(e.selfJid.length>0&&Ot(c,e.selfJid)||e.selfLid!=null&&Ot(c,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&xs(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=nt(w)??"";return ce(w,e,ae(u),M,rt(w,e),s)}catch{return null}},Ds=n=>Xe(_t(n)).mentionedJids,ec=n=>{try{return xc.jidNormalizedUser(n)}catch{return n}},Bs=(n,e)=>n.map(t=>{let r=ec(t);return e.lidMap?.get(r)??r}),Os=n=>(n.split("@")[0]??"").split(":")[0]??"",tc=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[Os(s),Os(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=K(o,n.pushName??void 0);if(a===null)return null;let c=Rs(o);if(c.length===0)return null;let d=_t(n),l=Se(c),u=c.endsWith("@broadcast"),w=c.endsWith("@newsletter"),M=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=Za(n),P=Qa(n,d),y=e.channelId??"",m=e.receiverId??"",g=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),k=e.resolveReceiverName??(()=>Promise.resolve(null)),pe=()=>Xa(d,e,c,a,b,o.fromMe===true),Qt=c.length>0?c:a.pn??a.jid,Xt=(tn,xi)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(Qt,tn,xi,n),en=tn=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,tn),Ti=Bs(Xe(d).mentionedJids,e),Ii=tc(r,e.lidMap),Wn={message:n,key:o,channelId:y,receiverId:m,selfJid:e.selfJid,text:Ii,chatType:t,sender:a,mentions:Ti,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:w,prefixes:g,...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:k,resolveReplied:pe,reply:Xt,react:en},Fn=s!==void 0?{...Wn,media:s}:Wn;return En(e.citationConfig!==void 0?{...Fn,citationConfig:e.citationConfig}:Fn)},nc=["image","video","audio","document","sticker"],Ws=(n,e,t)=>{let r=_s(n),s=Ya(r,e);if(s===null)return null;let i=bt(r,e,t.logger),o=Ur(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:x(s.fileLength),ptt:s.ptt===true,buffer:async()=>(await i()).buffer,stream:o}},rt=(n,e)=>{let t=f(n.message);if(t==null)return;let r=ae(n.message);return nc.includes(r)?Ws(n,r,e)??void 0:Ns(Ae(t))??void 0},Fs=(n,e)=>{if(f(n.message)==null)return null;let r=ae(n.message),s=rt(n,e),i=nt(n)??"";return i===""&&s===void 0?null:ce(n,e,r,i,s)},js=(n,e)=>{let t=f(n.message);if(t==null)return null;let r=Ae(t),s=Ls(r),i=Ns(r)??void 0;return s===null&&i===void 0?null:ce(n,e,ae(n.message),s??"",i)},st=(n,e,t)=>{let r=Ws(e,n,t);return r===null?null:ce(e,t,n,r.caption??"",r)},Us=(n,e)=>st("image",n,e),qs=(n,e)=>st("video",n,e),Ks=(n,e)=>st("audio",n,e),$s=(n,e)=>st("document",n,e),Gs=(n,e)=>st("sticker",n,e),Ot=(n,e)=>{try{return xc.jidNormalizedUser(n)===xc.jidNormalizedUser(e)}catch{return n===e}},Js=(n,e)=>{if(n.key==null)return null;let r=_t(n),s=Xe(r).mentionedJids;if(s.length===0)return null;let i=Bs(s,e);if(!(i.some(u=>Ot(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Ot(u,e.selfLid)))||f(n.message)==null)return null;let c=nt(n)??"",d=rt(n,e),l=ce(n,e,ae(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},Vs=(n,e)=>{let t=n.key;if(t==null)return null;let r=Rs(t);if(r.length===0||!Se(r))return null;let{mentionAll:s}=Xe(_t(n));if(!s||f(n.message)==null)return null;let o=nt(n)??"",a=rt(n,e),c=ce(n,e,ae(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var de=(n,e)=>{let t=be(n);return t===null?e:t},rc=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
15
+ `)}return ""},sc=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],zs=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=K(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:de(t.senderTimestampMs,0)}},Ys=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==xc.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=K(n.key,e.pushName);return s===null?null:{key:r,newContent:rc(t.editedMessage),editedAt:de(n.update.messageTimestamp,0),sender:s}},Zs=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==xc.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=K(n.key,e.pushName);if(s===null)return null;let i=Me(n.key.remoteJid),o=Me(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:de(n.update.messageTimestamp,0)}},Qs=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=K(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;return i?{pollKey:i,selectedOptions:sc(t.vote?.selectedOptions),voter:s,timestamp:de(t.senderTimestampMs,de(n.update.messageTimestamp,0))}:null}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:de(r.senderTimestampMs,de(n.update.messageTimestamp,0))}:null}return null};var Lt=n=>Array.isArray(n)?n:[],ic=3e3,oc=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),ac=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function In(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?y=>{let m=s.get(y);if(m!==void 0)return m;let g=t.groupMetadata;if(g==null)return Promise.resolve(null);let b=g(y).then(k=>k?.subject??null).catch(()=>null);return s.set(y,b),b}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid},d=(y,m)=>{let g=(...b)=>{try{m(b[0]);}catch(k){t.logger?.warn(k,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,g),r.push(()=>e.ev.off(y,g));},l=(y,m)=>{v(()=>Fs(y,m),g=>n.emit("message",g)),v(()=>js(y,m),g=>n.emit("text",g)),v(()=>Us(y,m),g=>n.emit("image",g)),v(()=>qs(y,m),g=>n.emit("video",g)),v(()=>Ks(y,m),g=>n.emit("audio",g)),v(()=>$s(y,m),g=>n.emit("document",g)),v(()=>Gs(y,m),g=>n.emit("sticker",g)),v(()=>Js(y,m),g=>n.emit("mention",g)),v(()=>Vs(y,m),g=>n.emit("mention-all",g)),v(()=>vs(y,a),g=>n.emit("button-click",g)),v(()=>Ms(y,a),g=>n.emit("list-select",g));},u=y=>{if(typeof y!="string"||y.length===0)return null;let m;try{m=xc.jidNormalizedUser(y);}catch{m=y;}return It(m)?m:null},w=y=>{let m=new Set;for(let g of [y.key?.participant,y.key?.remoteJid,t.selfJid,...Ds(y)]){let b=u(g);b!=null&&m.add(b);}return [...m]},M=async y=>{let m=t.resolveLidToPn;if(m==null||y.length===0)return;let g=new Map;return await Promise.all(y.map(async b=>{try{let k=await oc(Promise.resolve(m(b)),ic);if(k!=null&&k.length>0)try{g.set(b,xc.jidNormalizedUser(k));}catch{g.set(b,k);}}catch(k){t.logger?.warn(k,"inbound pipeline: lid->pn resolve threw");}})),g.size>0?g:void 0},v=(y,m)=>{let g;try{g=y();}catch(b){t.logger?.warn(b,"inbound pipeline: decoder threw");return}g!=null&&m(g);};d("messages.upsert",y=>{let m=ts(y);for(let g of m.messages){if(t.ignoreMe===!0&&g.key?.fromMe===!0)continue;let b=t.resolveLidToPn!=null?w(g):[];if(b.length===0){l(g,o);continue}M(b).then(k=>l(g,k!=null?{...o,lidMap:k}:o)).catch(k=>{t.logger?.warn(k,"inbound pipeline: deferred lid resolve emit failed"),l(g,o);});}}),d("messages.update",y=>{for(let m of Lt(y))v(()=>Ys(m,c),g=>n.emit("edit",g)),v(()=>Zs(m,c),g=>n.emit("delete",g)),v(()=>Qs(m,c),g=>n.emit("poll-vote",g));}),d("messages.reaction",y=>{for(let m of Lt(y))v(()=>zs(m,c),g=>n.emit("reaction",g));}),d("groups.update",y=>{for(let m of Lt(y))v(()=>os(m),g=>n.emit("group-update",g));}),d("group-participants.update",y=>{let m=y;v(()=>cs(m),g=>n.emit("group-join",g)),v(()=>ds(m),g=>n.emit("group-leave",g));}),d("group.member-tag.update",y=>{v(()=>as(y),m=>n.emit("member-tag",m));}),d("call",y=>{for(let m of Lt(y))v(()=>rs(m),g=>n.emit("call-incoming",g)),v(()=>ss(m),g=>n.emit("call-ended",g));}),d("messaging-history.status",y=>{v(()=>Ss(y),m=>n.emit("history-sync",m));}),d("presence.update",y=>{let m=(()=>{try{return bs(y)}catch(g){return t.logger?.warn(g,"inbound pipeline: decodePresence threw"),[]}})();for(let g of m)n.emit("presence",g);}),d("connection.update",y=>{let m=ac(y);m!==null&&v(()=>kn({source:"connection-update",reachoutTimeLock:m}),g=>n.emit("limited",g));}),d("message-capping.update",y=>{v(()=>kn({source:"message-capping",capInfo:y}),m=>n.emit("limited",m));}),d("newsletter.reaction",y=>{v(()=>et({source:"reaction",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter.view",y=>{v(()=>et({source:"view",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-participants.update",y=>{v(()=>et({source:"participants",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-settings.update",y=>{v(()=>et({source:"settings",payload:y}),m=>n.emit("newsletter",m));});let P=false;return {detach(){if(!P){P=true;for(let y of r)y();r.length=0;}}}}var Nt=class{inner=new events.EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=dc,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},dc=Symbol("zaileys.typed-ee.tag");var it=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},A=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function xn(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var Dt="v23.0",On="https://graph.facebook.com",ei=3,lc=500,uc=n=>new Promise(e=>setTimeout(e,n));function Bt(n,e){let t=n.baseUrl??On,r=n.apiVersion??Dt,s=uc,i=a=>`${t}/${r}/${a}`,o=async(a,c)=>{let d;for(let l=1;l<=ei;l++){let u;try{u=await fetch(i(a),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(m){throw new A("REQUEST_FAILED","graph request failed (network)",{cause:m})}if(u.ok)return await u.json().catch(()=>({}));let w=await u.json().catch(()=>({})),M=w.error?.message??`http ${u.status}`,v=w.error?` (code ${w.error.code??"?"}${w.error.error_subcode?`/${w.error.error_subcode}`:""})`:"";if(u.status===401||u.status===403)throw new A("AUTH",`graph auth rejected: ${M}${v}`);let P=u.status===429||u.status>=500,y=u.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(d=new A(y,`graph request failed: ${M}${v}`),!P)throw d;l<ei&&await s(lc*2**(l-1));}throw d??new A("REQUEST_FAILED","graph request failed")};return {url:i,get:a=>o(a,{method:"GET"}),post:(a,c)=>o(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(a,c)=>o(a,{method:"POST",body:c}),delete:(a,c)=>o(a,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var ti=n=>n.split("@")[0]??n,Q=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,J=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:ti(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function ni(n,e,t){let r=e;if(typeof r.text=="string")return {...J(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...J(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...J(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(c=>typeof c.vcard=="string"?pc(c.vcard):null).filter(c=>c!==null);if(a.length>0)return {...J(n,"contacts",t),contacts:a}}return null}function pc(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let c=a.slice(2).split(";");s=(c[0]??"").trim(),r=(c[1]??"").trim();}if(a.startsWith("TEL")){let c=a.indexOf(":");if(c>0){let d=a.slice(c+1).trim(),l=/waid=([0-9]+)/.exec(a);d.length>0&&i.push({phone:d,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function ot(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:Q(ti(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var mc=["image","video","audio","document","sticker"];function ri(n){let e=n;for(let t of mc){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function si(n,e,t){let r=t.mimetype??await me(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new A("REQUEST_FAILED","media upload returned no id");return i.id}function ii(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var gc=["image","video","audio","document","sticker"],fc=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},Wt=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,hc=n=>{for(let e of gc){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},yc=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},wc=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},vc=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
16
16
  `);return {displayName:i,vcard:`BEGIN:VCARD
17
17
  VERSION:3.0
18
18
  FN:${i}${o?`
19
19
  ${o}`:""}
20
- END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},lc=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:Q(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},uc=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:oc(n)??ac(n)??cc(n)??dc(n);if(t===null)return null;let r=lc(t,n),s=Bt(e,n.from);return {key:{id:n.id,remoteJid:Q(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},pc=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?Q(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},mc=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Bt(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:Q(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},gc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Bt(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:Q(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},fc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=Q(n.from),s=Bt(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ni(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let c of a.changes??[]){let d=c.value;if(d){if(c.field==="message_template_status_update"){let l=ic(d);l&&s.push(l);continue}for(let l of d.messages??[]){let u=fc(l,d);if(u){t.push(u);continue}let y=mc(l,d);if(y){i.push(y);continue}let M=gc(l,d);if(M){o.push(M);continue}let v=uc(l,d);v&&e.push(v);}for(let l of d.statuses??[]){let u=pc(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var ri=3,On=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function si(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new A("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=On(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(y=>({id:y.id??"",title:y.title??"",description:y.description??""}))}))}}}let c=t.filter(l=>l.name==="quick_reply");if(c.length>0&&c.length===t.length){if(c.length>ri)throw new A("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${ri} reply buttons (got ${c.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:c.map(l=>{let u=On(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let d=a&&a.name==="cta_url"?On(a.buttonParamsJson):null;if(d){let l=d;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new A("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ce=class{ev=new events.EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=Dt(e);}get apiVersion(){return this.options.apiVersion??Nt}get baseUrl(){return this.options.baseUrl??In}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new A("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new A("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new A("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new A("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=si(s);if(i===null)throw new A("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...J(e,"interactive"),interactive:i},c=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(c){let d=it(c,e,{text:""},Date.now());d.message=t,this.ev.emit("messages.upsert",{messages:[d],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...J(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new A("REQUEST_FAILED","graph interactive send returned no message id");let o=it(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...J(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new A("REQUEST_FAILED","graph template send returned no message id");let c=it(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[c],type:"append"}),c}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new A("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new A("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await me(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ni(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let c of s)this.ev.emit("cloud.status",c);for(let c of i)this.ev.emit("cloud.template-status",c);for(let c of o)this.ev.emit("cloud.flow-response",c);for(let c of a)this.ev.emit("cloud.order",c);}async sendMessage(e,t,r){let s=Qs(e,t,r);if(s===null){let c=Xs(t);if(c){let d=await ei(this.graph,this.options.phoneNumberId,c);s={...J(e,c.kind,r),[c.kind]:ti(c,d)};}}if(s===null)throw new A("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new A("REQUEST_FAILED","graph send returned no message id");let a=it(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var ot=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=Dt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new A("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new A("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var vc=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=crypto.createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:crypto.timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function xn(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!vc(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var bc="default",Ac="qr",oi=6e4,Cc=2,Pc=3e3,ai=class extends Lt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=zr();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:bn(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?Tn(e.cloud):void 0,this.sessionId=e.sessionId??bc,this.logger=bn(e.logger),this.authType=e.authType??Ac,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&jr(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new At({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new kt,this.reconnectStrategy=Hr(this.reconnectOptions),this.authGuard=Gr(e.authGuard),this.operationGuard=Mn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ie({perSec:t}):void 0,this.commandPrefixes=Ec(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new Ve(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&he.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof Mc.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=Mc.fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=Fr(e);t&&process.stderr.write(`${t}
21
- `);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new st(e)}get group(){return this.assertWebProvider("group"),this._group??=new Re(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new _e(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new Le(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Ne(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new De(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Be(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new We(()=>this._socket,e=>xe(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Fe(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new $e(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),Sn(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new Ge({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(new Error('phoneNumber is required when authType is "pairing"'));if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Ur(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qr(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:oi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a)},i=Mc__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{let d=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{d?.(),a();},this.connectReject=u=>{l?.(u),c(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??Mc.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ce(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=kn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.send(s).text(i,o).reply(a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new A("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return xn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new je).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=yn({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r)});}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.send(o).text(s,i).reply(t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return this._provider==="cloud"||xe(e)?z.create(t,e,void 0,r):z.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return this.assertWebProvider("edit"),new Oe(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await un(this.requireSocket(),e,t);}async react(e,t){return pn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new I("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new A("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ot(this.cloudOptions,()=>this.cloudTransport??=new Ce(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new A("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new A("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return mn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),Mt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),Mt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}resolveRecipient(e){return gn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new m("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new m("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=s=>{this.handleConnectionUpdate(s);},r=s=>{let i=this.creds?Object.assign(this.creds,s):s;this.creds=i,this.auth.creds.writeCreds(i).catch(o=>{this.logger.warn(o,"auth.creds.writeCreds failed");});};e.ev.on("connection.update",t),e.ev.on("creds.update",r),this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Jr({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let c=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:c.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:c.code,expiresAt:c.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vr(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+oi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=kn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.send(s).text(i,o).reply(a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Je({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ue({client:this,logger:this.logger}),this.pluginLoader=new qe({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(c=>o[r[c]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let d=o[r[a]]?.cloudMediaId;return typeof d!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(d)}return St(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=kc(e?.error),r=Kr(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<Cc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$r(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!Ye(r))&&!this.authExhausted){Ct(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:Pc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(c=>{this.logger.warn(c,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function Ec(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function kc(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var ci=class{credsBlob;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryAuthStore is closed")}};var Wt=null,Tc=async()=>{if(Wt)return Wt;try{return Wt=(await import('better-sqlite3')).default,Wt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Rn="default",li=500,ui=n=>Array.from({length:n},()=>"?").join(","),pi=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},mi=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Rn);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Rn,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Rn);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of pi(t,li)){let o=ui(i.length),c=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let d of c)r[d.id]=this.parseBlob(d.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let c=e[a];if(c)for(let d of Object.keys(c)){let l=c[d];l===null?i.push({type:a,id:d}):l!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=ui(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of pi(t,li))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await Tc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
22
- CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new h("STORE_CONNECTION_FAILED","failed to migrate sqlite schema",{cause:r})}this.db=t,this.prepared={readCreds:t.prepare("SELECT data FROM auth_creds WHERE id = ?"),writeCreds:t.prepare("INSERT INTO auth_creds(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data"),deleteCreds:t.prepare("DELETE FROM auth_creds WHERE id = ?"),writeSignal:t.prepare("INSERT INTO auth_signal(type, id, data) VALUES(?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET data = excluded.data"),deleteSignal:t.prepare("DELETE FROM auth_signal WHERE type = ? AND id = ?"),clearSignal:t.prepare("DELETE FROM auth_signal"),clearCreds:t.prepare("DELETE FROM auth_creds")};}encodeBlob(e){try{return Buffer.from(JSON.stringify(e,Mc.BufferJSON.replacer),"utf8")}catch(t){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:t})}}parseBlob(e){try{let t=Buffer.isBuffer(e)?e.toString("utf8"):Buffer.from(e).toString("utf8");return JSON.parse(t,Mc.BufferJSON.reviver)}catch(t){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var jt,Ic=async()=>(jt||(jt=import('pg').then(n=>n).catch(n=>{throw jt=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),jt),Oc="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",xc="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",gi=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","PostgresAuthStore is closed");if(this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Ic(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(Oc),await e.query(xc);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,c)=>`$${c+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let c=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(c.toString("utf8"),Mc.BufferJSON.reviver);}return s}catch(i){throw i instanceof h?i:new h("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let c=o[a];if(c===null)r.push({kind:"delete",type:String(i),id:a});else if(c!==void 0){let d=Buffer.from(JSON.stringify(c,Mc.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:d});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to write signal rows",{cause:i})}finally{s?.release();}},delete:async(e,t)=>{let r=await this.ensureReady();if(t.length!==0)try{let s=t.map((i,o)=>`$${o+2}`).join(", ");await r.query(`DELETE FROM zaileys_auth_signal WHERE type = $1 AND id IN (${s})`,[String(e),...Array.from(t)]);}catch(s){throw new h("STORE_WRITE_FAILED","failed to delete signal rows",{cause:s})}},clear:async()=>{let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_auth_signal"),await t.query("DELETE FROM zaileys_auth_creds"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to clear auth tables",{cause:r})}finally{t?.release();}},close:async()=>{if(this.closed)return;this.closed=true;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};creds={readCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'default'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,Mc.BufferJSON.reviver)}catch(t){throw t instanceof h?t:new h("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,Mc.BufferJSON.replacer);await t.query("INSERT INTO zaileys_auth_creds(id, data) VALUES ('default', $1::jsonb) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data",[r]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to write creds",{cause:r})}},deleteCreds:async()=>{let e=await this.ensureReady();try{await e.query("DELETE FROM zaileys_auth_creds WHERE id = 'default'");}catch(t){throw new h("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var Rc="zaileys",_c=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],Lc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},fi=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??Rc,this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let c=i[a];c!=null&&(o[t[a]]=JSON.parse(c,Mc.BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let c=o[a],d=this.signalKey(i,a),l=this.indexKey(i);c===null?(r.del(d),r.sRem(l,a)):c!==void 0&&(r.set(d,JSON.stringify(c,Mc.BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of _c){let s=this.indexKey(r),i=await this.runRead(()=>e.sMembers(s));for(let o of i)t.del(this.signalKey(r,o));t.del(s);}t.del(this.credsKey()),await this.runWrite(()=>t.exec());},close:async()=>{await this.shutdown();}};creds={readCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));if(t!=null)return JSON.parse(t,Mc.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,Mc.BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));}};credsKey(){return `${this.namespace}:auth:creds`}signalKey(e,t){return `${this.namespace}:auth:signal:${String(e)}:${t}`}indexKey(e){return `${this.namespace}:auth:signal-index:${String(e)}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new h("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Lc(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","redis write failed",{cause:t})}}async shutdown(){if(!this.closed){if(this.closed=true,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","RedisAuthStore is closed")}};var Nc="zaileys",at={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Dc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Pe=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??Nc,this.externalClient=e.client,this.url=e.url;}async get(e){if(this.assertOpen(),e.length===0)return new Map;let t=await this.ensureClient(),r=await this.runRead(()=>t.query(at.get,{namespace:this.namespace,keys:[...e]})),s=new Map;for(let i of r??[])s.set(i.key,i.value);return s}async set(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(at.set,{namespace:this.namespace,items:[...e]}));}async del(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(at.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(at.clear,e===void 0?{namespace:this.namespace}:{namespace:this.namespace,prefix:e}));}async list(e,t){this.assertOpen();let r=await this.ensureClient(),s={namespace:this.namespace,prefix:e};return typeof t?.before=="number"&&(s.before=t.before),typeof t?.limit=="number"&&(s.limit=t.limit),await this.runRead(()=>r.query(at.list,s))??[]}close(){this.closed=true,this.client=void 0;}async ensureClient(){if(this.externalClient)return this.externalClient;if(this.client)return this.client;let e="convex/browser",t;try{t=await import(e);}catch(r){throw Dc(r)?new h("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load convex module",{cause:r})}return this.client=new t.ConvexHttpClient(this.url),this.client}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","Convex store is closed")}};var Kt="creds",Bc="signal:",ct=(n,e)=>`${Bc}${n}:${e}`,hi=class{creds;signal;kv;constructor(e){this.kv=new Pe(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([Kt])).get(Kt);return s===void 0?void 0:JSON.parse(s,Mc.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:Kt,value:JSON.stringify(r,Mc.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([Kt]);}},this.signal={async read(r,s){let i=s.map(c=>ct(r,c)),o=await t.get(i),a={};for(let c of s){let d=o.get(ct(r,c));a[c]=d===void 0?void 0:JSON.parse(d,Mc.BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let c of Object.keys(a)){let d=a[c];d==null?i.push(ct(o,c)):s.push({key:ct(o,c),value:JSON.stringify(d,Mc.BufferJSON.replacer)});}}s.length>0&&await t.set(s),i.length>0&&await t.del(i);},async delete(r,s){await t.del(s.map(i=>ct(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var $t=null,Wc=async()=>{if($t)return $t;try{return $t=(await import('better-sqlite3')).default,$t}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Gt=n=>{try{return Buffer.from(JSON.stringify(n,Mc.BufferJSON.replacer),"utf8")}catch(e){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},le=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,Mc.BufferJSON.reviver)}catch(e){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},yi=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;constructor(e){this.options=e;}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe?1:0,o=Number(e.messageTimestamp??0);t.upsertMessage.run(r,s,i,o,Gt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?le(r.data):void 0}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=t?.before;return (typeof i=="number"?r.listMessages.all(e,i,s):r.listMessages.all(e,Number.MAX_SAFE_INTEGER,s)).map(a=>le(a.data))}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived?1:0;t.upsertChat.run(r,s,Gt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?le(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>le(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,Gt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?le(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>le(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,Gt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?le(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
20
+ END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Mc=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:Q(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Sc=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:hc(n)??yc(n)??wc(n)??vc(n);if(t===null)return null;let r=Mc(t,n),s=Wt(e,n.from);return {key:{id:n.id,remoteJid:Q(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},bc=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?Q(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},Ac=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Wt(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:Q(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},Cc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Wt(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:Q(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},Pc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=Q(n.from),s=Wt(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function oi(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let c of a.changes??[]){let d=c.value;if(d){if(c.field==="message_template_status_update"){let l=fc(d);l&&s.push(l);continue}for(let l of d.messages??[]){let u=Pc(l,d);if(u){t.push(u);continue}let w=Ac(l,d);if(w){i.push(w);continue}let M=Cc(l,d);if(M){o.push(M);continue}let v=Sc(l,d);v&&e.push(v);}for(let l of d.statuses??[]){let u=bc(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var ai=3,Rn=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function ci(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new A("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=Rn(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(w=>({id:w.id??"",title:w.title??"",description:w.description??""}))}))}}}let c=t.filter(l=>l.name==="quick_reply");if(c.length>0&&c.length===t.length){if(c.length>ai)throw new A("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${ai} reply buttons (got ${c.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:c.map(l=>{let u=Rn(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let d=a&&a.name==="cta_url"?Rn(a.buttonParamsJson):null;if(d){let l=d;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new A("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ce=class{ev=new events.EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=Bt(e);}get apiVersion(){return this.options.apiVersion??Dt}get baseUrl(){return this.options.baseUrl??On}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new A("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new A("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new A("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new A("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=ci(s);if(i===null)throw new A("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...J(e,"interactive"),interactive:i},c=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(c){let d=ot(c,e,{text:""},Date.now());d.message=t,this.ev.emit("messages.upsert",{messages:[d],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...J(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new A("REQUEST_FAILED","graph interactive send returned no message id");let o=ot(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...J(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new A("REQUEST_FAILED","graph template send returned no message id");let c=ot(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[c],type:"append"}),c}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new A("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new A("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await me(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=oi(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let c of s)this.ev.emit("cloud.status",c);for(let c of i)this.ev.emit("cloud.template-status",c);for(let c of o)this.ev.emit("cloud.flow-response",c);for(let c of a)this.ev.emit("cloud.order",c);}async sendMessage(e,t,r){let s=ni(e,t,r);if(s===null){let c=ri(t);if(c){let d=await si(this.graph,this.options.phoneNumberId,c);s={...J(e,c.kind,r),[c.kind]:ii(c,d)};}}if(s===null)throw new A("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new A("REQUEST_FAILED","graph send returned no message id");let a=ot(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var at=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=Bt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new A("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new A("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var Ic=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=crypto.createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:crypto.timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function _n(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!Ic(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var Rc="default",_c="qr",li=6e4,Lc=2,Nc=3e3,ui=class extends Nt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=Xr();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:Cn(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?xn(e.cloud):void 0,this.sessionId=e.sessionId??Rc,this.logger=Cn(e.logger),this.authType=e.authType??_c,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&$r(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ct({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Tt,this.reconnectStrategy=Qr(this.reconnectOptions),this.authGuard=zr(e.authGuard),this.operationGuard=bn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ie({perSec:t}):void 0,this.commandPrefixes=Dc(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new He(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&he.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof xc.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=xc.fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=Kr(e);t&&process.stderr.write(`${t}
21
+ `);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new it(e)}get group(){return this.assertWebProvider("group"),this._group??=new _e(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Le(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new Ne(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new De(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new Be(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new We(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new Fe(()=>this._socket,e=>Re(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new je(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new Ge(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),An(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new Je({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(new Error('phoneNumber is required when authType is "pairing"'));if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Gr(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=Jr(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:li,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=xc__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{let d=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{d?.(),a();},this.connectReject=u=>{l?.(u),c(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??xc.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ce(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=In(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.send(s).text(i,o).reply(a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new A("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return _n({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new Ue).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=vn({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r)});}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.send(o).text(s,i).reply(t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return this._provider==="cloud"||Re(e)?z.create(t,e,void 0,r):z.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return this.assertWebProvider("edit"),new Oe(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await mn(this.requireSocket(),e,t);}async react(e,t){return gn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new I("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new A("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new at(this.cloudOptions,()=>this.cloudTransport??=new Ce(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new A("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new A("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return fn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),St(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),St(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Lr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return hn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=s=>{this.handleConnectionUpdate(s);},r=s=>{let i=this.creds?Object.assign(this.creds,s):s;this.creds=i,this.auth.creds.writeCreds(i).catch(o=>{this.logger.warn(o,"auth.creds.writeCreds failed");});};e.ev.on("connection.update",t),e.ev.on("creds.update",r),this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Yr({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let c=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:c.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:c.code,expiresAt:c.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Zr(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+li});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=In(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.send(s).text(i,o).reply(a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ve({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new qe({client:this,logger:this.logger}),this.pluginLoader=new Ke({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(c=>o[r[c]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let d=o[r[a]]?.cloudMediaId;return typeof d!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(d)}return bt(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=Bc(e?.error),r=Vr(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<Lc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),Hr(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!Ze(r))&&!this.authExhausted){Pt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:Nc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(c=>{this.logger.warn(c,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function Dc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function Bc(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var pi=class{credsBlob;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryAuthStore is closed")}};var Ft=null,Wc=async()=>{if(Ft)return Ft;try{return Ft=(await import('better-sqlite3')).default,Ft}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Ln="default",gi=500,fi=n=>Array.from({length:n},()=>"?").join(","),hi=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},yi=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Ln);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Ln,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Ln);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of hi(t,gi)){let o=fi(i.length),c=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let d of c)r[d.id]=this.parseBlob(d.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let c=e[a];if(c)for(let d of Object.keys(c)){let l=c[d];l===null?i.push({type:a,id:d}):l!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=fi(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of hi(t,gi))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await Wc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
22
+ CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new h("STORE_CONNECTION_FAILED","failed to migrate sqlite schema",{cause:r})}this.db=t,this.prepared={readCreds:t.prepare("SELECT data FROM auth_creds WHERE id = ?"),writeCreds:t.prepare("INSERT INTO auth_creds(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data"),deleteCreds:t.prepare("DELETE FROM auth_creds WHERE id = ?"),writeSignal:t.prepare("INSERT INTO auth_signal(type, id, data) VALUES(?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET data = excluded.data"),deleteSignal:t.prepare("DELETE FROM auth_signal WHERE type = ? AND id = ?"),clearSignal:t.prepare("DELETE FROM auth_signal"),clearCreds:t.prepare("DELETE FROM auth_creds")};}encodeBlob(e){try{return Buffer.from(JSON.stringify(e,xc.BufferJSON.replacer),"utf8")}catch(t){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:t})}}parseBlob(e){try{let t=Buffer.isBuffer(e)?e.toString("utf8"):Buffer.from(e).toString("utf8");return JSON.parse(t,xc.BufferJSON.reviver)}catch(t){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var Ut,Fc=async()=>(Ut||(Ut=import('pg').then(n=>n).catch(n=>{throw Ut=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),Ut),jc="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",Uc="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",wi=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","PostgresAuthStore is closed");if(this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Fc(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(jc),await e.query(Uc);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,c)=>`$${c+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let c=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(c.toString("utf8"),xc.BufferJSON.reviver);}return s}catch(i){throw i instanceof h?i:new h("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let c=o[a];if(c===null)r.push({kind:"delete",type:String(i),id:a});else if(c!==void 0){let d=Buffer.from(JSON.stringify(c,xc.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:d});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to write signal rows",{cause:i})}finally{s?.release();}},delete:async(e,t)=>{let r=await this.ensureReady();if(t.length!==0)try{let s=t.map((i,o)=>`$${o+2}`).join(", ");await r.query(`DELETE FROM zaileys_auth_signal WHERE type = $1 AND id IN (${s})`,[String(e),...Array.from(t)]);}catch(s){throw new h("STORE_WRITE_FAILED","failed to delete signal rows",{cause:s})}},clear:async()=>{let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_auth_signal"),await t.query("DELETE FROM zaileys_auth_creds"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to clear auth tables",{cause:r})}finally{t?.release();}},close:async()=>{if(this.closed)return;this.closed=true;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};creds={readCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'default'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,xc.BufferJSON.reviver)}catch(t){throw t instanceof h?t:new h("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,xc.BufferJSON.replacer);await t.query("INSERT INTO zaileys_auth_creds(id, data) VALUES ('default', $1::jsonb) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data",[r]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to write creds",{cause:r})}},deleteCreds:async()=>{let e=await this.ensureReady();try{await e.query("DELETE FROM zaileys_auth_creds WHERE id = 'default'");}catch(t){throw new h("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var qc="zaileys",Kc=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],$c=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},vi=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??qc,this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let c=i[a];c!=null&&(o[t[a]]=JSON.parse(c,xc.BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let c=o[a],d=this.signalKey(i,a),l=this.indexKey(i);c===null?(r.del(d),r.sRem(l,a)):c!==void 0&&(r.set(d,JSON.stringify(c,xc.BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of Kc){let s=this.indexKey(r),i=await this.runRead(()=>e.sMembers(s));for(let o of i)t.del(this.signalKey(r,o));t.del(s);}t.del(this.credsKey()),await this.runWrite(()=>t.exec());},close:async()=>{await this.shutdown();}};creds={readCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));if(t!=null)return JSON.parse(t,xc.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,xc.BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));}};credsKey(){return `${this.namespace}:auth:creds`}signalKey(e,t){return `${this.namespace}:auth:signal:${String(e)}:${t}`}indexKey(e){return `${this.namespace}:auth:signal-index:${String(e)}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new h("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw $c(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","redis write failed",{cause:t})}}async shutdown(){if(!this.closed){if(this.closed=true,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","RedisAuthStore is closed")}};var Gc="zaileys",ct={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Jc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Pe=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??Gc,this.externalClient=e.client,this.url=e.url;}async get(e){if(this.assertOpen(),e.length===0)return new Map;let t=await this.ensureClient(),r=await this.runRead(()=>t.query(ct.get,{namespace:this.namespace,keys:[...e]})),s=new Map;for(let i of r??[])s.set(i.key,i.value);return s}async set(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(ct.set,{namespace:this.namespace,items:[...e]}));}async del(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(ct.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(ct.clear,e===void 0?{namespace:this.namespace}:{namespace:this.namespace,prefix:e}));}async list(e,t){this.assertOpen();let r=await this.ensureClient(),s={namespace:this.namespace,prefix:e};return typeof t?.before=="number"&&(s.before=t.before),typeof t?.limit=="number"&&(s.limit=t.limit),await this.runRead(()=>r.query(ct.list,s))??[]}close(){this.closed=true,this.client=void 0;}async ensureClient(){if(this.externalClient)return this.externalClient;if(this.client)return this.client;let e="convex/browser",t;try{t=await import(e);}catch(r){throw Jc(r)?new h("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load convex module",{cause:r})}return this.client=new t.ConvexHttpClient(this.url),this.client}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","Convex store is closed")}};var $t="creds",Vc="signal:",dt=(n,e)=>`${Vc}${n}:${e}`,Mi=class{creds;signal;kv;constructor(e){this.kv=new Pe(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([$t])).get($t);return s===void 0?void 0:JSON.parse(s,xc.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:$t,value:JSON.stringify(r,xc.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([$t]);}},this.signal={async read(r,s){let i=s.map(c=>dt(r,c)),o=await t.get(i),a={};for(let c of s){let d=o.get(dt(r,c));a[c]=d===void 0?void 0:JSON.parse(d,xc.BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let c of Object.keys(a)){let d=a[c];d==null?i.push(dt(o,c)):s.push({key:dt(o,c),value:JSON.stringify(d,xc.BufferJSON.replacer)});}}s.length>0&&await t.set(s),i.length>0&&await t.del(i);},async delete(r,s){await t.del(s.map(i=>dt(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var Gt=null,Hc=async()=>{if(Gt)return Gt;try{return Gt=(await import('better-sqlite3')).default,Gt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Jt=n=>{try{return Buffer.from(JSON.stringify(n,xc.BufferJSON.replacer),"utf8")}catch(e){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},le=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,xc.BufferJSON.reviver)}catch(e){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Si=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;constructor(e){this.options=e;}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe?1:0,o=Number(e.messageTimestamp??0);t.upsertMessage.run(r,s,i,o,Jt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?le(r.data):void 0}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=t?.before;return (typeof i=="number"?r.listMessages.all(e,i,s):r.listMessages.all(e,Number.MAX_SAFE_INTEGER,s)).map(a=>le(a.data))}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived?1:0;t.upsertChat.run(r,s,Jt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?le(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>le(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,Jt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?le(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>le(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,Jt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?le(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
23
23
  SELECT rowid FROM (
24
24
  SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
25
25
  FROM messages ${o}
26
26
  ) WHERE rn > ?
27
- )`);s+=a.run(...i??[],e.maxPerChat).changes;}return s}bind(e){if(this.closed)throw new h("STORE_CLOSED","SqliteMessageStore is closed");this.boundSocket=e;let t=(...o)=>{let c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){let e=await this.ensureReady();this.db.transaction(()=>{e.clearMessages.run(),e.clearChats.run(),e.clearContacts.run(),e.clearPresence.run();})();}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);this.listeners.clear(),this.boundSocket=void 0;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteMessageStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await Wc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS messages (
27
+ )`);s+=a.run(...i??[],e.maxPerChat).changes;}return s}bind(e){if(this.closed)throw new h("STORE_CLOSED","SqliteMessageStore is closed");this.boundSocket=e;let t=(...o)=>{let c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){let e=await this.ensureReady();this.db.transaction(()=>{e.clearMessages.run(),e.clearChats.run(),e.clearContacts.run(),e.clearPresence.run();})();}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);this.listeners.clear(),this.boundSocket=void 0;try{this.db?.close();}catch(e){throw new h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}async ensureReady(){if(this.closed)throw new h("STORE_CLOSED","SqliteMessageStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await Hc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS messages (
28
28
  remote_jid TEXT NOT NULL,
29
29
  id TEXT NOT NULL,
30
30
  from_me INTEGER NOT NULL,
@@ -39,4 +39,4 @@ END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsAr
39
39
  ON CONFLICT(remote_jid, id, from_me) DO UPDATE SET timestamp = excluded.timestamp, data = excluded.data`),getMessage:t.prepare("SELECT data FROM messages WHERE remote_jid = ? AND id = ? AND from_me = ?"),listMessages:t.prepare("SELECT data FROM messages WHERE remote_jid = ? AND timestamp < ? ORDER BY timestamp DESC LIMIT ?"),upsertChat:t.prepare(`INSERT INTO chats(jid, archived, data) VALUES(?, ?, ?)
40
40
  ON CONFLICT(jid) DO UPDATE SET archived = excluded.archived, data = excluded.data`),getChat:t.prepare("SELECT data FROM chats WHERE jid = ?"),listChats:t.prepare("SELECT data FROM chats"),listChatsArchived:t.prepare("SELECT data FROM chats WHERE archived = 1"),upsertContact:t.prepare(`INSERT INTO contacts(jid, data) VALUES(?, ?)
41
41
  ON CONFLICT(jid) DO UPDATE SET data = excluded.data`),getContact:t.prepare("SELECT data FROM contacts WHERE jid = ?"),listContacts:t.prepare("SELECT data FROM contacts"),upsertPresence:t.prepare(`INSERT INTO presence(jid, data) VALUES(?, ?)
42
- ON CONFLICT(jid) DO UPDATE SET data = excluded.data`),getPresence:t.prepare("SELECT data FROM presence WHERE jid = ?"),clearMessages:t.prepare("DELETE FROM messages"),clearChats:t.prepare("DELETE FROM chats"),clearContacts:t.prepare("DELETE FROM contacts"),clearPresence:t.prepare("DELETE FROM presence"),deleteMessage:t.prepare("DELETE FROM messages WHERE remote_jid = ? AND id = ? AND from_me = ?"),pruneByAge:t.prepare("DELETE FROM messages WHERE timestamp < ?"),pruneByAgeChat:t.prepare("DELETE FROM messages WHERE timestamp < ? AND remote_jid = ?")};}};var Jt,Fc=async()=>(Jt||(Jt=import('pg').then(n=>n).catch(n=>{throw Jt=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),Jt),jc=["CREATE TABLE IF NOT EXISTS zaileys_messages (remote_jid text NOT NULL, id text NOT NULL, from_me boolean NOT NULL, timestamp bigint NOT NULL, data jsonb NOT NULL, PRIMARY KEY(remote_jid, id, from_me))","CREATE INDEX IF NOT EXISTS zaileys_messages_jid_ts_idx ON zaileys_messages(remote_jid, timestamp DESC)","CREATE TABLE IF NOT EXISTS zaileys_chats (jid text PRIMARY KEY, archived boolean NOT NULL DEFAULT false, data jsonb NOT NULL)","CREATE INDEX IF NOT EXISTS zaileys_chats_archived_idx ON zaileys_chats(archived) WHERE archived = true","CREATE TABLE IF NOT EXISTS zaileys_contacts (jid text PRIMARY KEY, data jsonb NOT NULL)","CREATE TABLE IF NOT EXISTS zaileys_presence (jid text PRIMARY KEY, data jsonb NOT NULL, updated_at timestamptz NOT NULL DEFAULT now())"],ue=n=>{if(n==null)return n;let e=typeof n=="string"?n:JSON.stringify(n);return JSON.parse(e,Mc.BufferJSON.reviver)},vi=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;boundSocket;listeners=new Map;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new h("STORE_CONNECTION_FAILED","PostgresMessageStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("STORE_CONNECTION_FAILED","PostgresMessageStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","PostgresMessageStore is closed")}async ensureReady(){if(this.assertOpen(),this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Fc(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{for(let t of jc)await e.query(t);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate message schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe===true,o=Number(e.messageTimestamp??0);try{await t.query("INSERT INTO zaileys_messages(remote_jid, id, from_me, timestamp, data) VALUES ($1, $2, $3, $4, $5::jsonb) ON CONFLICT (remote_jid, id, from_me) DO UPDATE SET data = EXCLUDED.data, timestamp = EXCLUDED.timestamp",[r,s,i,o,JSON.stringify(e,Mc.BufferJSON.replacer)]);}catch(a){throw new h("STORE_WRITE_FAILED","failed to save message",{cause:a})}}async getMessage(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0])).rows[0];return s?ue(s.data):void 0}catch(r){throw r instanceof h?r:new h("STORE_READ_FAILED","failed to read message",{cause:r})}}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?t.before:null;try{return (await r.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND ($2::bigint IS NULL OR timestamp < $2::bigint) ORDER BY timestamp DESC LIMIT $3",[e,i,s])).rows.map(a=>ue(a.data))}catch(o){throw new h("STORE_READ_FAILED","failed to list messages",{cause:o})}}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived===true;try{await t.query("INSERT INTO zaileys_chats(jid, archived, data) VALUES ($1, $2, $3::jsonb) ON CONFLICT (jid) DO UPDATE SET archived = EXCLUDED.archived, data = EXCLUDED.data",[r,s,JSON.stringify(e,Mc.BufferJSON.replacer)]);}catch(i){throw new h("STORE_WRITE_FAILED","failed to save chat",{cause:i})}}async getChat(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_chats WHERE jid = $1",[e])).rows[0];return s?ue(s.data):void 0}catch(r){throw new h("STORE_READ_FAILED","failed to read chat",{cause:r})}}async listChats(e){let t=await this.ensureReady(),r=typeof e?.archived=="boolean"?e.archived:null;try{return (await t.query("SELECT data FROM zaileys_chats WHERE ($1::boolean IS NULL OR archived = $1::boolean)",[r])).rows.map(i=>ue(i.data))}catch(s){throw new h("STORE_READ_FAILED","failed to list chats",{cause:s})}}async saveContact(e){let t=await this.ensureReady();try{await t.query("INSERT INTO zaileys_contacts(jid, data) VALUES ($1, $2::jsonb) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data",[e.id,JSON.stringify(e,Mc.BufferJSON.replacer)]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to save contact",{cause:r})}}async getContact(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_contacts WHERE jid = $1",[e])).rows[0];return s?ue(s.data):void 0}catch(r){throw new h("STORE_READ_FAILED","failed to read contact",{cause:r})}}async listContacts(){let e=await this.ensureReady();try{return (await e.query("SELECT data FROM zaileys_contacts")).rows.map(r=>ue(r.data))}catch(t){throw new h("STORE_READ_FAILED","failed to list contacts",{cause:t})}}async savePresence(e,t){let r=await this.ensureReady();try{await r.query("INSERT INTO zaileys_presence(jid, data, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data, updated_at = now()",[e,JSON.stringify(t,Mc.BufferJSON.replacer)]);}catch(s){throw new h("STORE_WRITE_FAILED","failed to save presence",{cause:s})}}async getPresence(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_presence WHERE jid = $1",[e])).rows[0];return s?ue(s.data):void 0}catch(r){throw new h("STORE_READ_FAILED","failed to read presence",{cause:r})}}async deleteMessage(e){let t=await this.ensureReady();try{await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to delete message",{cause:r})}}async pruneMessages(e){let t=await this.ensureReady();try{let r=0,s;if(e.chatFilter&&(s=(await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[])).rows.map(o=>o.remote_jid).filter(o=>e.chatFilter(o))),e.olderThan!==void 0){let i=s?await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1 AND remote_jid = ANY($2::text[])",[e.olderThan,s]):await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1",[e.olderThan]);r+=i.rowCount??0;}if(e.maxPerChat!==void 0){let i=s??await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[]).then(o=>o.rows.map(a=>a.remote_jid));for(let o of i){let c=(await t.query("SELECT id, from_me FROM zaileys_messages WHERE remote_jid = $1 ORDER BY timestamp DESC",[o])).rows.slice(e.maxPerChat);if(c.length!==0)for(let d of c){let l=await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[o,d.id,d.from_me]);r+=l.rowCount??0;}}}return r}catch(r){throw new h("STORE_WRITE_FAILED","failed to prune messages",{cause:r})}}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.getMessage(l.key).then(u=>{if(!u)return;let y={...u,...l.update};return this.saveMessage(y)}).catch(()=>{});},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.getChat(l.id).then(u=>{let y={...u??{},...l};return this.saveChat(y)}).catch(()=>{});},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async clear(){let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_messages"),await t.query("DELETE FROM zaileys_chats"),await t.query("DELETE FROM zaileys_contacts"),await t.query("DELETE FROM zaileys_presence"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to clear message tables",{cause:r})}finally{t?.release();}}async close(){if(this.closed)return;if(this.closed=true,this.boundSocket?.ev.off)for(let[t,r]of this.listeners)this.boundSocket.ev.off(t,r);this.listeners.clear(),this.boundSocket=void 0;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};var Uc="zaileys",qc=300,Mi=1e3,_n=n=>`${n.id??""}|${n.fromMe?1:0}`,Kc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Si=class{namespace;externalClient;url;ownedClient;ready;closed=false;boundSocket;listeners=new Map;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisMessageStore requires either client or url");this.namespace=e.namespace??Uc,this.externalClient=e.client,this.url=e.url;}async saveMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.key.remoteJid??"",s=_n(e.key),i=Number(e.messageTimestamp??0),o=JSON.stringify(e,Mc.BufferJSON.replacer),a=t.multi();a.zAdd(this.msgIndexKey(r),{score:i,value:s}),a.hSet(this.msgDataKey(r),s,o),await this.runWrite(()=>a.exec());}async getMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=await this.runRead(()=>t.hGet(this.msgDataKey(r),_n(e)));if(s!=null)return JSON.parse(s,Mc.BufferJSON.reviver)}async listMessages(e,t){this.assertOpen();let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?`(${t.before}`:"+inf",o=await this.runRead(()=>r.zRangeByScore(this.msgIndexKey(e),"-inf",i,{LIMIT:{offset:0,count:s+1024}}));if(o.length===0)return [];let c=[...o].reverse().slice(0,s),d=await this.runRead(()=>r.hmGet(this.msgDataKey(e),c)),l=[];for(let u of d)u!=null&&l.push(JSON.parse(u,Mc.BufferJSON.reviver));return l}async saveChat(e){this.assertOpen();let t=e.id;if(!t)return;let s=(await this.ensureReady()).multi();s.hSet(this.chatsKey(),t,JSON.stringify(e,Mc.BufferJSON.replacer)),e.archived===true?s.sAdd(this.chatsArchiveKey(),t):s.sRem(this.chatsArchiveKey(),t),await this.runWrite(()=>s.exec());}async getChat(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.chatsKey(),e));if(r!=null)return JSON.parse(r,Mc.BufferJSON.reviver)}async listChats(e){this.assertOpen();let t=await this.ensureReady();if(e?.archived===true){let i=await this.runRead(()=>t.sMembers(this.chatsArchiveKey()));if(i.length===0)return [];let o=await this.runRead(()=>t.hmGet(this.chatsKey(),i)),a=[];for(let c of o)c!=null&&a.push(JSON.parse(c,Mc.BufferJSON.reviver));return a}let r=await this.runRead(()=>t.hGetAll(this.chatsKey())),s=[];for(let i of Object.keys(r)){let o=r[i];if(o==null)continue;let a=JSON.parse(o,Mc.BufferJSON.reviver);e?.archived===false&&await this.runRead(()=>t.sIsMember(this.chatsArchiveKey(),i))||s.push(a);}return s}async saveContact(e){this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.hSet(this.contactsKey(),e.id,JSON.stringify(e,Mc.BufferJSON.replacer)));}async getContact(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.contactsKey(),e));if(r!=null)return JSON.parse(r,Mc.BufferJSON.reviver)}async listContacts(){this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.hGetAll(this.contactsKey())),r=[];for(let s of Object.keys(t)){let i=t[s];i!=null&&r.push(JSON.parse(i,Mc.BufferJSON.reviver));}return r}async savePresence(e,t){this.assertOpen();let r=await this.ensureReady();await this.runWrite(()=>r.set(this.presenceKey(e),JSON.stringify(t,Mc.BufferJSON.replacer),{EX:qc}));}async getPresence(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.get(this.presenceKey(e)));if(r!=null)return JSON.parse(r,Mc.BufferJSON.reviver)}bind(e){if(this.assertOpen(),this.boundSocket&&this.boundSocket.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen();let e=await this.ensureReady(),t=`${this.namespace}:*`,r=0;do{let s=await this.runRead(()=>e.scan(r,{MATCH:t,COUNT:Mi}));r=Number(s.cursor),s.keys.length>0&&await this.runWrite(()=>e.del(s.keys));}while(r!==0)}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);if(this.listeners.clear(),this.boundSocket=void 0,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}async deleteMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=_n(e),i=t.multi();i.zRem(this.msgIndexKey(r),s),i.hDel(this.msgDataKey(r),s),await this.runWrite(()=>i.exec());}async pruneMessages(e){this.assertOpen();let t=await this.ensureReady(),r=0,s=[],i=this.msgIndexKey("*"),o=0,a=this.msgDataKey("");do{let c=await this.runRead(()=>t.scan(o,{MATCH:i,COUNT:Mi}));o=Number(c.cursor);for(let d of c.keys)d.startsWith(a)||s.push(d);}while(o!==0);for(let c of s){let d=this.jidFromIndexKey(c);if(e.chatFilter&&!e.chatFilter(d))continue;let l=this.msgDataKey(d),u=new Set;if(e.olderThan!==void 0){let v=await this.runRead(()=>t.zRangeByScore(c,"-inf",`(${e.olderThan}`));for(let P of v)u.add(P);}if(e.maxPerChat!==void 0){let v=e.maxPerChat,P=await this.runRead(()=>t.zRange(c,0,-(v+1)));for(let w of P)u.add(w);}if(u.size===0)continue;let y=[...u],M=t.multi();M.zRem(c,y),M.hDel(l,y),await this.runWrite(()=>M.exec()),r+=y.length;}return r}jidFromIndexKey(e){let t=this.msgIndexKey("");return e.startsWith(t)?e.slice(t.length):e}msgIndexKey(e){return `${this.namespace}:msg:${e}`}msgDataKey(e){return `${this.namespace}:msg-data:${e}`}chatsKey(){return `${this.namespace}:chats`}chatsArchiveKey(){return `${this.namespace}:chats-archived`}contactsKey(){return `${this.namespace}:contacts`}presenceKey(e){return `${this.namespace}:presence:${e}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new h("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Kc(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","redis write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","RedisMessageStore is closed")}};var Yt="msg:",Vt="chat:",Ht="contact:",Ln="presence:",Nn="job:",$c=n=>`${n.id??""}|${n.fromMe?1:0}`,zt=n=>`${Yt}${n.remoteJid??""}:${$c(n)}`,lt=n=>JSON.stringify(n,Mc.BufferJSON.replacer),X=n=>JSON.parse(n,Mc.BufferJSON.reviver),bi=class{kv;closed=false;boundSocket;listeners=new Map;constructor(e){this.kv=new Pe(e);}async saveMessage(e){this.assertOpen(),await this.kv.set([{key:zt(e.key),value:lt(e),sortKey:Number(e.messageTimestamp??0)}]);}async getMessage(e){this.assertOpen();let r=(await this.kv.get([zt(e)])).get(zt(e));return r===void 0?void 0:X(r)}async listMessages(e,t){this.assertOpen();let r={};return typeof t?.before=="number"&&(r.before=t.before),typeof t?.limit=="number"&&(r.limit=t.limit),(await this.kv.list(`${Yt}${e}:`,r)).map(i=>X(i.value))}async saveChat(e){this.assertOpen();let t=e.id;t&&await this.kv.set([{key:`${Vt}${t}`,value:lt(e)}]);}async getChat(e){this.assertOpen();let r=(await this.kv.get([`${Vt}${e}`])).get(`${Vt}${e}`);return r===void 0?void 0:X(r)}async listChats(e){this.assertOpen();let t=await this.kv.list(Vt),r=[];for(let s of t){let i=X(s.value),o=i.archived===true;e?.archived===true&&!o||e?.archived===false&&o||r.push(i);}return r}async saveContact(e){this.assertOpen(),await this.kv.set([{key:`${Ht}${e.id}`,value:lt(e)}]);}async getContact(e){this.assertOpen();let r=(await this.kv.get([`${Ht}${e}`])).get(`${Ht}${e}`);return r===void 0?void 0:X(r)}async listContacts(){return this.assertOpen(),(await this.kv.list(Ht)).map(t=>X(t.value))}async savePresence(e,t){this.assertOpen(),await this.kv.set([{key:`${Ln}${e}`,value:lt(t)}]);}async getPresence(e){this.assertOpen();let r=(await this.kv.get([`${Ln}${e}`])).get(`${Ln}${e}`);return r===void 0?void 0:X(r)}async saveScheduledJob(e){this.assertOpen(),await this.kv.set([{key:`${Nn}${e.id}`,value:lt(e),sortKey:e.fireAt}]);}async listScheduledJobs(){return this.assertOpen(),(await this.kv.list(Nn)).map(t=>X(t.value))}async deleteScheduledJob(e){this.assertOpen(),await this.kv.del([`${Nn}${e}`]);}async deleteMessage(e){this.assertOpen(),await this.kv.del([zt(e)]);}async pruneMessages(e){this.assertOpen();let t=await this.kv.list(Yt,{}),r=new Map;for(let i of t){let o=i.key.slice(Yt.length),a=o.slice(0,o.indexOf(":"));if(e.chatFilter&&!e.chatFilter(a))continue;let c=r.get(a)??[];c.push({key:i.key,ts:i.sortKey??0}),r.set(a,c);}let s=[];for(let i of r.values()){i.sort((o,a)=>a.ts-o.ts);for(let o=0;o<i.length;o++){let a=i[o];(e.olderThan!==void 0&&a.ts<e.olderThan||e.maxPerChat!==void 0&&o>=e.maxPerChat)&&s.push(a.key);}}return s.length>0&&await this.kv.del(s),s.length}bind(e){if(this.assertOpen(),this.boundSocket?.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let a=o[0]?.messages;if(Array.isArray(a))for(let c of a)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen(),await this.kv.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);this.listeners.clear(),this.boundSocket=void 0,this.kv.close();}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","ConvexMessageStore is closed")}};var Gc=(n,e)=>{if(e<=0)throw new RangeError("chunk size must be positive");let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t};var _h=n=>{let t=(n.split("@")[0]??"").split(":")[0]?.replace(/\D/g,"")??"";return n.endsWith("@s.whatsapp.net")||n.endsWith("@c.us")?t:""},Lh=n=>`${n.replace(/\D/g,"")}@s.whatsapp.net`;Object.defineProperty(exports,"areJidsSameUser",{enumerable:true,get:function(){return Mc.areJidsSameUser}});Object.defineProperty(exports,"getDevice",{enumerable:true,get:function(){return Mc.getDevice}});Object.defineProperty(exports,"isJidBroadcast",{enumerable:true,get:function(){return Mc.isJidBroadcast}});Object.defineProperty(exports,"isJidGroup",{enumerable:true,get:function(){return Mc.isJidGroup}});Object.defineProperty(exports,"isJidNewsletter",{enumerable:true,get:function(){return Mc.isJidNewsletter}});Object.defineProperty(exports,"isLidUser",{enumerable:true,get:function(){return Mc.isLidUser}});Object.defineProperty(exports,"isPnUser",{enumerable:true,get:function(){return Mc.isPnUser}});Object.defineProperty(exports,"jidDecode",{enumerable:true,get:function(){return Mc.jidDecode}});Object.defineProperty(exports,"jidEncode",{enumerable:true,get:function(){return Mc.jidEncode}});Object.defineProperty(exports,"jidNormalizedUser",{enumerable:true,get:function(){return Mc.jidNormalizedUser}});exports.AudioProcessor=ne;exports.AutoDeleteSweeper=Je;exports.AutoRejectCallModule=Ve;exports.BufferConverter=k;exports.BusinessModule=Fe;exports.ChatModule=Be;exports.Client=ai;exports.CloudModule=ot;exports.CloudTransport=Ce;exports.CommandRegistry=je;exports.CommunityModule=Ne;exports.ContactModule=We;exports.ConvexAuthStore=hi;exports.ConvexMessageStore=bi;exports.DEFAULT_GRAPH_VERSION=Nt;exports.DocumentProcessor=gt;exports.EditBuilder=Oe;exports.FFMPEG_CONSTANTS=C;exports.FFmpegProcessor=ee;exports.FileAuthStore=At;exports.FileManager=V;exports.GroupModule=Re;exports.ImageProcessor=F;exports.Media=re;exports.MemoryAuthStore=ci;exports.MemoryMessageStore=kt;exports.MessageBuilder=z;exports.MimeValidator=L;exports.NewsletterModule=Le;exports.PostgresAuthStore=gi;exports.PostgresMessageStore=vi;exports.PresenceModule=$e;exports.PrivacyModule=_e;exports.ProfileModule=De;exports.RateLimiter=ie;exports.RedisAuthStore=fi;exports.RedisMessageStore=Si;exports.SELF_ONLY_PROTOCOL_TYPES=jm;exports.Scheduler=Ge;exports.SqliteAuthStore=mi;exports.SqliteMessageStore=yi;exports.StickerProcessor=he;exports.TaskQueue=Ke;exports.TypedEventEmitter=Lt;exports.VideoProcessor=q;exports.ZaileysAutomationError=I;exports.ZaileysBuilderError=m;exports.ZaileysCloudError=A;exports.ZaileysCommandError=_;exports.ZaileysDomainError=T;exports.ZaileysProviderError=st;exports.ZaileysStoreError=h;exports.adoptLogger=bn;exports.attachCommandDispatcher=yn;exports.buildMessageContext=Pn;exports.chunk=Gc;exports.computeStaticId=As;exports.computeUniqueId=bs;exports.createAuthGuard=Gr;exports.createConnectionStateMachine=zr;exports.createLogger=aa;exports.createOperationGuard=Mn;exports.createPairingFlow=Jr;exports.createReconnectStrategy=Hr;exports.createWebhookHandler=xn;exports.definePlugin=Rr;exports.deleteMessage=un;exports.detectFileType=N;exports.detectMimeFromBuffer=me;exports.dropSpoofedSelfOnly=Zr;exports.epochSecondsToMs=Cs;exports.extractLinks=Ms;exports.ffmpegTransform=U;exports.forwardMessage=mn;exports.generateId=ut;exports.genericPrune=Nr;exports.initializeFFmpeg=tn;exports.isFatalDisconnect=Ye;exports.isJid=xe;exports.isLidJid=Tt;exports.isPnJid=os;exports.isRateLimited=Ct;exports.jidToPhone=_h;exports.loadMedia=x;exports.makeCacheableAuthStore=Ur;exports.mapDisconnectReason=Kr;exports.normalizeJid=Me;exports.normalizePhoneNumber=Xo;exports.parseCommand=fn;exports.phoneToJid=Lh;exports.pinMessage=Mt;exports.printQrToTerminal=Vr;exports.reactToMessage=pn;exports.renderQrInTerminal=na;exports.resolveUsername=gn;exports.runBroadcast=Sn;exports.runMiddleware=hn;exports.senderDeviceOf=Ps;exports.shouldClearAuth=$r;exports.shouldReconnect=km;exports.signalKeyStoreFromAuthStore=qr;exports.validateCloudOptions=Tn;exports.validateE164=ea;
42
+ ON CONFLICT(jid) DO UPDATE SET data = excluded.data`),getPresence:t.prepare("SELECT data FROM presence WHERE jid = ?"),clearMessages:t.prepare("DELETE FROM messages"),clearChats:t.prepare("DELETE FROM chats"),clearContacts:t.prepare("DELETE FROM contacts"),clearPresence:t.prepare("DELETE FROM presence"),deleteMessage:t.prepare("DELETE FROM messages WHERE remote_jid = ? AND id = ? AND from_me = ?"),pruneByAge:t.prepare("DELETE FROM messages WHERE timestamp < ?"),pruneByAgeChat:t.prepare("DELETE FROM messages WHERE timestamp < ? AND remote_jid = ?")};}};var Vt,zc=async()=>(Vt||(Vt=import('pg').then(n=>n).catch(n=>{throw Vt=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),Vt),Yc=["CREATE TABLE IF NOT EXISTS zaileys_messages (remote_jid text NOT NULL, id text NOT NULL, from_me boolean NOT NULL, timestamp bigint NOT NULL, data jsonb NOT NULL, PRIMARY KEY(remote_jid, id, from_me))","CREATE INDEX IF NOT EXISTS zaileys_messages_jid_ts_idx ON zaileys_messages(remote_jid, timestamp DESC)","CREATE TABLE IF NOT EXISTS zaileys_chats (jid text PRIMARY KEY, archived boolean NOT NULL DEFAULT false, data jsonb NOT NULL)","CREATE INDEX IF NOT EXISTS zaileys_chats_archived_idx ON zaileys_chats(archived) WHERE archived = true","CREATE TABLE IF NOT EXISTS zaileys_contacts (jid text PRIMARY KEY, data jsonb NOT NULL)","CREATE TABLE IF NOT EXISTS zaileys_presence (jid text PRIMARY KEY, data jsonb NOT NULL, updated_at timestamptz NOT NULL DEFAULT now())"],ue=n=>{if(n==null)return n;let e=typeof n=="string"?n:JSON.stringify(n);return JSON.parse(e,xc.BufferJSON.reviver)},Ai=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;boundSocket;listeners=new Map;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new h("STORE_CONNECTION_FAILED","PostgresMessageStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("STORE_CONNECTION_FAILED","PostgresMessageStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","PostgresMessageStore is closed")}async ensureReady(){if(this.assertOpen(),this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await zc(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{for(let t of Yc)await e.query(t);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate message schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe===true,o=Number(e.messageTimestamp??0);try{await t.query("INSERT INTO zaileys_messages(remote_jid, id, from_me, timestamp, data) VALUES ($1, $2, $3, $4, $5::jsonb) ON CONFLICT (remote_jid, id, from_me) DO UPDATE SET data = EXCLUDED.data, timestamp = EXCLUDED.timestamp",[r,s,i,o,JSON.stringify(e,xc.BufferJSON.replacer)]);}catch(a){throw new h("STORE_WRITE_FAILED","failed to save message",{cause:a})}}async getMessage(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0])).rows[0];return s?ue(s.data):void 0}catch(r){throw r instanceof h?r:new h("STORE_READ_FAILED","failed to read message",{cause:r})}}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?t.before:null;try{return (await r.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND ($2::bigint IS NULL OR timestamp < $2::bigint) ORDER BY timestamp DESC LIMIT $3",[e,i,s])).rows.map(a=>ue(a.data))}catch(o){throw new h("STORE_READ_FAILED","failed to list messages",{cause:o})}}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived===true;try{await t.query("INSERT INTO zaileys_chats(jid, archived, data) VALUES ($1, $2, $3::jsonb) ON CONFLICT (jid) DO UPDATE SET archived = EXCLUDED.archived, data = EXCLUDED.data",[r,s,JSON.stringify(e,xc.BufferJSON.replacer)]);}catch(i){throw new h("STORE_WRITE_FAILED","failed to save chat",{cause:i})}}async getChat(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_chats WHERE jid = $1",[e])).rows[0];return s?ue(s.data):void 0}catch(r){throw new h("STORE_READ_FAILED","failed to read chat",{cause:r})}}async listChats(e){let t=await this.ensureReady(),r=typeof e?.archived=="boolean"?e.archived:null;try{return (await t.query("SELECT data FROM zaileys_chats WHERE ($1::boolean IS NULL OR archived = $1::boolean)",[r])).rows.map(i=>ue(i.data))}catch(s){throw new h("STORE_READ_FAILED","failed to list chats",{cause:s})}}async saveContact(e){let t=await this.ensureReady();try{await t.query("INSERT INTO zaileys_contacts(jid, data) VALUES ($1, $2::jsonb) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data",[e.id,JSON.stringify(e,xc.BufferJSON.replacer)]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to save contact",{cause:r})}}async getContact(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_contacts WHERE jid = $1",[e])).rows[0];return s?ue(s.data):void 0}catch(r){throw new h("STORE_READ_FAILED","failed to read contact",{cause:r})}}async listContacts(){let e=await this.ensureReady();try{return (await e.query("SELECT data FROM zaileys_contacts")).rows.map(r=>ue(r.data))}catch(t){throw new h("STORE_READ_FAILED","failed to list contacts",{cause:t})}}async savePresence(e,t){let r=await this.ensureReady();try{await r.query("INSERT INTO zaileys_presence(jid, data, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data, updated_at = now()",[e,JSON.stringify(t,xc.BufferJSON.replacer)]);}catch(s){throw new h("STORE_WRITE_FAILED","failed to save presence",{cause:s})}}async getPresence(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_presence WHERE jid = $1",[e])).rows[0];return s?ue(s.data):void 0}catch(r){throw new h("STORE_READ_FAILED","failed to read presence",{cause:r})}}async deleteMessage(e){let t=await this.ensureReady();try{await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0]);}catch(r){throw new h("STORE_WRITE_FAILED","failed to delete message",{cause:r})}}async pruneMessages(e){let t=await this.ensureReady();try{let r=0,s;if(e.chatFilter&&(s=(await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[])).rows.map(o=>o.remote_jid).filter(o=>e.chatFilter(o))),e.olderThan!==void 0){let i=s?await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1 AND remote_jid = ANY($2::text[])",[e.olderThan,s]):await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1",[e.olderThan]);r+=i.rowCount??0;}if(e.maxPerChat!==void 0){let i=s??await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[]).then(o=>o.rows.map(a=>a.remote_jid));for(let o of i){let c=(await t.query("SELECT id, from_me FROM zaileys_messages WHERE remote_jid = $1 ORDER BY timestamp DESC",[o])).rows.slice(e.maxPerChat);if(c.length!==0)for(let d of c){let l=await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[o,d.id,d.from_me]);r+=l.rowCount??0;}}}return r}catch(r){throw new h("STORE_WRITE_FAILED","failed to prune messages",{cause:r})}}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.getMessage(l.key).then(u=>{if(!u)return;let w={...u,...l.update};return this.saveMessage(w)}).catch(()=>{});},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.getChat(l.id).then(u=>{let w={...u??{},...l};return this.saveChat(w)}).catch(()=>{});},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async clear(){let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_messages"),await t.query("DELETE FROM zaileys_chats"),await t.query("DELETE FROM zaileys_contacts"),await t.query("DELETE FROM zaileys_presence"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new h("STORE_WRITE_FAILED","failed to clear message tables",{cause:r})}finally{t?.release();}}async close(){if(this.closed)return;if(this.closed=true,this.boundSocket?.ev.off)for(let[t,r]of this.listeners)this.boundSocket.ev.off(t,r);this.listeners.clear(),this.boundSocket=void 0;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};var Zc="zaileys",Qc=300,Ci=1e3,Nn=n=>`${n.id??""}|${n.fromMe?1:0}`,Xc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Pi=class{namespace;externalClient;url;ownedClient;ready;closed=false;boundSocket;listeners=new Map;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisMessageStore requires either client or url");this.namespace=e.namespace??Zc,this.externalClient=e.client,this.url=e.url;}async saveMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.key.remoteJid??"",s=Nn(e.key),i=Number(e.messageTimestamp??0),o=JSON.stringify(e,xc.BufferJSON.replacer),a=t.multi();a.zAdd(this.msgIndexKey(r),{score:i,value:s}),a.hSet(this.msgDataKey(r),s,o),await this.runWrite(()=>a.exec());}async getMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=await this.runRead(()=>t.hGet(this.msgDataKey(r),Nn(e)));if(s!=null)return JSON.parse(s,xc.BufferJSON.reviver)}async listMessages(e,t){this.assertOpen();let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?`(${t.before}`:"+inf",o=await this.runRead(()=>r.zRangeByScore(this.msgIndexKey(e),"-inf",i,{LIMIT:{offset:0,count:s+1024}}));if(o.length===0)return [];let c=[...o].reverse().slice(0,s),d=await this.runRead(()=>r.hmGet(this.msgDataKey(e),c)),l=[];for(let u of d)u!=null&&l.push(JSON.parse(u,xc.BufferJSON.reviver));return l}async saveChat(e){this.assertOpen();let t=e.id;if(!t)return;let s=(await this.ensureReady()).multi();s.hSet(this.chatsKey(),t,JSON.stringify(e,xc.BufferJSON.replacer)),e.archived===true?s.sAdd(this.chatsArchiveKey(),t):s.sRem(this.chatsArchiveKey(),t),await this.runWrite(()=>s.exec());}async getChat(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.chatsKey(),e));if(r!=null)return JSON.parse(r,xc.BufferJSON.reviver)}async listChats(e){this.assertOpen();let t=await this.ensureReady();if(e?.archived===true){let i=await this.runRead(()=>t.sMembers(this.chatsArchiveKey()));if(i.length===0)return [];let o=await this.runRead(()=>t.hmGet(this.chatsKey(),i)),a=[];for(let c of o)c!=null&&a.push(JSON.parse(c,xc.BufferJSON.reviver));return a}let r=await this.runRead(()=>t.hGetAll(this.chatsKey())),s=[];for(let i of Object.keys(r)){let o=r[i];if(o==null)continue;let a=JSON.parse(o,xc.BufferJSON.reviver);e?.archived===false&&await this.runRead(()=>t.sIsMember(this.chatsArchiveKey(),i))||s.push(a);}return s}async saveContact(e){this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.hSet(this.contactsKey(),e.id,JSON.stringify(e,xc.BufferJSON.replacer)));}async getContact(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.contactsKey(),e));if(r!=null)return JSON.parse(r,xc.BufferJSON.reviver)}async listContacts(){this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.hGetAll(this.contactsKey())),r=[];for(let s of Object.keys(t)){let i=t[s];i!=null&&r.push(JSON.parse(i,xc.BufferJSON.reviver));}return r}async savePresence(e,t){this.assertOpen();let r=await this.ensureReady();await this.runWrite(()=>r.set(this.presenceKey(e),JSON.stringify(t,xc.BufferJSON.replacer),{EX:Qc}));}async getPresence(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.get(this.presenceKey(e)));if(r!=null)return JSON.parse(r,xc.BufferJSON.reviver)}bind(e){if(this.assertOpen(),this.boundSocket&&this.boundSocket.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen();let e=await this.ensureReady(),t=`${this.namespace}:*`,r=0;do{let s=await this.runRead(()=>e.scan(r,{MATCH:t,COUNT:Ci}));r=Number(s.cursor),s.keys.length>0&&await this.runWrite(()=>e.del(s.keys));}while(r!==0)}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);if(this.listeners.clear(),this.boundSocket=void 0,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}async deleteMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=Nn(e),i=t.multi();i.zRem(this.msgIndexKey(r),s),i.hDel(this.msgDataKey(r),s),await this.runWrite(()=>i.exec());}async pruneMessages(e){this.assertOpen();let t=await this.ensureReady(),r=0,s=[],i=this.msgIndexKey("*"),o=0,a=this.msgDataKey("");do{let c=await this.runRead(()=>t.scan(o,{MATCH:i,COUNT:Ci}));o=Number(c.cursor);for(let d of c.keys)d.startsWith(a)||s.push(d);}while(o!==0);for(let c of s){let d=this.jidFromIndexKey(c);if(e.chatFilter&&!e.chatFilter(d))continue;let l=this.msgDataKey(d),u=new Set;if(e.olderThan!==void 0){let v=await this.runRead(()=>t.zRangeByScore(c,"-inf",`(${e.olderThan}`));for(let P of v)u.add(P);}if(e.maxPerChat!==void 0){let v=e.maxPerChat,P=await this.runRead(()=>t.zRange(c,0,-(v+1)));for(let y of P)u.add(y);}if(u.size===0)continue;let w=[...u],M=t.multi();M.zRem(c,w),M.hDel(l,w),await this.runWrite(()=>M.exec()),r+=w.length;}return r}jidFromIndexKey(e){let t=this.msgIndexKey("");return e.startsWith(t)?e.slice(t.length):e}msgIndexKey(e){return `${this.namespace}:msg:${e}`}msgDataKey(e){return `${this.namespace}:msg-data:${e}`}chatsKey(){return `${this.namespace}:chats`}chatsArchiveKey(){return `${this.namespace}:chats-archived`}contactsKey(){return `${this.namespace}:contacts`}presenceKey(e){return `${this.namespace}:presence:${e}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new h("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Xc(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","redis write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","RedisMessageStore is closed")}};var Zt="msg:",Ht="chat:",zt="contact:",Dn="presence:",Bn="job:",ed=n=>`${n.id??""}|${n.fromMe?1:0}`,Yt=n=>`${Zt}${n.remoteJid??""}:${ed(n)}`,ut=n=>JSON.stringify(n,xc.BufferJSON.replacer),X=n=>JSON.parse(n,xc.BufferJSON.reviver),ki=class{kv;closed=false;boundSocket;listeners=new Map;constructor(e){this.kv=new Pe(e);}async saveMessage(e){this.assertOpen(),await this.kv.set([{key:Yt(e.key),value:ut(e),sortKey:Number(e.messageTimestamp??0)}]);}async getMessage(e){this.assertOpen();let r=(await this.kv.get([Yt(e)])).get(Yt(e));return r===void 0?void 0:X(r)}async listMessages(e,t){this.assertOpen();let r={};return typeof t?.before=="number"&&(r.before=t.before),typeof t?.limit=="number"&&(r.limit=t.limit),(await this.kv.list(`${Zt}${e}:`,r)).map(i=>X(i.value))}async saveChat(e){this.assertOpen();let t=e.id;t&&await this.kv.set([{key:`${Ht}${t}`,value:ut(e)}]);}async getChat(e){this.assertOpen();let r=(await this.kv.get([`${Ht}${e}`])).get(`${Ht}${e}`);return r===void 0?void 0:X(r)}async listChats(e){this.assertOpen();let t=await this.kv.list(Ht),r=[];for(let s of t){let i=X(s.value),o=i.archived===true;e?.archived===true&&!o||e?.archived===false&&o||r.push(i);}return r}async saveContact(e){this.assertOpen(),await this.kv.set([{key:`${zt}${e.id}`,value:ut(e)}]);}async getContact(e){this.assertOpen();let r=(await this.kv.get([`${zt}${e}`])).get(`${zt}${e}`);return r===void 0?void 0:X(r)}async listContacts(){return this.assertOpen(),(await this.kv.list(zt)).map(t=>X(t.value))}async savePresence(e,t){this.assertOpen(),await this.kv.set([{key:`${Dn}${e}`,value:ut(t)}]);}async getPresence(e){this.assertOpen();let r=(await this.kv.get([`${Dn}${e}`])).get(`${Dn}${e}`);return r===void 0?void 0:X(r)}async saveScheduledJob(e){this.assertOpen(),await this.kv.set([{key:`${Bn}${e.id}`,value:ut(e),sortKey:e.fireAt}]);}async listScheduledJobs(){return this.assertOpen(),(await this.kv.list(Bn)).map(t=>X(t.value))}async deleteScheduledJob(e){this.assertOpen(),await this.kv.del([`${Bn}${e}`]);}async deleteMessage(e){this.assertOpen(),await this.kv.del([Yt(e)]);}async pruneMessages(e){this.assertOpen();let t=await this.kv.list(Zt,{}),r=new Map;for(let i of t){let o=i.key.slice(Zt.length),a=o.slice(0,o.indexOf(":"));if(e.chatFilter&&!e.chatFilter(a))continue;let c=r.get(a)??[];c.push({key:i.key,ts:i.sortKey??0}),r.set(a,c);}let s=[];for(let i of r.values()){i.sort((o,a)=>a.ts-o.ts);for(let o=0;o<i.length;o++){let a=i[o];(e.olderThan!==void 0&&a.ts<e.olderThan||e.maxPerChat!==void 0&&o>=e.maxPerChat)&&s.push(a.key);}}return s.length>0&&await this.kv.del(s),s.length}bind(e){if(this.assertOpen(),this.boundSocket?.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let a=o[0]?.messages;if(Array.isArray(a))for(let c of a)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen(),await this.kv.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);this.listeners.clear(),this.boundSocket=void 0,this.kv.close();}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","ConvexMessageStore is closed")}};var td=(n,e)=>{if(e<=0)throw new RangeError("chunk size must be positive");let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t};var Hh=n=>{let t=(n.split("@")[0]??"").split(":")[0]?.replace(/\D/g,"")??"";return n.endsWith("@s.whatsapp.net")||n.endsWith("@c.us")?t:""},zh=n=>`${n.replace(/\D/g,"")}@s.whatsapp.net`;Object.defineProperty(exports,"areJidsSameUser",{enumerable:true,get:function(){return xc.areJidsSameUser}});Object.defineProperty(exports,"getDevice",{enumerable:true,get:function(){return xc.getDevice}});Object.defineProperty(exports,"isJidBroadcast",{enumerable:true,get:function(){return xc.isJidBroadcast}});Object.defineProperty(exports,"isJidGroup",{enumerable:true,get:function(){return xc.isJidGroup}});Object.defineProperty(exports,"isJidNewsletter",{enumerable:true,get:function(){return xc.isJidNewsletter}});Object.defineProperty(exports,"isLidUser",{enumerable:true,get:function(){return xc.isLidUser}});Object.defineProperty(exports,"isPnUser",{enumerable:true,get:function(){return xc.isPnUser}});Object.defineProperty(exports,"jidDecode",{enumerable:true,get:function(){return xc.jidDecode}});Object.defineProperty(exports,"jidEncode",{enumerable:true,get:function(){return xc.jidEncode}});Object.defineProperty(exports,"jidNormalizedUser",{enumerable:true,get:function(){return xc.jidNormalizedUser}});exports.AudioProcessor=ne;exports.AutoDeleteSweeper=Ve;exports.AutoRejectCallModule=He;exports.BufferConverter=E;exports.BusinessModule=je;exports.ChatModule=We;exports.Client=ui;exports.CloudModule=at;exports.CloudTransport=Ce;exports.CommandRegistry=Ue;exports.CommunityModule=De;exports.ContactModule=Fe;exports.ConvexAuthStore=Mi;exports.ConvexMessageStore=ki;exports.DEFAULT_GRAPH_VERSION=Dt;exports.DocumentProcessor=ft;exports.EditBuilder=Oe;exports.FFMPEG_CONSTANTS=C;exports.FFmpegProcessor=ee;exports.FileAuthStore=Ct;exports.FileManager=V;exports.GroupModule=_e;exports.ImageProcessor=F;exports.Media=re;exports.MemoryAuthStore=pi;exports.MemoryMessageStore=Tt;exports.MessageBuilder=z;exports.MimeValidator=L;exports.NewsletterModule=Ne;exports.PostgresAuthStore=wi;exports.PostgresMessageStore=Ai;exports.PresenceModule=Ge;exports.PrivacyModule=Le;exports.ProfileModule=Be;exports.RateLimiter=ie;exports.RedisAuthStore=vi;exports.RedisMessageStore=Pi;exports.SELF_ONLY_PROTOCOL_TYPES=eg;exports.Scheduler=Je;exports.SqliteAuthStore=yi;exports.SqliteMessageStore=Si;exports.StickerProcessor=he;exports.TaskQueue=$e;exports.TypedEventEmitter=Nt;exports.VideoProcessor=q;exports.ZaileysAutomationError=I;exports.ZaileysBuilderError=p;exports.ZaileysCloudError=A;exports.ZaileysCommandError=_;exports.ZaileysDomainError=T;exports.ZaileysProviderError=it;exports.ZaileysStoreError=h;exports.adoptLogger=Cn;exports.attachCommandDispatcher=vn;exports.buildMessageContext=En;exports.chunk=td;exports.computeStaticId=Es;exports.computeUniqueId=ks;exports.createAuthGuard=zr;exports.createConnectionStateMachine=Xr;exports.createLogger=ya;exports.createOperationGuard=bn;exports.createPairingFlow=Yr;exports.createReconnectStrategy=Qr;exports.createWebhookHandler=_n;exports.definePlugin=Dr;exports.deleteMessage=mn;exports.detectFileType=N;exports.detectMimeFromBuffer=me;exports.dropSpoofedSelfOnly=ts;exports.epochSecondsToMs=Ts;exports.extractLinks=Cs;exports.ffmpegTransform=U;exports.forwardMessage=fn;exports.generateId=pt;exports.genericPrune=Fr;exports.initializeFFmpeg=nn;exports.isFatalDisconnect=Ze;exports.isJid=Re;exports.isLidJid=It;exports.isPnJid=ls;exports.isRateLimited=Pt;exports.jidToPhone=Hh;exports.loadMedia=O;exports.makeCacheableAuthStore=Gr;exports.mapDisconnectReason=Vr;exports.normalizeJid=Me;exports.normalizePhoneNumber=da;exports.parseCommand=yn;exports.phoneToJid=zh;exports.pinMessage=St;exports.printQrToTerminal=Zr;exports.reactToMessage=gn;exports.renderQrInTerminal=pa;exports.resolveUsername=hn;exports.runBroadcast=An;exports.runMiddleware=wn;exports.senderDeviceOf=Is;exports.shouldClearAuth=Hr;exports.shouldReconnect=Um;exports.signalKeyStoreFromAuthStore=Jr;exports.validateCloudOptions=xn;exports.validateE164=la;