diff --git a/lib/client.js b/lib/client.js index 843fc77..e4d49a3 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1,5 +1,5 @@ window.__ModuleLoader__.load({ - id: "@xmanrui/dsh-im", + id: "dsh-im-ops", factory: (require) => { var module = { exports: {} }; var exports = module.exports; @@ -570,9 +570,9 @@ var React23 = __toESM(require("react"), 1); // package.json var package_default = { - name: "@xmanrui/dsh-im", - version: "4.9.1", - description: "\u628A\u4E5D\u79CD IM \u673A\u5668\u4EBA\u548C\u516C\u7F51 AI Office \u63A5\u5165\u672C\u673A DeepSeek Harness\u3002 Connect nine IM channels and a public AI Office to a local DeepSeek Harness.", + name: "dsh-im-ops", + version: "4.9.1-ops.0", + description: "Ops fork of dsh-im (all channels kept). Based on @xmanrui/dsh-im@4.9.1 \u2014 access/session policies owned here.", keywords: [ "deepseek-harness", "dsh", @@ -591,7 +591,9 @@ var package_default = { "telegram", "discord", "whatsapp", - "ai-office" + "ai-office", + "ops", + "fork" ], author: "xmanrui (https://github.com/xmanrui)", contributors: [ @@ -612,14 +614,11 @@ var package_default = { type: "module", repository: { type: "git", - url: "git+https://github.com/xmanrui/dsh-im.git" + url: "git+https://github.com/hansjone/dsh-im-ops.git" }, - homepage: "https://github.com/xmanrui/dsh-im#readme", + homepage: "https://github.com/hansjone/dsh-im-ops#readme", bugs: { - url: "https://github.com/xmanrui/dsh-im/issues" - }, - publishConfig: { - access: "public" + url: "https://github.com/hansjone/dsh-im-ops/issues" }, bin: { "dsh-im": "bin/dsh-im.mjs" @@ -3756,7 +3755,7 @@ function installDingtalkStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = DINGTALK_STYLE_ID; style.textContent = CSS; document.head.appendChild(style); @@ -5328,7 +5327,7 @@ function installDiscordStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = DISCORD_STYLE_ID; style.textContent = CSS2; document.head.appendChild(style); @@ -7709,7 +7708,7 @@ function installFeishuStyles() { }; } const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = FEISHU_STYLE_ID; style.textContent = CSS3; document.head.appendChild(style); @@ -7871,7 +7870,7 @@ function installQqStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = QQ_STYLE_ID; style.textContent = CSS4; document.head.appendChild(style); @@ -8928,7 +8927,7 @@ function installSlackStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = SLACK_STYLE_ID; style.textContent = CSS6; document.head.appendChild(style); @@ -9099,7 +9098,7 @@ function installTelegramStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = TELEGRAM_STYLE_ID; style.textContent = CSS7; document.head.appendChild(style); @@ -9266,7 +9265,7 @@ function installWecomStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = WECOM_STYLE_ID; style.textContent = CSS8; document.head.appendChild(style); @@ -11018,7 +11017,7 @@ function installWeixinStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = WEIXIN_STYLE_ID; style.textContent = CSS9; document.head.appendChild(style); @@ -11162,7 +11161,7 @@ function installWhatsappStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = WHATSAPP_STYLE_ID; style.textContent = CSS10; document.head.appendChild(style); @@ -13629,7 +13628,7 @@ function installImStyles() { if (existing) return () => { }; const style = document.createElement("style"); - style.dataset.plugin = "@xmanrui/dsh-im"; + style.dataset.plugin = "dsh-im-ops"; style.dataset.pluginCss = IM_STYLE_ID; style.textContent = CSS11; document.head.appendChild(style); @@ -13724,7 +13723,7 @@ function manualUpdateCommand(snapshot) { snapshot.job?.state !== "completed" ? snapshot.job?.targetVersion : null ].filter(validVersion); const version = targets.length ? [...targets, snapshot.runningVersion, snapshot.installedVersion].filter(validVersion).sort(import_rcompare.default)[0] : "latest"; - return `dsh plugin --profile ${profileArgument} add -w @xmanrui/dsh-im@${version}`; + return `dsh plugin --profile ${profileArgument} add -w dsh-im-ops@${version}`; } function ManualUpdateCommand({ command, disabled, sourceInstall, desktop }) { const [copyState, setCopyState] = React22.useState("idle"); @@ -13805,7 +13804,7 @@ function ManualUpdateCommand({ command, disabled, sourceInstall, desktop }) { h2("path", { d: "M5 13H3.5A1.5 1.5 0 0 1 2 11.5v-8A1.5 1.5 0 0 1 3.5 2h8A1.5 1.5 0 0 1 13 3.5V5" }) ))) ), - command.endsWith("@xmanrui/dsh-im@latest") ? h2( + command.endsWith("dsh-im-ops@latest") ? h2( "p", { className: "dim-updateManualHint" }, "\u5C1A\u672A\u786E\u8BA4\u76EE\u6807\u7248\u672C\uFF0C\u6B64\u547D\u4EE4\u5B89\u88C5\u6267\u884C\u65F6 npm \u7684 latest \u7248\u672C\u3002" diff --git a/lib/index.js b/lib/index.js index 0c5fb22..31e98ad 100644 --- a/lib/index.js +++ b/lib/index.js @@ -169,7 +169,7 @@ ${n}`:n)}function u_(n,t,o){return{cardParamMap:{flowStatus:t,msgContent:VE(n,o) ${lhe(I.text,s)}`);g=hc([a,...c,A.join(` `)].join(` -`)),s=Math.floor(s/2)}while(s>0&&(g.message.length>3e3||g.messages.length>3));return g}function phe(n){let t=n?.code??n?.failure?.code;return t==="session-not-found"?w("\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u7ED1\u5B9A\u4F1A\u8BDD\u3002"):t===wa||t==="workspace-bot-not-found"||t==="session-binding-changed"?w("\u4F1A\u8BDD\u3001\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C /history\u3002"):t==="harness-api-not-found"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"):n?.name==="AbortError"?w("\u5386\u53F2\u8BFB\u53D6\u5DF2\u53D6\u6D88\u3002"):n?.name==="TimeoutError"||t==="harness-timeout"?w("\u8BFB\u53D6\u5386\u53F2\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):w("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}function Ka(n){return typeof n=="string"&&FY.test(n.trim())}async function ao(n,t,o,i,{signal:e,isDirect:a=!1,hasImages:A=!1,hasFiles:r=!1}={}){if(!Ka(n))return null;let s=FY.exec(n.trim())[1].trim();if(s&&(!/^\d+$/u.test(s)||/^0+$/u.test(s)))return hc(w(nhe));let g=s?Math.min(Number(s),she):3;if(!a)return hc(w("\u8BF7\u5728\u4E0E\u673A\u5668\u4EBA\u7684\u79C1\u804A\u4E2D\u4F7F\u7528 /history\u3002"));if(A||r)return hc(w("/history \u4EC5\u652F\u6301\u6587\u5B57\u547D\u4EE4\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u6216\u6587\u4EF6\u540E\u91CD\u8BD5\u3002"));let c=o?.sessionFor?.(i);if(typeof c!="string"||!c)return hc(w("\u5F53\u524D\u804A\u5929\u5C1A\u672A\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u6216\u4F7F\u7528 /session \u7ED1\u5B9A\u4F1A\u8BDD\u3002"));try{let I=t?.workspaceSession?.(c);if(typeof I?.readHistory!="function")return hc(w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"));let d=AbortSignal.timeout(GY),B=e?AbortSignal.any([e,d]):d,f=Date.now()+GY,Q=new Map,y,m,T=[],_=!1;for(let R=0;R=f)throw new DOMException("History read timed out","TimeoutError");let H=await I.readHistory({maxMessages:ghe,...y===void 0?{}:{beforeSeq:y},timeoutMs:Math.max(1,f-Date.now()),signal:B});if(B.throwIfAborted(),Date.now()>=f)throw new DOMException("History read timed out","TimeoutError");if(o.sessionFor(i)!==c){let q=new Error("Session binding changed during history read");throw q.code="session-binding-changed",q}if(!H||!Array.isArray(H.events)||typeof H.hasMore!="boolean")throw new TypeError("Invalid history page");let F=y??1/0;for(let q of H.events){let z=q?.event;if(!z||!Number.isSafeInteger(z.seq)||z.seq<0||typeof z.type!="string"||!z.type)throw new TypeError("Invalid history event");if(m!==void 0&&z.seq>m)continue;let K=Q.get(z.seq);if(K){if(!ohe(K,z))throw new TypeError("Conflicting history events")}else{if(y!==void 0&&z.seq>=y)throw new TypeError("Invalid history cursor");Q.set(z.seq,z)}F=Math.min(F,z.seq)}let L=[...Q.values()].sort((q,z)=>q.seq-z.seq);if(m??=L.at(-1)?.seq,_=H.hasMore,_&&(!Number.isFinite(F)||F===y))throw new TypeError("History cursor did not advance");if(T=Ihe(L).slice(-g),T.length>=g||!_)break;y=F}return T.length===0?hc(_?w("\u672C\u6B21\u6709\u9650\u8BFB\u53D6\u4E2D\u672A\u627E\u5230\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002"):w("\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002")):dhe(c,T,g,_)}catch(I){return hc(phe(I))}}var PQ={name:"@xmanrui/dsh-im",version:"4.9.1",description:"\u628A\u4E5D\u79CD IM \u673A\u5668\u4EBA\u548C\u516C\u7F51 AI Office \u63A5\u5165\u672C\u673A DeepSeek Harness\u3002 Connect nine IM channels and a public AI Office to a local DeepSeek Harness.",keywords:["deepseek-harness","dsh","dsh-plugin","ai-agent","im","instant-messaging","chatbot","feishu","lark","wechat","wecom","dingtalk","qq","slack","telegram","discord","whatsapp","ai-office"],author:"xmanrui (https://github.com/xmanrui)",contributors:[{name:"C3H3-AI",url:"https://github.com/C3H3-AI"},{name:"divingleee",url:"https://github.com/divingleee"},{name:"Chan-0312",url:"https://github.com/Chan-0312"}],license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/xmanrui/dsh-im.git"},homepage:"https://github.com/xmanrui/dsh-im#readme",bugs:{url:"https://github.com/xmanrui/dsh-im/issues"},publishConfig:{access:"public"},bin:{"dsh-im":"bin/dsh-im.mjs"},main:"./lib/index.js",exports:{".":"./lib/index.js","./client":"./lib/client.js","./package.json":"./package.json"},files:["assets","bin","cordis.patch.yml","lib","plugin-src","scripts","src","PROACTIVE_DELIVERY.md","PROACTIVE_DELIVERY.en.md","LICENSE","README.md","README.en.md","THIRD_PARTY_NOTICES.md"],dsh:{bundle:{patch:"./cordis.patch.yml"},client:{inject:["@deepseek-ai/dsh-client-connection","@deepseek-ai/dsh-client-runtime","@deepseek-ai/dsh-client-ui-settings","@deepseek-ai/dsh-client-ui-slots","@deepseek-ai/dsh-client-locale"],platform:"web"}},scripts:{build:"node plugin-src/client/build.mjs && node plugin-src/host/build.mjs",test:"node --test test/*.test.mjs test/channels/*/*.test.mjs",check:"npm run build && npm test && node scripts/verify-package.mjs"},engines:{node:">=22.19"},dependencies:{"@tencent-connect/qqbot-connector":"1.2.0","@tencent-connect/qqbot-nodejs":"1.0.4","@wecom/aibot-node-sdk":"1.0.7","dingtalk-stream":"2.1.4",qrcode:"1.5.4",undici:"7.29.0"},devDependencies:{"@deepseek-ai/cordis":"4.0.1","@larksuiteoapi/node-sdk":"1.73.0","@whiskeysockets/baileys":"7.0.0-rc14",esbuild:"0.25.9","https-proxy-agent":"5.0.1",react:"18.3.1","react-dom":"18.3.1","react-test-renderer":"18.3.1",semver:"7.8.5"},directories:{doc:"docs",lib:"lib",test:"test"}};var Ehe=/^\/(?:stop|steer|version)(?=$|\s)/iu,uhe=/^\/stop(?=$|\s)/iu,Che=/^\/version(?=$|\s)/iu,Bhe="\u7528\u6CD5\uFF1A/stop\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",fhe="\u7528\u6CD5\uFF1A/version\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Qhe="\u7528\u6CD5\uFF1A/steer <\u8865\u5145\u6307\u4EE4>",yhe="\u63A7\u5236\u547D\u4EE4\u4EC5\u652F\u6301\u7EAF\u6587\u5B57\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u540E\u91CD\u8BD5\u3002";function No(n,t={}){return{message:n,...t}}function UY(n){return n?{signal:n}:{}}function HY(n,t,o){if(typeof t?.sessionFor!="function")return null;let i=t.sessionFor(o);if(typeof i!="string"||!i)return null;if(typeof n?.workspaceSession!="function")throw new TypeError("Harness does not support workspace sessions");let e=n.workspaceSession(i);if(!e||typeof e!="object")throw new TypeError("Harness returned an invalid workspace session");return e}function ci(n){return typeof n=="string"&&Ehe.test(n.trim())}async function Ti(n,t,o,i,{signal:e,hasImages:a=!1,pendingInteraction:A=!1,control:r}={}){if(!ci(n))return null;let s=n.trim(),g=uhe.test(s),c=Che.test(s);if(a)return No(w(yhe));if(c)return/^\/version$/iu.test(s)?No(`dsh-im v${PQ.version}`):No(w(fhe));if(g){if(!/^\/stop$/iu.test(s))return No(w(Bhe));let Q=HY(t,o,i);if(!Q)return No(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"));if(typeof Q.stopActiveTurn!="function")throw new TypeError("Harness session does not support stopping active turns");return await Q.stopActiveTurn(r,UY(e))?No(w("\u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002"),{stopped:!0}):No(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))}let d=/^\/steer(?:\s+([\s\S]*))?$/iu.exec(s)?.[1]?.trim()??"";if(!d)return No(w(Qhe));if(A)return No([w("\u5F53\u524D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u4F60\u7684\u56DE\u7B54\u6216\u5BA1\u6279\u3002"),"",w("\u8BF7\u5148\u5904\u7406\u5F53\u524D\u8BF7\u6C42\uFF0C\u6216\u8005\u53D1\u9001 /stop \u505C\u6B62\u4EFB\u52A1\u3002")].join(` +`)),s=Math.floor(s/2)}while(s>0&&(g.message.length>3e3||g.messages.length>3));return g}function phe(n){let t=n?.code??n?.failure?.code;return t==="session-not-found"?w("\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u7ED1\u5B9A\u4F1A\u8BDD\u3002"):t===wa||t==="workspace-bot-not-found"||t==="session-binding-changed"?w("\u4F1A\u8BDD\u3001\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C /history\u3002"):t==="harness-api-not-found"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"):n?.name==="AbortError"?w("\u5386\u53F2\u8BFB\u53D6\u5DF2\u53D6\u6D88\u3002"):n?.name==="TimeoutError"||t==="harness-timeout"?w("\u8BFB\u53D6\u5386\u53F2\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):w("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}function Ka(n){return typeof n=="string"&&FY.test(n.trim())}async function ao(n,t,o,i,{signal:e,isDirect:a=!1,hasImages:A=!1,hasFiles:r=!1}={}){if(!Ka(n))return null;let s=FY.exec(n.trim())[1].trim();if(s&&(!/^\d+$/u.test(s)||/^0+$/u.test(s)))return hc(w(nhe));let g=s?Math.min(Number(s),she):3;if(!a)return hc(w("\u8BF7\u5728\u4E0E\u673A\u5668\u4EBA\u7684\u79C1\u804A\u4E2D\u4F7F\u7528 /history\u3002"));if(A||r)return hc(w("/history \u4EC5\u652F\u6301\u6587\u5B57\u547D\u4EE4\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u6216\u6587\u4EF6\u540E\u91CD\u8BD5\u3002"));let c=o?.sessionFor?.(i);if(typeof c!="string"||!c)return hc(w("\u5F53\u524D\u804A\u5929\u5C1A\u672A\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u6216\u4F7F\u7528 /session \u7ED1\u5B9A\u4F1A\u8BDD\u3002"));try{let I=t?.workspaceSession?.(c);if(typeof I?.readHistory!="function")return hc(w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"));let d=AbortSignal.timeout(GY),B=e?AbortSignal.any([e,d]):d,f=Date.now()+GY,Q=new Map,y,m,T=[],_=!1;for(let R=0;R=f)throw new DOMException("History read timed out","TimeoutError");let H=await I.readHistory({maxMessages:ghe,...y===void 0?{}:{beforeSeq:y},timeoutMs:Math.max(1,f-Date.now()),signal:B});if(B.throwIfAborted(),Date.now()>=f)throw new DOMException("History read timed out","TimeoutError");if(o.sessionFor(i)!==c){let q=new Error("Session binding changed during history read");throw q.code="session-binding-changed",q}if(!H||!Array.isArray(H.events)||typeof H.hasMore!="boolean")throw new TypeError("Invalid history page");let F=y??1/0;for(let q of H.events){let z=q?.event;if(!z||!Number.isSafeInteger(z.seq)||z.seq<0||typeof z.type!="string"||!z.type)throw new TypeError("Invalid history event");if(m!==void 0&&z.seq>m)continue;let K=Q.get(z.seq);if(K){if(!ohe(K,z))throw new TypeError("Conflicting history events")}else{if(y!==void 0&&z.seq>=y)throw new TypeError("Invalid history cursor");Q.set(z.seq,z)}F=Math.min(F,z.seq)}let L=[...Q.values()].sort((q,z)=>q.seq-z.seq);if(m??=L.at(-1)?.seq,_=H.hasMore,_&&(!Number.isFinite(F)||F===y))throw new TypeError("History cursor did not advance");if(T=Ihe(L).slice(-g),T.length>=g||!_)break;y=F}return T.length===0?hc(_?w("\u672C\u6B21\u6709\u9650\u8BFB\u53D6\u4E2D\u672A\u627E\u5230\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002"):w("\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002")):dhe(c,T,g,_)}catch(I){return hc(phe(I))}}var PQ={name:"dsh-im-ops",version:"4.9.1-ops.0",description:"Ops fork of dsh-im (all channels kept). Based on @xmanrui/dsh-im@4.9.1 \u2014 access/session policies owned here.",keywords:["deepseek-harness","dsh","dsh-plugin","ai-agent","im","instant-messaging","chatbot","feishu","lark","wechat","wecom","dingtalk","qq","slack","telegram","discord","whatsapp","ai-office","ops","fork"],author:"xmanrui (https://github.com/xmanrui)",contributors:[{name:"C3H3-AI",url:"https://github.com/C3H3-AI"},{name:"divingleee",url:"https://github.com/divingleee"},{name:"Chan-0312",url:"https://github.com/Chan-0312"}],license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/hansjone/dsh-im-ops.git"},homepage:"https://github.com/hansjone/dsh-im-ops#readme",bugs:{url:"https://github.com/hansjone/dsh-im-ops/issues"},bin:{"dsh-im":"bin/dsh-im.mjs"},main:"./lib/index.js",exports:{".":"./lib/index.js","./client":"./lib/client.js","./package.json":"./package.json"},files:["assets","bin","cordis.patch.yml","lib","plugin-src","scripts","src","PROACTIVE_DELIVERY.md","PROACTIVE_DELIVERY.en.md","LICENSE","README.md","README.en.md","THIRD_PARTY_NOTICES.md"],dsh:{bundle:{patch:"./cordis.patch.yml"},client:{inject:["@deepseek-ai/dsh-client-connection","@deepseek-ai/dsh-client-runtime","@deepseek-ai/dsh-client-ui-settings","@deepseek-ai/dsh-client-ui-slots","@deepseek-ai/dsh-client-locale"],platform:"web"}},scripts:{build:"node plugin-src/client/build.mjs && node plugin-src/host/build.mjs",test:"node --test test/*.test.mjs test/channels/*/*.test.mjs",check:"npm run build && npm test && node scripts/verify-package.mjs"},engines:{node:">=22.19"},dependencies:{"@tencent-connect/qqbot-connector":"1.2.0","@tencent-connect/qqbot-nodejs":"1.0.4","@wecom/aibot-node-sdk":"1.0.7","dingtalk-stream":"2.1.4",qrcode:"1.5.4",undici:"7.29.0"},devDependencies:{"@deepseek-ai/cordis":"4.0.1","@larksuiteoapi/node-sdk":"1.73.0","@whiskeysockets/baileys":"7.0.0-rc14",esbuild:"0.25.9","https-proxy-agent":"5.0.1",react:"18.3.1","react-dom":"18.3.1","react-test-renderer":"18.3.1",semver:"7.8.5"},directories:{doc:"docs",lib:"lib",test:"test"}};var Ehe=/^\/(?:stop|steer|version)(?=$|\s)/iu,uhe=/^\/stop(?=$|\s)/iu,Che=/^\/version(?=$|\s)/iu,Bhe="\u7528\u6CD5\uFF1A/stop\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",fhe="\u7528\u6CD5\uFF1A/version\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Qhe="\u7528\u6CD5\uFF1A/steer <\u8865\u5145\u6307\u4EE4>",yhe="\u63A7\u5236\u547D\u4EE4\u4EC5\u652F\u6301\u7EAF\u6587\u5B57\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u540E\u91CD\u8BD5\u3002";function No(n,t={}){return{message:n,...t}}function UY(n){return n?{signal:n}:{}}function HY(n,t,o){if(typeof t?.sessionFor!="function")return null;let i=t.sessionFor(o);if(typeof i!="string"||!i)return null;if(typeof n?.workspaceSession!="function")throw new TypeError("Harness does not support workspace sessions");let e=n.workspaceSession(i);if(!e||typeof e!="object")throw new TypeError("Harness returned an invalid workspace session");return e}function ci(n){return typeof n=="string"&&Ehe.test(n.trim())}async function Ti(n,t,o,i,{signal:e,hasImages:a=!1,pendingInteraction:A=!1,control:r}={}){if(!ci(n))return null;let s=n.trim(),g=uhe.test(s),c=Che.test(s);if(a)return No(w(yhe));if(c)return/^\/version$/iu.test(s)?No(`dsh-im v${PQ.version}`):No(w(fhe));if(g){if(!/^\/stop$/iu.test(s))return No(w(Bhe));let Q=HY(t,o,i);if(!Q)return No(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"));if(typeof Q.stopActiveTurn!="function")throw new TypeError("Harness session does not support stopping active turns");return await Q.stopActiveTurn(r,UY(e))?No(w("\u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002"),{stopped:!0}):No(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))}let d=/^\/steer(?:\s+([\s\S]*))?$/iu.exec(s)?.[1]?.trim()??"";if(!d)return No(w(Qhe));if(A)return No([w("\u5F53\u524D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u4F60\u7684\u56DE\u7B54\u6216\u5BA1\u6279\u3002"),"",w("\u8BF7\u5148\u5904\u7406\u5F53\u524D\u8BF7\u6C42\uFF0C\u6216\u8005\u53D1\u9001 /stop \u505C\u6B62\u4EFB\u52A1\u3002")].join(` `));let B=HY(t,o,i);if(!B)return No(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u8865\u5145\u6307\u4EE4\u3002\u8BF7\u5148\u7ED1\u5B9A\u4F1A\u8BDD\u3002"));if(typeof B.steerActiveTurn!="function")throw new TypeError("Harness session does not support steering active turns");let f=await B.steerActiveTurn(d,r,UY(e));return No(f?w("\u5DF2\u63D0\u4EA4\u8865\u5145\u6307\u4EE4\uFF0CAgent \u4F1A\u5728\u4E0B\u4E00\u6B65\u8BFB\u53D6\u3002"):w("\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\uFF0C\u65E0\u6CD5\u8865\u5145\u6307\u4EE4\u3002\u8BF7\u76F4\u63A5\u53D1\u9001\u6D88\u606F\u5F00\u59CB\u65B0\u4EFB\u52A1\u3002"))}var mhe=/^\/model(?=$|\s)/i,WY=/^\/models(?=$|\s)/i,ZY=/^\/reasoning(?=$|\s)/i,XY=/^\/reasonings(?=$|\s)/i,$Y=/^\/reasoninglist(?=$|\s)/i,KY="\u7528\u6CD5\uFF1A/model <\u5E8F\u53F7\u6216 provider/model> [\u63A8\u7406\u7B49\u7EA7ID]",She="\u7528\u6CD5\uFF1A/models\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",whe="\u7528\u6CD5\uFF1A/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default]",Dhe="\u7528\u6CD5\uFF1A/reasoninglist \u6216 /reasonings\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",e1="session-binding-changed",A1="model-selection-mismatch",Ohe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;function Ct(n){return{handled:!0,message:n,messages:cg(n)}}function ra(n){return typeof n!="string"?"":n.replace(Ohe," ").replace(/\s+/gu," ").trim()}function bhe(n){return n?{signal:n}:{}}function Mhe(n){if(n===void 0)return;if(!n||typeof n!="object"||!Array.isArray(n.efforts)||n.efforts.length===0)throw new TypeError("Harness returned invalid model reasoning metadata");let t=n.efforts.map(o=>{if(!o||typeof o!="object"||typeof o.id!="string"||!o.id||typeof o.name!="string"||!o.name||o.description!==void 0&&typeof o.description!="string")throw new TypeError("Harness returned an invalid reasoning effort");return{id:o.id,name:o.name,...o.description===void 0?{}:{description:o.description}}});if(n.defaultEffort!==void 0&&(typeof n.defaultEffort!="string"||!n.defaultEffort))throw new TypeError("Harness returned an invalid default reasoning effort");return{efforts:t,...n.defaultEffort===void 0?{}:{defaultEffort:n.defaultEffort}}}function t1(n,{requireCurrent:t=!1}={}){if(!n||typeof n!="object"||!Array.isArray(n.groups)||!Array.isArray(n.failures))throw new TypeError("Harness returned an invalid model catalog");let o=n.groups.map(a=>{if(!a||typeof a!="object"||typeof a.id!="string"||!a.id||typeof a.name!="string"||!a.name||!Array.isArray(a.models))throw new TypeError("Harness returned an invalid model provider group");return{id:a.id,name:a.name,models:a.models.map(A=>{if(!A||typeof A!="object"||typeof A.id!="string"||!A.id||typeof A.name!="string"||!A.name||A.description!==void 0&&typeof A.description!="string")throw new TypeError("Harness returned an invalid model");return{id:A.id,name:A.name,...A.description===void 0?{}:{description:A.description},...A.reasoning===void 0?{}:{reasoning:Mhe(A.reasoning)}}})}}),i=n.failures.map(a=>{if(!a||typeof a!="object"||typeof a.id!="string"||!a.id||typeof a.name!="string"||!a.name)throw new TypeError("Harness returned an invalid model provider failure");return{id:a.id,name:a.name}}),e=null;if(n.current!==void 0){if(!n.current||typeof n.current!="object"||typeof n.current.provider!="string"||!n.current.provider||typeof n.current.model!="string"||!n.current.model||n.current.reasoningEffort!==void 0&&(typeof n.current.reasoningEffort!="string"||!n.current.reasoningEffort))throw new TypeError("Harness returned an invalid current model");e={provider:n.current.provider,model:n.current.model,...n.current.reasoningEffort===void 0?{}:{reasoningEffort:n.current.reasoningEffort}}}else if(t)throw new TypeError("Harness returned no current model");return{groups:o,failures:i,current:e}}function Ig(n,t){return`${n}/${t}`}function r1(n,t){return n?.provider===t?.provider&&n?.model===t?.model}function _he(n,t){return r1(n,t)&&n?.reasoningEffort===t?.reasoningEffort}function The(n,t){return r1(n,t)&&(t.reasoningEffort===void 0||n?.reasoningEffort===t.reasoningEffort)}function G_(n){if(!n?.provider||!n?.model)return"";let t=Ig(n.provider,n.model);return n.reasoningEffort===void 0?t:`${t} \xB7 reasoningEffort=${ra(n.reasoningEffort)}`}function xY(n,t,o){let i=new Error(`Harness ${o} did not confirm the selected model`);return i.code=A1,i.expected=n,i.actual=t,i.source=o,i}function a1(){let n=new Error("Conversation binding changed during model selection");return n.code=e1,n}function YY(n,t,o){if((typeof n?.sessionFor=="function"?n.sessionFor(t):null)!==o)throw a1()}function Nhe(n,t){for(let o of n.groups)for(let i of o.models)if(Ig(o.id,i.id)===t)return{provider:o.id,model:i.id};return null}function Rhe(n,t){let o=0;for(let i of n.groups)for(let e of i.models)if(o+=1,o===t)return{provider:i.id,model:e.id};return null}function jY(n){if(!/^\d+$/u.test(n))return null;let t=Number(n);return{index:Number.isSafeInteger(t)&&t>0?t:null}}function GQ(n,t){return t?n.groups.find(({id:i})=>i===t.provider)?.models.find(({id:i})=>i===t.model)??null:null}function khe(n,t){return n?.reasoning?.efforts?.[t-1]??null}function F_(n,t){return n?.reasoning?.efforts?.find(({id:o})=>o===t)??null}function FQ(n,t){return n?.reasoningEffort??t?.reasoning?.defaultEffort}function ZE(n,t){if(t===void 0)return w("Default\uFF08\u7531\u6A21\u578B\u6216 Provider \u51B3\u5B9A\uFF09");let o=F_(n,t);if(!o)return ra(t);let i=ra(o.name),e=ra(o.id);return i===e?e:`${i} (${e})`}function i1(n){let t=GQ(n,n.current);return ZE(t,FQ(n.current,t))}function vhe(n,t,o){return n===t&&n===o?w("\uFF08\u5F53\u524D\u3001\u9ED8\u8BA4\uFF09"):n===t?w("\uFF08\u5F53\u524D\uFF09"):n===o?w("\uFF08\u9ED8\u8BA4\uFF09"):""}function JY(n){return[w("\u6A21\u578B\u5E8F\u53F7\u65E0\u6548\uFF1A{input}",{input:ra(n)}),"",w("\u8BF7\u53D1\u9001 /models \u67E5\u770B\u5E76\u8F93\u5165\u6709\u6548\u7684\u6B63\u6574\u6570\u5E8F\u53F7\u3002")].join(` `)}function qY(n){return[w("\u63A8\u7406\u7B49\u7EA7\u5E8F\u53F7\u65E0\u6548\uFF1A{input}",{input:ra(n)}),"",w("\u8BF7\u53D1\u9001 /reasoninglist \u67E5\u770B\u5E76\u8F93\u5165\u6709\u6548\u7684\u6B63\u6574\u6570\u5E8F\u53F7\u3002")].join(` `)}function k_(n,t,o){let i=[w("\u6A21\u578B\u4E0D\u652F\u6301\u63A8\u7406\u7B49\u7EA7\uFF1A{effort}",{effort:ra(t)}),"",ra(G_(n))],e=o?.reasoning?.efforts?.map(({id:a})=>ra(a))??[];return e.length>0?i.push(w("\u53EF\u7528\u63A8\u7406\u7B49\u7EA7\uFF1A{efforts}",{efforts:e.join(", ")})):i.push(w("\u8BE5\u6A21\u578B\u4E0D\u63D0\u4F9B\u53EF\u5207\u6362\u7684\u63A8\u7406\u7B49\u7EA7\u3002")),i.join(` @@ -433,7 +433,7 @@ ${B}`:ut(m),s,g),I||await this.#o.markSeen(A)}catch(T){this.#s.error?.("[dsh-wei `);let o=xn(n.content,t+1),i=`<${n.tag} ${Object.entries(n.attrs||{}).filter(([,a])=>a!==void 0).map(([a,A])=>`${a}='${A}'`).join(" ")}`,e=o?`> ${o} ${OD(t)}`:"/>";return i+e}var oI=ze(Vc(),1);import{createCipheriv as OL,createDecipheriv as bL,createHash as Nxe,createHmac as Rxe,randomBytes as kxe}from"crypto";var HB=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,C$.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,C$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_expandedappstatekeys_free(t,0)}get indexKey(){let t=ie.expandedappstatekeys_indexKey(this.__wbg_ptr);return mA(t)}get patchMacKey(){let t=ie.expandedappstatekeys_patchMacKey(this.__wbg_ptr);return mA(t)}get snapshotMacKey(){let t=ie.expandedappstatekeys_snapshotMacKey(this.__wbg_ptr);return mA(t)}get valueEncryptionKey(){let t=ie.expandedappstatekeys_valueEncryptionKey(this.__wbg_ptr);return mA(t)}get valueMacKey(){let t=ie.expandedappstatekeys_valueMacKey(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(HB.prototype[Symbol.dispose]=HB.prototype.free);var MD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,B$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_groupcipher_free(t,0)}decrypt(t){let o=vt(t,ie.__wbindgen_export),i=KA,e=ie.groupcipher_decrypt(this.__wbg_ptr,o,i);return mA(e)}encrypt(t){let o=vt(t,ie.__wbindgen_export),i=KA,e=ie.groupcipher_encrypt(this.__wbg_ptr,o,i);return mA(e)}constructor(t,o,i){let e=jn(o,ie.__wbindgen_export,ie.__wbindgen_export2),a=KA;aI(i,iI);let A=ie.groupcipher_new(rA(t),e,a,i.__wbg_ptr);return this.__wbg_ptr=A>>>0,B$.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(MD.prototype[Symbol.dispose]=MD.prototype.free);var _D=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,f$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_groupsessionbuilder_free(t,0)}create(t){aI(t,Oh);let o=ie.groupsessionbuilder_create(this.__wbg_ptr,t.__wbg_ptr);return mA(o)}constructor(t){let o=ie.groupsessionbuilder_new(rA(t));return this.__wbg_ptr=o>>>0,f$.register(this,this.__wbg_ptr,this),this}process(t,o){aI(t,Oh),aI(o,Dh);let i=ie.groupsessionbuilder_process(this.__wbg_ptr,t.__wbg_ptr,o.__wbg_ptr);return mA(i)}};Symbol.dispose&&(_D.prototype[Symbol.dispose]=_D.prototype.free);var KB=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,Q$.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Q$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_internalbinarynode_free(t,0)}get attrs(){let t=ie.internalbinarynode_attrs(this.__wbg_ptr);return mA(t)}get content(){let t=ie.internalbinarynode_content(this.__wbg_ptr);return mA(t)}set attrs(t){ie.internalbinarynode_set_attrs(this.__wbg_ptr,rA(t))}set content(t){ie.internalbinarynode_set_content(this.__wbg_ptr,rA(t))}get tag(){let t,o;try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.internalbinarynode_tag(a,this.__wbg_ptr);var i=eA().getInt32(a+0,!0),e=eA().getInt32(a+4,!0);return t=i,o=e,vr(i,e)}finally{ie.__wbindgen_add_to_stack_pointer(16),ie.__wbindgen_export4(t,o,1)}}toJSON(){let t=ie.internalbinarynode_toJSON(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(KB.prototype[Symbol.dispose]=KB.prototype.free);var wh=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,y$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_lthashantitampering_free(t,0)}constructor(){let t=ie.lthashantitampering_new();return this.__wbg_ptr=t>>>0,y$.register(this,this.__wbg_ptr,this),this}subtractThenAdd(t,o,i){try{let r=ie.__wbindgen_add_to_stack_pointer(-16),s=vt(t,ie.__wbindgen_export),g=KA,c=_$(o,ie.__wbindgen_export),I=KA,d=_$(i,ie.__wbindgen_export),B=KA;ie.lthashantitampering_subtractThenAdd(r,this.__wbg_ptr,s,g,c,I,d,B);var e=eA().getInt32(r+0,!0),a=eA().getInt32(r+4,!0),A=eA().getInt32(r+8,!0);if(A)throw mA(a);return mA(e)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(wh.prototype[Symbol.dispose]=wh.prototype.free);var TD=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,yL.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,yL.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_lthashstate_free(t,0)}clone(){let t=ie.lthashstate_clone(this.__wbg_ptr);return n.__wrap(t)}deleteValueMac(t){let o=jn(t,ie.__wbindgen_export,ie.__wbindgen_export2),i=KA;return ie.lthashstate_deleteValueMac(this.__wbg_ptr,o,i)!==0}getValueMac(t){let o=jn(t,ie.__wbindgen_export,ie.__wbindgen_export2),i=KA,e=ie.lthashstate_getValueMac(this.__wbg_ptr,o,i);return mA(e)}hasValueMac(t){let o=jn(t,ie.__wbindgen_export,ie.__wbindgen_export2),i=KA;return ie.lthashstate_hasValueMac(this.__wbg_ptr,o,i)!==0}get hash(){let t=ie.lthashstate_hash(this.__wbg_ptr);return mA(t)}constructor(){let t=ie.lthashstate_new();return this.__wbg_ptr=t>>>0,yL.register(this,this.__wbg_ptr,this),this}setValueMac(t,o){let i=jn(t,ie.__wbindgen_export,ie.__wbindgen_export2),e=KA,a=vt(o,ie.__wbindgen_export),A=KA;ie.lthashstate_setValueMac(this.__wbg_ptr,i,e,a,A)}set hash(t){let o=vt(t,ie.__wbindgen_export),i=KA;ie.lthashstate_set_hash(this.__wbg_ptr,o,i)}set version(t){ie.lthashstate_set_version(this.__wbg_ptr,t)}get version(){let t=ie.lthashstate_version(this.__wbg_ptr);return BigInt.asUintN(64,t)}};Symbol.dispose&&(TD.prototype[Symbol.dispose]=TD.prototype.free);var ND=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,m$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_noisesession_free(t,0)}authenticate(t){let o=vt(t,ie.__wbindgen_export),i=KA;ie.noisesession_authenticate(this.__wbg_ptr,o,i)}get bufferedBytes(){return ie.noisesession_bufferedBytes(this.__wbg_ptr)>>>0}clearBuffer(){ie.noisesession_clearBuffer(this.__wbg_ptr)}decodeFrame(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16),A=vt(t,ie.__wbindgen_export),r=KA;ie.noisesession_decodeFrame(a,this.__wbg_ptr,A,r);var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}decrypt(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16),A=vt(t,ie.__wbindgen_export),r=KA;ie.noisesession_decrypt(a,this.__wbg_ptr,A,r);var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}encodeFrame(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.noisesession_encodeFrame(a,this.__wbg_ptr,rA(t));var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}encodeFrameRaw(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16),A=vt(t,ie.__wbindgen_export),r=KA;ie.noisesession_encodeFrameRaw(a,this.__wbg_ptr,A,r);var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}encrypt(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16),A=vt(t,ie.__wbindgen_export),r=KA;ie.noisesession_encrypt(a,this.__wbg_ptr,A,r);var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}finishInit(){try{let i=ie.__wbindgen_add_to_stack_pointer(-16);ie.noisesession_finishInit(i,this.__wbg_ptr);var t=eA().getInt32(i+0,!0),o=eA().getInt32(i+4,!0);if(o)throw mA(t)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}getHash(){let t=ie.noisesession_getHash(this.__wbg_ptr);return mA(t)}get isFinished(){return ie.noisesession_isFinished(this.__wbg_ptr)!==0}mixIntoKey(t){try{let e=ie.__wbindgen_add_to_stack_pointer(-16),a=vt(t,ie.__wbindgen_export),A=KA;ie.noisesession_mixIntoKey(e,this.__wbg_ptr,a,A);var o=eA().getInt32(e+0,!0),i=eA().getInt32(e+4,!0);if(i)throw mA(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}constructor(t,o,i){try{let g=ie.__wbindgen_add_to_stack_pointer(-16),c=vt(t,ie.__wbindgen_export),I=KA,d=vt(o,ie.__wbindgen_export),B=KA;var e=Yn(i)?0:vt(i,ie.__wbindgen_export),a=KA;ie.noisesession_new(g,c,I,d,B,e,a);var A=eA().getInt32(g+0,!0),r=eA().getInt32(g+4,!0),s=eA().getInt32(g+8,!0);if(s)throw mA(r);return this.__wbg_ptr=A>>>0,m$.register(this,this.__wbg_ptr,this),this}finally{ie.__wbindgen_add_to_stack_pointer(16)}}processHandshakeFinish(t,o,i){try{let r=ie.__wbindgen_add_to_stack_pointer(-16),s=vt(t,ie.__wbindgen_export),g=KA,c=vt(o,ie.__wbindgen_export),I=KA,d=vt(i,ie.__wbindgen_export),B=KA;ie.noisesession_processHandshakeFinish(r,this.__wbg_ptr,s,g,c,I,d,B);var e=eA().getInt32(r+0,!0),a=eA().getInt32(r+4,!0),A=eA().getInt32(r+8,!0);if(A)throw mA(a);return mA(e)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}processHandshakeInit(t,o,i,e){try{let s=ie.__wbindgen_add_to_stack_pointer(-16),g=vt(t,ie.__wbindgen_export),c=KA,I=vt(o,ie.__wbindgen_export),d=KA,B=vt(i,ie.__wbindgen_export),f=KA,Q=vt(e,ie.__wbindgen_export),y=KA;ie.noisesession_processHandshakeInit(s,this.__wbg_ptr,g,c,I,d,B,f,Q,y);var a=eA().getInt32(s+0,!0),A=eA().getInt32(s+4,!0),r=eA().getInt32(s+8,!0);if(r)throw mA(A);return mA(a)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(ND.prototype[Symbol.dispose]=ND.prototype.free);var iI=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,mL.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,mL.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_protocoladdress_free(t,0)}get deviceId(){return ie.protocoladdress_deviceId(this.__wbg_ptr)>>>0}static from(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.protocoladdress_from(a,rA(t));var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}get id(){let t,o;try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.protocoladdress_id(a,this.__wbg_ptr);var i=eA().getInt32(a+0,!0),e=eA().getInt32(a+4,!0);return t=i,o=e,vr(i,e)}finally{ie.__wbindgen_add_to_stack_pointer(16),ie.__wbindgen_export4(t,o,1)}}is(t){return aI(t,n),ie.protocoladdress_is(this.__wbg_ptr,t.__wbg_ptr)!==0}constructor(t,o){try{let A=ie.__wbindgen_add_to_stack_pointer(-16);ie.protocoladdress_new(A,rA(t),rA(o));var i=eA().getInt32(A+0,!0),e=eA().getInt32(A+4,!0),a=eA().getInt32(A+8,!0);if(a)throw mA(e);return this.__wbg_ptr=i>>>0,mL.register(this,this.__wbg_ptr,this),this}finally{ie.__wbindgen_add_to_stack_pointer(16)}}toString(){let t,o;try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.protocoladdress_toString(a,this.__wbg_ptr);var i=eA().getInt32(a+0,!0),e=eA().getInt32(a+4,!0);return t=i,o=e,vr(i,e)}finally{ie.__wbindgen_add_to_stack_pointer(16),ie.__wbindgen_export4(t,o,1)}}};Symbol.dispose&&(iI.prototype[Symbol.dispose]=iI.prototype.free);var Dh=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,S$.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,S$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_senderkeydistributionmessage_free(t,0)}static deserialize(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16),A=vt(t,ie.__wbindgen_export),r=KA;ie.senderkeydistributionmessage_deserialize(a,A,r);var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}serialize(){let t=ie.senderkeydistributionmessage_serialize(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(Dh.prototype[Symbol.dispose]=Dh.prototype.free);var Oh=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,w$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_senderkeyname_free(t,0)}constructor(t,o){let i=jn(t,ie.__wbindgen_export,ie.__wbindgen_export2),e=KA;aI(o,iI);let a=ie.senderkeyname_new(i,e,o.__wbg_ptr);return this.__wbg_ptr=a>>>0,w$.register(this,this.__wbg_ptr,this),this}toString(){let t,o;try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.senderkeyname_toString(a,this.__wbg_ptr);var i=eA().getInt32(a+0,!0),e=eA().getInt32(a+4,!0);return t=i,o=e,vr(i,e)}finally{ie.__wbindgen_add_to_stack_pointer(16),ie.__wbindgen_export4(t,o,1)}}};Symbol.dispose&&(Oh.prototype[Symbol.dispose]=Oh.prototype.free);var RD=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,SL.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,SL.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_senderkeyrecord_free(t,0)}static deserialize(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16),A=vt(t,ie.__wbindgen_export),r=KA;ie.senderkeyrecord_deserialize(a,A,r);var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}isEmpty(){return ie.senderkeyrecord_isEmpty(this.__wbg_ptr)!==0}constructor(){let t=ie.senderkeyrecord_new();return this.__wbg_ptr=t>>>0,SL.register(this,this.__wbg_ptr,this),this}serialize(){try{let e=ie.__wbindgen_add_to_stack_pointer(-16);ie.senderkeyrecord_serialize(e,this.__wbg_ptr);var t=eA().getInt32(e+0,!0),o=eA().getInt32(e+4,!0),i=eA().getInt32(e+8,!0);if(i)throw mA(o);return mA(t)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(RD.prototype[Symbol.dispose]=RD.prototype.free);var kD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,D$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_sessionbuilder_free(t,0)}initOutgoing(t){let o=ie.sessionbuilder_initOutgoing(this.__wbg_ptr,rA(t));return mA(o)}constructor(t,o){aI(o,iI);let i=ie.sessionbuilder_new(rA(t),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,D$.register(this,this.__wbg_ptr,this),this}processPreKeyBundle(t){let o=ie.sessionbuilder_processPreKeyBundle(this.__wbg_ptr,rA(t));return mA(o)}};Symbol.dispose&&(kD.prototype[Symbol.dispose]=kD.prototype.free);var vD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,O$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_sessioncipher_free(t,0)}decryptPreKeyWhisperMessage(t){let o=vt(t,ie.__wbindgen_export),i=KA,e=ie.sessioncipher_decryptPreKeyWhisperMessage(this.__wbg_ptr,o,i);return mA(e)}decryptWhisperMessage(t){let o=vt(t,ie.__wbindgen_export),i=KA,e=ie.sessioncipher_decryptWhisperMessage(this.__wbg_ptr,o,i);return mA(e)}encrypt(t){let o=vt(t,ie.__wbindgen_export),i=KA,e=ie.sessioncipher_encrypt(this.__wbg_ptr,o,i);return mA(e)}hasOpenSession(){let t=ie.sessioncipher_hasOpenSession(this.__wbg_ptr);return mA(t)}constructor(t,o){aI(o,iI);let i=ie.sessioncipher_new(rA(t),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,O$.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(vD.prototype[Symbol.dispose]=vD.prototype.free);var xB=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,b$.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,b$.unregister(this),t}free(){let t=this.__destroy_into_raw();ie.__wbg_sessionrecord_free(t,0)}static deserialize(t){try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.sessionrecord_deserialize(a,rA(t));var o=eA().getInt32(a+0,!0),i=eA().getInt32(a+4,!0),e=eA().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}haveOpenSession(){return ie.sessionrecord_haveOpenSession(this.__wbg_ptr)!==0}serialize(){let t=ie.sessionrecord_serialize(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(xB.prototype[Symbol.dispose]=xB.prototype.free);function T$(n){let t=vt(n,ie.__wbindgen_export),o=KA,i=ie.expandAppStateKeys(t,o);return HB.__wrap(i)}function Jn(n,t,o){try{let A=ie.__wbindgen_add_to_stack_pointer(-16),r=vt(n,ie.__wbindgen_export),s=KA;ie.hkdf(A,r,s,t,rA(o));var i=eA().getInt32(A+0,!0),e=eA().getInt32(A+4,!0),a=eA().getInt32(A+8,!0);if(a)throw mA(e);return mA(i)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}function Cxe(){return{__proto__:null,"./whatsapp_rust_bridge_bg.js":{__proto__:null,__wbg_Error_83742b46f01ce22d:function(t,o){let i=Error(vr(t,o));return rA(i)},__wbg_Number_a5a435bd7bbec835:function(t){return Number(Fe(t))},__wbg_String_8564e559799eccda:function(t,o){let i=String(Fe(o)),e=jn(i,ie.__wbindgen_export,ie.__wbindgen_export2),a=KA;eA().setInt32(t+4,a,!0),eA().setInt32(t+0,e,!0)},__wbg___wbindgen_bigint_get_as_i64_447a76b5c6ef7bda:function(t,o){let i=Fe(o),e=typeof i=="bigint"?i:void 0;eA().setBigInt64(t+8,Yn(e)?BigInt(0):e,!0),eA().setInt32(t+0,!Yn(e),!0)},__wbg___wbindgen_boolean_get_c0f3f60bac5a78d1:function(t){let o=Fe(t),i=typeof o=="boolean"?o:void 0;return Yn(i)?16777215:i?1:0},__wbg___wbindgen_debug_string_5398f5bb970e0daa:function(t,o){let i=DL(Fe(o)),e=jn(i,ie.__wbindgen_export,ie.__wbindgen_export2),a=KA;eA().setInt32(t+4,a,!0),eA().setInt32(t+0,e,!0)},__wbg___wbindgen_in_41dbb8413020e076:function(t,o){return Fe(t)in Fe(o)},__wbg___wbindgen_is_bigint_e2141d4f045b7eda:function(t){return typeof Fe(t)=="bigint"},__wbg___wbindgen_is_function_3c846841762788c1:function(t){return typeof Fe(t)=="function"},__wbg___wbindgen_is_null_0b605fc6b167c56f:function(t){return Fe(t)===null},__wbg___wbindgen_is_object_781bc9f159099513:function(t){let o=Fe(t);return typeof o=="object"&&o!==null},__wbg___wbindgen_is_undefined_52709e72fb9f179c:function(t){return Fe(t)===void 0},__wbg___wbindgen_jsval_eq_ee31bfad3e536463:function(t,o){return Fe(t)===Fe(o)},__wbg___wbindgen_jsval_loose_eq_5bcc3bed3c69e72b:function(t,o){return Fe(t)==Fe(o)},__wbg___wbindgen_number_get_34bb9d9dcfa21373:function(t,o){let i=Fe(o),e=typeof i=="number"?i:void 0;eA().setFloat64(t+8,Yn(e)?0:e,!0),eA().setInt32(t+0,!Yn(e),!0)},__wbg___wbindgen_string_get_395e606bd0ee4427:function(t,o){let i=Fe(o),e=typeof i=="string"?i:void 0;var a=Yn(e)?0:jn(e,ie.__wbindgen_export,ie.__wbindgen_export2),A=KA;eA().setInt32(t+4,A,!0),eA().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_6ddd609b62940d55:function(t,o){throw new Error(vr(t,o))},__wbg__wbg_cb_unref_6b5b6b8576d35cb1:function(t){Fe(t)._wbg_cb_unref()},__wbg_attrs_eb268b5ce109b817:function(t){let o=Fe(t).attrs;return rA(o)},__wbg_call_2d781c1f4d5c0ef8:function(){return kr(function(t,o,i){let e=Fe(t).call(Fe(o),Fe(i));return rA(e)},arguments)},__wbg_call_e133b57c9155d22c:function(){return kr(function(t,o){let i=Fe(t).call(Fe(o));return rA(i)},arguments)},__wbg_content_54fb4ecf37d1b68a:function(t){let o=Fe(t).content;return rA(o)},__wbg_debug_10ca7029b12f8d85:function(t,o,i,e){Fe(t).debug(Fe(o),i===0?void 0:vr(i,e))},__wbg_done_08ce71ee07e3bd17:function(t){return Fe(t).done},__wbg_entries_e8a20ff8c9757101:function(t){let o=Object.entries(Fe(t));return rA(o)},__wbg_error_9cce413345f88385:function(t,o,i,e){Fe(t).error(Fe(o),i===0?void 0:vr(i,e))},__wbg_from_4bdf88943703fd48:function(t){let o=Array.from(Fe(t));return rA(o)},__wbg_getOurIdentity_85a51d9b5b46c006:function(){return kr(function(t){let o=Fe(t).getOurIdentity();return rA(o)},arguments)},__wbg_getOurRegistrationId_6d41d022f3c2af8a:function(){return kr(function(t){let o=Fe(t).getOurRegistrationId();return rA(o)},arguments)},__wbg_getRandomValues_3f44b700395062e5:function(){return kr(function(t,o){globalThis.crypto.getRandomValues(GB(t,o))},arguments)},__wbg_get_326e41e095fb2575:function(){return kr(function(t,o){let i=Reflect.get(Fe(t),Fe(o));return rA(i)},arguments)},__wbg_get_3ef1eba1850ade27:function(){return kr(function(t,o){let i=Reflect.get(Fe(t),Fe(o));return rA(i)},arguments)},__wbg_get_a8ee5c45dabc1b3b:function(t,o){let i=Fe(t)[o>>>0];return rA(i)},__wbg_get_unchecked_329cfe50afab7352:function(t,o){let i=Fe(t)[o>>>0];return rA(i)},__wbg_get_with_ref_key_6412cf3094599694:function(t,o){let i=Fe(t)[Fe(o)];return rA(i)},__wbg_has_926ef2ff40b308cf:function(){return kr(function(t,o){return Reflect.has(Fe(t),Fe(o))},arguments)},__wbg_info_b728e87a346ff6a2:function(t,o,i,e){Fe(t).info(Fe(o),i===0?void 0:vr(i,e))},__wbg_instanceof_ArrayBuffer_101e2bf31071a9f6:function(t){let o;try{o=Fe(t)instanceof ArrayBuffer}catch{o=!1}return o},__wbg_instanceof_Map_f194b366846aca0c:function(t){let o;try{o=Fe(t)instanceof Map}catch{o=!1}return o},__wbg_instanceof_Object_be1962063fcc0c9f:function(t){let o;try{o=Fe(t)instanceof Object}catch{o=!1}return o},__wbg_instanceof_Promise_7c3bdd7805c2c6e6:function(t){let o;try{o=Fe(t)instanceof Promise}catch{o=!1}return o},__wbg_instanceof_Uint8Array_740438561a5b956d:function(t){let o;try{o=Fe(t)instanceof Uint8Array}catch{o=!1}return o},__wbg_internalbinarynode_new:function(t){let o=KB.__wrap(t);return rA(o)},__wbg_isArray_33b91feb269ff46e:function(t){return Array.isArray(Fe(t))},__wbg_isSafeInteger_ecd6a7f9c3e053cd:function(t){return Number.isSafeInteger(Fe(t))},__wbg_isTrustedIdentity_8beedd37958ed6af:function(){return kr(function(t,o,i,e,a){let A=Fe(t).isTrustedIdentity(vr(o,i),Fe(e),a>>>0);return rA(A)},arguments)},__wbg_iterator_d8f549ec8fb061b1:function(){return rA(Symbol.iterator)},__wbg_keys_ab0d051a1c55236d:function(t){let o=Object.keys(Fe(t));return rA(o)},__wbg_length_b3416cf66a5452c8:function(t){return Fe(t).length},__wbg_length_ea16607d7b61445b:function(t){return Fe(t).length},__wbg_level_4b50b181832c5acf:function(t,o){let i=Fe(o).level,e=jn(i,ie.__wbindgen_export,ie.__wbindgen_export2),a=KA;eA().setInt32(t+4,a,!0),eA().setInt32(t+0,e,!0)},__wbg_loadPreKey_db3458e3339f7328:function(){return kr(function(t,o){let i=Fe(t).loadPreKey(o>>>0);return rA(i)},arguments)},__wbg_loadSenderKey_fd075b57283fd71b:function(){return kr(function(t,o,i){let e=Fe(t).loadSenderKey(vr(o,i));return rA(e)},arguments)},__wbg_loadSession_8564b20b09724f27:function(){return kr(function(t,o,i){let e=Fe(t).loadSession(vr(o,i));return rA(e)},arguments)},__wbg_loadSignedPreKey_3d5c6c6819f3adf3:function(){return kr(function(t,o){let i=Fe(t).loadSignedPreKey(o>>>0);return rA(i)},arguments)},__wbg_new_5f486cdf45a04d78:function(t){let o=new Uint8Array(Fe(t));return rA(o)},__wbg_new_7dce085c132c6f91:function(t,o){let i=new TypeError(vr(t,o));return rA(i)},__wbg_new_a70fbab9066b301f:function(){let t=new Array;return rA(t)},__wbg_new_ab79df5bd7c26067:function(){let t=new Object;return rA(t)},__wbg_new_from_slice_22da9388ac046e50:function(t,o){let i=new Uint8Array(GB(t,o));return rA(i)},__wbg_new_typed_aaaeaf29cf802876:function(t,o){try{var i={a:t,b:o},e=(A,r)=>{let s=i.a;i.a=0;try{return fxe(s,i.b,A,r)}finally{i.a=s}};let a=new Promise(e);return rA(a)}finally{i.a=i.b=0}},__wbg_new_with_length_3259a525196bd8cc:function(t){let o=new Array(t>>>0);return rA(o)},__wbg_new_with_length_825018a1616e9e55:function(t){let o=new Uint8Array(t>>>0);return rA(o)},__wbg_next_11b99ee6237339e3:function(){return kr(function(t){let o=Fe(t).next();return rA(o)},arguments)},__wbg_next_e01a967809d1aa68:function(t){let o=Fe(t).next;return rA(o)},__wbg_parse_e9eddd2a82c706eb:function(){return kr(function(t,o){let i=JSON.parse(vr(t,o));return rA(i)},arguments)},__wbg_prototypesetcall_d62e5099504357e6:function(t,o,i){Uint8Array.prototype.set.call(GB(t,o),Fe(i))},__wbg_push_e87b0e732085a946:function(t,o){return Fe(t).push(Fe(o))},__wbg_queueMicrotask_0c399741342fb10f:function(t){let o=Fe(t).queueMicrotask;return rA(o)},__wbg_queueMicrotask_a082d78ce798393e:function(t){queueMicrotask(Fe(t))},__wbg_removePreKey_c0b0a066eb6f2e1e:function(){return kr(function(t,o){let i=Fe(t).removePreKey(o>>>0);return rA(i)},arguments)},__wbg_resolve_ae8d83246e5bcc12:function(t){let o=Promise.resolve(Fe(t));return rA(o)},__wbg_senderkeydistributionmessage_new:function(t){let o=Dh.__wrap(t);return rA(o)},__wbg_sessionrecord_new:function(t){let o=xB.__wrap(t);return rA(o)},__wbg_set_282384002438957f:function(t,o,i){Fe(t)[o>>>0]=mA(i)},__wbg_set_6be42768c690e380:function(t,o,i){Fe(t)[mA(o)]=mA(i)},__wbg_set_7eaa4f96924fd6b3:function(){return kr(function(t,o,i){return Reflect.set(Fe(t),Fe(o),Fe(i))},arguments)},__wbg_set_8c0b3ffcf05d61c2:function(t,o,i){Fe(t).set(GB(o,i))},__wbg_static_accessor_GLOBAL_8adb955bd33fac2f:function(){let t=typeof global>"u"?null:global;return Yn(t)?0:rA(t)},__wbg_static_accessor_GLOBAL_THIS_ad356e0db91c7913:function(){let t=typeof globalThis>"u"?null:globalThis;return Yn(t)?0:rA(t)},__wbg_static_accessor_SELF_f207c857566db248:function(){let t=typeof self>"u"?null:self;return Yn(t)?0:rA(t)},__wbg_static_accessor_WINDOW_bb9f1ba69d61b386:function(){let t=typeof window>"u"?null:window;return Yn(t)?0:rA(t)},__wbg_storeSenderKey_8a6c9ec5f7e1cd2e:function(){return kr(function(t,o,i,e){let a=Fe(t).storeSenderKey(vr(o,i),Fe(e));return rA(a)},arguments)},__wbg_storeSessionRaw_09b5cc73064d12d8:function(){return kr(function(t,o,i,e){let a=Fe(t).storeSessionRaw(vr(o,i),Fe(e));return rA(a)},arguments)},__wbg_storeSession_4d419555ce654965:function(){return kr(function(t,o,i,e){let a=Fe(t).storeSession(vr(o,i),mA(e));return rA(a)},arguments)},__wbg_tag_33cfe8e9ee66b4db:function(t,o){let i=Fe(o).tag,e=jn(i,ie.__wbindgen_export,ie.__wbindgen_export2),a=KA;eA().setInt32(t+4,a,!0),eA().setInt32(t+0,e,!0)},__wbg_then_098abe61755d12f6:function(t,o){let i=Fe(t).then(Fe(o));return rA(i)},__wbg_then_9e335f6dd892bc11:function(t,o,i){let e=Fe(t).then(Fe(o),Fe(i));return rA(e)},__wbg_trace_58264fbce2ceb5e6:function(t,o,i,e){Fe(t).trace(Fe(o),i===0?void 0:vr(i,e))},__wbg_value_21fc78aab0322612:function(t){let o=Fe(t).value;return rA(o)},__wbg_warn_db531770752932a9:function(t,o,i,e){Fe(t).warn(Fe(o),i===0?void 0:vr(i,e))},__wbindgen_cast_0000000000000001:function(t,o){let i=yxe(t,o,ie.__wasm_bindgen_func_elem_694,Bxe);return rA(i)},__wbindgen_cast_0000000000000002:function(t){return rA(t)},__wbindgen_cast_0000000000000003:function(t){return rA(t)},__wbindgen_cast_0000000000000004:function(t,o){let i=GB(t,o);return rA(i)},__wbindgen_cast_0000000000000005:function(t,o){let i=vr(t,o);return rA(i)},__wbindgen_cast_0000000000000006:function(t){let o=BigInt.asUintN(64,t);return rA(o)},__wbindgen_object_clone_ref:function(t){let o=Fe(t);return rA(o)},__wbindgen_object_drop_ref:function(t){mA(t)}}}}function Bxe(n,t,o){try{let a=ie.__wbindgen_add_to_stack_pointer(-16);ie.__wasm_bindgen_func_elem_699(a,n,t,rA(o));var i=eA().getInt32(a+0,!0),e=eA().getInt32(a+4,!0);if(e)throw mA(i)}finally{ie.__wbindgen_add_to_stack_pointer(16)}}function fxe(n,t,o,i){ie.__wasm_bindgen_func_elem_1248(n,t,rA(o),rA(i))}var C$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_expandedappstatekeys_free(n>>>0,1)),B$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_groupcipher_free(n>>>0,1)),f$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_groupsessionbuilder_free(n>>>0,1)),Q$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_internalbinarynode_free(n>>>0,1)),y$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_lthashantitampering_free(n>>>0,1)),yL=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_lthashstate_free(n>>>0,1)),m$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_noisesession_free(n>>>0,1)),mL=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_protocoladdress_free(n>>>0,1)),S$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_senderkeydistributionmessage_free(n>>>0,1)),w$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_senderkeyname_free(n>>>0,1)),SL=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_senderkeyrecord_free(n>>>0,1)),D$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_sessionbuilder_free(n>>>0,1)),O$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_sessioncipher_free(n>>>0,1)),b$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ie.__wbg_sessionrecord_free(n>>>0,1));function rA(n){LB===jg.length&&jg.push(jg.length+1);let t=LB;return LB=jg[t],jg[t]=n,t}function aI(n,t){if(!(n instanceof t))throw new Error(`expected instance of ${t.name}`)}var M$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>n.dtor(n.a,n.b));function DL(n){let t=typeof n;if(t=="number"||t=="boolean"||n==null)return`${n}`;if(t=="string")return`"${n}"`;if(t=="symbol"){let e=n.description;return e==null?"Symbol":`Symbol(${e})`}if(t=="function"){let e=n.name;return typeof e=="string"&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(n)){let e=n.length,a="[";e>0&&(a+=DL(n[0]));for(let A=1;A1)i=o[1];else return toString.call(n);if(i=="Object")try{return"Object("+JSON.stringify(n)+")"}catch{return"Object"}return n instanceof Error?`${n.name}: ${n.message} -${n.stack}`:i}function Qxe(n){n<1028||(jg[n]=LB,LB=n)}function GB(n,t){return n=n>>>0,Sh().subarray(n/1,n/1+t)}var Kl=null;function eA(){return(Kl===null||Kl.buffer.detached===!0||Kl.buffer.detached===void 0&&Kl.buffer!==ie.memory.buffer)&&(Kl=new DataView(ie.memory.buffer)),Kl}function vr(n,t){return n=n>>>0,Sxe(n,t)}var FB=null;function Sh(){return(FB===null||FB.byteLength===0)&&(FB=new Uint8Array(ie.memory.buffer)),FB}function Fe(n){return jg[n]}function kr(n,t){try{return n.apply(this,t)}catch(o){ie.__wbindgen_export3(rA(o))}}var jg=new Array(1024).fill(void 0);jg.push(void 0,null,!0,!1);var LB=jg.length;function Yn(n){return n==null}function yxe(n,t,o,i){let e={a:n,b:t,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let r=e.a;e.a=0;try{return i(r,e.b,...A)}finally{e.a=r,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,M$.unregister(e))},M$.register(a,e,e),a}function vt(n,t){let o=t(n.length*1,1)>>>0;return Sh().set(n,o/1),KA=n.length,o}function _$(n,t){let o=t(n.length*4,4)>>>0,i=eA();for(let e=0;e>>0;return Sh().subarray(s,s+r.length).set(r),KA=r.length,s}let i=n.length,e=t(i,1)>>>0,a=Sh(),A=0;for(;A127)break;a[e+A]=r}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let r=Sh().subarray(e+A,e+i),s=UB.encodeInto(n,r);A+=s.written,e=o(e,i,A,1)>>>0}return KA=A,e}function mA(n){let t=Fe(n);return Qxe(n),t}var bD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});bD.decode();var mxe=2146435072,wL=0;function Sxe(n,t){return wL+=t,wL>=mxe&&(bD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),bD.decode(),wL=t),bD.decode(Sh().subarray(n,n+t))}var UB=new TextEncoder;"encodeInto"in UB||(UB.encodeInto=function(n,t){let o=UB.encode(n);return t.set(o),{read:n.length,written:o.length}});var KA=0,wxe,ie;function Dxe(n,t){return ie=n.exports,wxe=t,Kl=null,FB=null,ie}function N$(n){if(ie!==void 0)return ie;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=Cxe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,t);return Dxe(o,n)}var Oxe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function R$(n){let t=atob(n),o=new Uint8Array(t.length);for(let i=0;in.length===33?n:Buffer.concat([Jg,n]),Dr={generateKeyPair:()=>{let{pubKey:n,privKey:t}=oI.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(n.slice(1))}},sharedKey:(n,t)=>{let o=oI.calculateAgreement($o(t),n);return Buffer.from(o)},sign:(n,t)=>oI.calculateSignature(n,t),verify:(n,t,o)=>{try{return oI.verifySignature($o(n),t,o),!0}catch{return!1}}},PD=(n,t)=>{let o=Dr.generateKeyPair(),i=$o(o.public),e=Dr.sign(n.private,i);return{keyPair:o,signature:e,keyId:t}},v$=16;function xl(n,t,o,i){let e=OL("aes-256-gcm",t,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function Yl(n,t,o,i){let e=bL("aes-256-gcm",t,o),a=n.slice(0,n.length-v$),A=n.slice(n.length-v$);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function P$(n,t,o){let i=OL("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function G$(n,t,o){let i=bL("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function F$(n,t){return vxe(n.subarray(16),t,n.subarray(0,16))}function vxe(n,t,o){let i=bL("aes-256-cbc",t,o);return Buffer.concat([i.update(n),i.final()])}function L$(n,t){let o=kxe(16),i=OL("aes-256-cbc",t,o);return Buffer.concat([o,i.update(n),i.final()])}function qn(n,t,o="sha256"){return Rxe(o,t).update(n).digest()}function bh(n){return Nxe("sha256").update(n).digest()}async function GD(n,t){let i=new TextEncoder().encode(n),e=new Uint8Array(t instanceof Uint8Array?t:new Uint8Array(t)),a=await k$.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await k$.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var jB={replacer:(n,t)=>Buffer.isBuffer(t)||t instanceof Uint8Array||t?.type==="Buffer"?{type:"Buffer",data:Buffer.from(t?.data||t).toString("base64")}:t,reviver:(n,t)=>{if(typeof t=="object"&&t!==null&&t.type==="Buffer"&&typeof t.data=="string")return Buffer.from(t.data,"base64");if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(t);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return t}},Mh=(n,t="me")=>(n?.fromMe?t:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",K$=n=>n==null||n==="",Gxe=n=>{let o=(YB(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},x$=n=>{let t=new Uint8Array(n);if(t.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=t[t.length-1];if(o>t.length)throw new Error(`unpad given ${t.length} bytes, but pad is ${o}`);return new Uint8Array(t.buffer,t.byteOffset,t.length-o)},Y$=n=>(n.sort(),"2:"+bh(Buffer.from(n.join(""))).toString("base64").slice(0,6)),_h=n=>Gxe(ne.Message.encode(n).finish()),j$=()=>Uint16Array.from(YB(2))[0]&16383,qg=(n,t=4)=>{let o=n,i=new Uint8Array(t);for(let e=t-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},qr=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,va=(n=new Date)=>Math.floor(n.getTime()/1e3);var JB=n=>J$(n).delay,J$=n=>{let t=new Error().stack,o,i;return{delay:new Promise((A,r)=>{o=setTimeout(A,n),i=r}),cancel:()=>{clearTimeout(o),i(new FD.Boom("Cancelled",{statusCode:500,data:{stack:t}}))}}};async function Th(n,t){if(!n)return new Promise(t);let o=new Error().stack,{delay:i,cancel:e}=J$(n);return new Promise((A,r)=>{i.then(()=>r(new FD.Boom("Timed Out",{statusCode:tr.timedOut,data:{stack:o}}))).catch(s=>r(s)),t(A,r)}).finally(e)}var zr=n=>{let t=Buffer.alloc(44);if(t.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=fA(n);e?.user&&(t.write(e.user,8),t.write("@c.us",8+e.user.length))}return YB(16).copy(t,28),"3EB0"+Pxe("sha256").update(t).digest().toString("hex").toUpperCase().substring(0,18)},ML=()=>"3EB0"+YB(18).toString("hex").toUpperCase();function _L(n,t){return async(o,i)=>{let e,a;await Th(i,(A,r)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&r(g?.error||new FD.Boom("Connection Closed",{statusCode:tr.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(t,e)}).finally(()=>{n.off(t,e),n.off("connection.update",a)})}}var q$=n=>_L(n,"connection.update");var z$=()=>{let n=YB(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},Fxe={sender:ne.WebMessageInfo.Status.SERVER_ACK,played:ne.WebMessageInfo.Status.PLAYED,read:ne.WebMessageInfo.Status.READ,"read-self":ne.WebMessageInfo.Status.READ},V$=n=>{let t=Fxe[n];return typeof n>"u"?ne.WebMessageInfo.Status.DELIVERY_ACK:t},Lxe={conflict:tr.connectionReplaced},W$=n=>{let[t]=vs(n),o=t?.tag||"unknown",i=+(n.attrs.code||Lxe[o]||tr.badSession);return i===tr.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},Z$=({tag:n,attrs:t})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":t.reason==="timeout"?o="timeout":o="terminate";break;case"preaccept":o="preaccept";break;case"transport":o="transport";break;case"relaylatency":o="relaylatency";break;case"reject":o="reject";break;case"accept":o="accept";break;default:o="ringing";break}return o},U$="Unexpected server response: ",X$=n=>{let t=500;if(n?.message?.includes(U$)){let o=+n?.message.slice(U$.length);!Number.isNaN(o)&&o>=400&&(t=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(t=408);return t};function LD(n){for(let t in n)typeof n[t]>"u"&&delete n[t];return n}var H$="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function $$(n){let t=0,o=0,i=[];for(let e of n)for(t=t<<8|e&255,o+=8;o>=5;)i.push(H$.charAt(t>>>o-5&31)),o-=5;return o>0&&i.push(H$.charAt(t<<5-o&31)),i.join("")}function eee(n){return ne.Message.encode(n).finish()}var jl=ze(jr(),1);var Uxe=async(n,t)=>qA(n)||Ea(n)?n:await t.lidMapping.getLIDForPN(n)||n,Hxe=async(n,t,o,i,e)=>{let{senderAlt:a}=HD(n);if(a&&qA(a)&&Tt(t)&&i===t)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:t}]),await o.migrateSession(t,a),e.debug({sender:t,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:t,senderAlt:a,error:A},"Failed to store LID mapping")}},UD="Message absent from node",Aee="Key used already or never filled",tee="Your account has been restricted",Kxe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},Jl={SenderReachoutTimelocked:463,ParsingError:487,UnrecognizedStanza:488,UnrecognizedStanzaClass:489,UnrecognizedStanzaType:490,InvalidProtobuf:491,InvalidHostedCompanionStanza:493,MissingMessageSecret:495,SignalErrorOldCounter:496,MessageDeletedOnPeer:499,UnhandledError:500,UnsupportedAdminRevoke:550,UnsupportedLIDGroup:551,DBOperationFailed:552},TL={MessageAccountRestriction:"463",SmaxInvalid:"479"},HD=n=>{let t,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(t=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(t=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:t,recipientAlt:o}};function NL(n,t,o){let i,e,a,A=!1,r=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!r)throw new jl.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new jl.Boom("Invalid message stanza: missing from attribute",{data:n});let I=HD(n),d=m=>kt(m,t),B=m=>kt(m,o);if(Tt(s)||qA(s)||Ea(s)||wr(s)){if(c&&!mh(c)){if(!d(s)&&!B(s))throw new jl.Boom("receipient present, but msg not from me",{data:n});(d(s)||B(s))&&(A=!0),e=c}else(d(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(Jr(s)){if(!g)throw new jl.Boom("No participant in group message");(d(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(PB(s)){if(!g)throw new jl.Boom("No participant in group message");let m=d(g);Yg(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(tI(s))i="newsletter",e=s,a=s,(d(s)||B(s))&&(A=!0);else throw new jl.Boom("Unknown message type",{data:n});let f=n?.attrs?.notify,Q={remoteJid:e,remoteJidAlt:Jr(e)?void 0:I.senderAlt,remoteJidUsername:Jr(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:r,participant:g,participantAlt:Jr(e)?I.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:I.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:Q,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:f,broadcast:PB(s)};return Q.fromMe&&(y.status=ne.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var ree=(n,t,o,i,e)=>{let{fullMessage:a,author:A,sender:r}=NL(n,t,o);return{fullMessage:a,category:n.attrs.category,author:A,async decrypt(){let s=0;if(Array.isArray(n.content))for(let{tag:g,attrs:c,content:I}of n.content){if(g==="verified_name"&&I instanceof Uint8Array){let f=ne.VerifiedNameCertificate.decode(I),Q=ne.VerifiedNameCertificate.Details.decode(f.details);a.verifiedBizName=Q.verifiedName}if(g==="unavailable"&&c.type==="view_once"&&(a.key.isViewOnce=!0),c.count&&g==="enc"&&(a.retryCount=Number(c.count)),g!=="enc"&&g!=="plaintext"||!(I instanceof Uint8Array))continue;s+=1;let d,B=await Uxe(A,i);g!=="plaintext"&&await Hxe(n,A,i,B,e);try{let f=g==="plaintext"?"plaintext":c.type;switch(f){case"skmsg":d=await i.decryptGroupMessage({group:r,authorJid:A,msg:I});break;case"pkmsg":case"msg":d=await i.decryptMessage({jid:B,type:f,ciphertext:I});break;case"plaintext":d=I;break;default:throw new Error(`Unknown e2e type: ${f}`)}let Q=ne.Message.decode(f!=="plaintext"?x$(d):d);if(Q=Q.deviceSentMessage?.message||Q,Q.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:Q.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,Q):a.message=Q}catch(f){let Q={key:a.key,err:f,messageType:g==="plaintext"?"plaintext":c.type,sender:r,author:A,isSessionRecordError:xxe(f)};e.error(Q,"failed to decrypt message"),a.messageStubType=ne.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[f.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=ne.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[UD])}}};function xxe(n){let t=n?.message||n?.toString()||"";return Kxe.sessionRecordErrors.some(o=>t.includes(o))}var rc=ze(jr(),1);import{randomBytes as JU}from"crypto";import{promises as qU}from"fs";var Vn=ze(jr(),1);import{exec as xze}from"child_process";import*as yo from"crypto";import{once as CE}from"events";import{createReadStream as Fb,createWriteStream as FU,promises as fE}from"fs";import{tmpdir as Mne}from"os";import{join as Pb}from"path";import{Readable as Ff,Transform as Yze}from"stream";import{URL as LU}from"url";var UU=()=>Mne(),_ne=async()=>{let[n,t]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(pre(),dre)).catch(()=>{})]);if(t)return{sharp:t};if(n)return{jimp:n};throw new Vn.Boom("No image processing library available")},jze=n=>`WhatsApp ${Kne[n]} Keys`,Lb=async(n,t,o)=>{let{stream:i}=await Lf(n);o?.debug("got stream for raw upload");let e=yo.createHash("sha256"),a=Pb(Mne(),t+zr()),A=FU(a),r=0;try{for await(let g of i)r+=g.length,e.update(g),A.write(g)||await CE(A,"drain");A.end(),await CE(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:r}}catch(s){A.destroy(),i.destroy();try{await fE.unlink(a)}catch{}throw s}};async function Tne(n,t){if(!n)throw new Vn.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=Jn(n,112,{info:jze(t)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var Jze=async(n,t,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${t}`;xze(A,r=>{r?a(r):e()})}),HU=async(n,t=32)=>{n instanceof Ff&&(n=await Gb(n));let o=await _ne();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(t).jpeg({quality:50}).toBuffer(),original:{width:e.width,height:e.height}}}else if("jimp"in o&&typeof o.jimp?.Jimp=="object"){let i=await o.jimp.Jimp.read(n),e={width:i.width,height:i.height};return{buffer:await i.resize({w:t,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new Vn.Boom("No image processing library available")},qze=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),Ub=async(n,t)=>{let o,{width:i=640,height:e=640}=t||{};if(Buffer.isBuffer(n))o=n;else{let{stream:r}=await Lf(n);o=await Gb(r)}let a=await _ne(),A;if("sharp"in a&&typeof a.sharp?.default=="function")A=a.sharp.default(o).resize(i,e).jpeg({quality:50}).toBuffer();else if("jimp"in a&&typeof a.jimp?.Jimp=="function"){let r=await a.jimp.Jimp.read(o),s=Math.min(r.width,r.height);A=r.crop({x:0,y:0,w:s,h:s}).resize({w:i,h:e,mode:a.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50})}else throw new Vn.Boom("No image processing library available");return{img:await A}};async function Nne(n){let t=await Promise.resolve().then(()=>(One(),Dne)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await t.parseBuffer(n,void 0,i):typeof n=="string"?o=await t.parseFile(n,i):o=await t.parseStream(n,void 0,i),o.format.duration}async function Rne(n,t){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let d=Fb(n);i=await Gb(d)}else i=await Gb(n);let a=(await o(i)).getChannelData(0),A=64,r=Math.floor(a.length/A),s=[];for(let d=0;dd*g);return new Uint8Array(c.map(d=>Math.floor(100*d)))}catch(o){t?.debug("Failed to generate waveform: "+o)}}var bne=n=>{let t=new Ff({read:()=>{}});return t.push(n),t.push(null),t},Gb=async n=>{let t=[];for await(let o of n)t.push(o);return n.destroy(),Buffer.concat(t)},Lf=async(n,t)=>{if(Buffer.isBuffer(n))return{stream:bne(n),type:"buffer"};if("stream"in n)return{stream:n.stream,type:"readable"};let o=n.url.toString();if(o.startsWith("data:")){let i=Buffer.from(o.split(",")[1],"base64");return{stream:bne(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await Hb(n.url,t),type:"remote"}:{stream:Fb(n.url),type:"file"}};async function kne(n,t,o){let i,e;if(t==="image"){let{buffer:a,original:A}=await HU(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(t==="video"){let a=Pb(UU(),zr()+".jpg");try{await Jze(n,a,"00:00:00",{width:32,height:32}),i=(await fE.readFile(a)).toString("base64"),await fE.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var Hb=async(n,t={})=>{let o=await fetch(n.toString(),{dispatcher:t.dispatcher,method:"GET",headers:t.headers});if(!o.ok)throw new Vn.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof Ff?o.body:Ff.fromWeb(o.body)},vne=async(n,t,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await Lf(n,e);o?.debug("fetched media stream");let r=yo.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await Tne(r,t),I=Pb(UU(),t+zr()+"-enc"),d=FU(I),B,f;i&&(f=Pb(UU(),t+zr()+"-original"),B=FU(f));let Q=0,y=yo.createCipheriv("aes-256-cbc",s,g),m=yo.createHmac("sha256",c).update(g),T=yo.createHash("sha256"),_=yo.createHash("sha256"),R=async H=>{_.update(H),m.update(H),d.write(H)||await CE(d,"drain")};try{for await(let K of a){if(Q+=K.length,A==="remote"&&e?.maxContentLength&&Q+K.length>e.maxContentLength)throw new Vn.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(K)||await CE(B,"drain")),T.update(K),await R(y.update(K))}await R(y.final());let H=m.digest().slice(0,10);_.update(H);let F=T.digest(),L=_.digest();d.write(H);let q=CE(d,"finish"),z=B?CE(B,"finish"):Promise.resolve();return d.end(),B?.end?.(),a.destroy(),await q,await z,o?.debug("encrypted data successfully"),{mediaKey:r,originalFilePath:f,encFilePath:I,mac:H,fileEncSha256:L,fileSha256:F,fileLength:Q}}catch(H){d.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),T.destroy(),_.destroy(),a.destroy();try{await fE.unlink(I),f&&await fE.unlink(f)}catch(F){o?.error({err:F},"failed deleting tmp files")}throw H}},KU="mmg.whatsapp.net",BE=16,GU=n=>Math.floor(n/BE)*BE,Uf=(n,t=KU)=>`https://${t}${n}`,zze=n=>{if(n)try{return new LU(n).host}catch{return}},QE=async({mediaKey:n,directPath:t,url:o},i,e={})=>{let a=e.host??zze(o),A=t?Uf(t,a):o;if(!A)throw new Vn.Boom("No valid media URL or directPath present in message",{statusCode:400});let r=await Tne(n,i);return Vze(A,r,e)},Vze=async(n,{cipherKey:t,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,r=0,s=!1;if(i){let m=GU(i||0);m&&(r=m-BE,A=m,s=!0)}let g=e?GU(e||0)+BE:void 0,c=a?.headers?a.headers:void 0,I={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:Hf};(r||g)&&(I.Range=`bytes=${r}-`,g&&(I.Range+=g));let d=await Hb(n,{...a||{},headers:I}),B=Buffer.from([]),f,Q=(m,T)=>{if(i||e){let _=A>=i?void 0:Math.max(i-A,0),R=A+m.lengththis.push(F)),_()}catch(F){_(F)}},final(m){try{Q(f.final(),T=>this.push(T)),m()}catch(T){m(T)}}});return d.pipe(y,{end:!0})};var Wze=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",Pne=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new LU(n),r=A.protocol==="https:"?await import("https"):await import("http"),g=(await fE.stat(t)).size;return new Promise((c,I)=>{let d=r.request({hostname:A.hostname,port:A.port||(A.protocol==="https:"?443:80),path:A.pathname+A.search,method:"POST",headers:{...o,"Content-Length":g},agent:e,timeout:i},f=>{if(f.statusCode&&f.statusCode>=300&&f.statusCode<400&&f.headers.location){f.resume();let y=new LU(f.headers.location,n).toString();c(Pne({url:y,filePath:t,headers:o,timeoutMs:i,agent:e},a+1));return}let Q="";f.on("data",y=>Q+=y),f.on("end",()=>{try{c(JSON.parse(Q))}catch{c(void 0)}})});d.on("error",I),d.on("timeout",()=>{d.destroy(),I(new Error("Upload timeout"))});let B=Fb(t);B.pipe(d),B.on("error",f=>{d.destroy(),I(f)})})},Zze=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e})=>{let a=Fb(t),A=Ff.toWeb(a),r=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...r?{dispatcher:r}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},Xze=async(n,t)=>Wze()?(t?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),Pne(n)):(t?.debug("Using web-standard Fetch API for upload"),Zze(n)),Gne=({customUploadHosts:n,fetchAgent:t,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:r,timeoutMs:s})=>{let g=await e(!1),c,I=[...n,...g.hosts];r=qze(r);let B={...(()=>{let f=i?.headers;return f?Array.isArray(f)?Object.fromEntries(f):f:{}})(),"Content-Type":"application/octet-stream",Origin:Hf};for(let{hostname:f}of I){o.debug(`uploading to "${f}"`);let Q=encodeURIComponent(g.auth),y=`https://${f}${YU[A]}/${r}?auth=${Q}&token=${r}`,m;try{if(m=await Xze({url:y,filePath:a,headers:B,timeoutMs:s,agent:t},o),m?.url||m?.direct_path){c={mediaUrl:m.url,directPath:m.direct_path,meta_hmac:m.meta_hmac,fbid:m.fbid,ts:m.ts};break}else throw g=await e(!0),new Error(`upload failed, reason: ${JSON.stringify(m)}`)}catch(T){let _=f===I[g.hosts.length-1]?.hostname;o.warn({trace:T?.stack,uploadResult:m},`Error in uploading to ${f} ${_?"":", retrying..."}`)}}if(!c)throw new Vn.Boom("Media upload failed on all hosts",{statusCode:500});return c},Fne=n=>Jn(n,32,{info:"WhatsApp Media Retry Notification"}),Lne=(n,t,o)=>{let i={stanzaId:n.id},e=ne.ServerErrorReceipt.encode(i).finish(),a=yo.randomBytes(12),A=Fne(t),r=xl(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:CA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:r},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},Une=n=>{let t=le(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:t.attrs.jid,fromMe:t.attrs.from_me==="true",participant:t.attrs.participant}},i=le(n,"error");if(i){let e=+i.attrs.code;o.error=new Vn.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:xU(e)})}else{let e=le(n,"encrypt"),a=ka(e,"enc_p"),A=ka(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new Vn.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},Hne=({ciphertext:n,iv:t},o,i)=>{let e=Fne(o),a=Yl(n,e,t,Buffer.from(i));return ne.MediaRetryNotification.decode(a)},xU=n=>$ze[n],$ze={[ne.MediaRetryNotification.ResultType.SUCCESS]:200,[ne.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[ne.MediaRetryNotification.ResultType.NOT_FOUND]:404,[ne.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as eVe}from"crypto";var AVe=[{f:1},{f:3,s:[{f:2},{f:3},{f:8},{f:11},{f:17,s:[{f:21},{f:22}]},{f:25}]},{f:4,s:[{f:1},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:5,s:[{f:3},{f:4},{f:5},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:6,s:[{f:1},{f:17,s:[{f:21},{f:22}]},{f:30}]},{f:7,s:[{f:2},{f:7},{f:10},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:8,s:[{f:2},{f:7},{f:9},{f:17,s:[{f:21},{f:22}]},{f:21}]},{f:9,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:12,s:[{f:1},{f:2},{f:14,m:!0},{f:15}]},{f:18,s:[{f:6},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:26,s:[{f:4},{f:5},{f:8},{f:13},{f:17,s:[{f:21},{f:22}]}]},{f:28,s:[{f:1},{f:2},{f:4},{f:5},{f:6},{f:7,s:[{f:21},{f:22}]}]},{f:37,s:[{f:1,m:!0}]},{f:49,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:53,s:[{f:1,m:!0}]},{f:55,s:[{f:1,m:!0}]},{f:58,s:[{f:1,m:!0}]},{f:59,s:[{f:1,m:!0}]},{f:60,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:64,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:66,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:74,s:[{f:1,m:!0}]},{f:87,s:[{f:1,m:!0}]},{f:88,s:[{f:1},{f:2,s:[{f:1}]},{f:3,s:[{f:21},{f:22}]}]},{f:92,s:[{f:1,m:!0}]},{f:93,s:[{f:1,m:!0}]},{f:94,s:[{f:1,m:!0}]}],Yne=n=>{let t=new Map;for(let o of n)t.set(o.f,{m:o.m,children:o.s?Yne(o.s):void 0});return t},tVe=Yne(AVe),rVe=new Map,aVe="Report Token",Kb={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},xb=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,iVe=(n,t,o,i,e)=>{let a=Buffer.concat([Buffer.from(t,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return Jn(e,32,{info:a.toString("latin1")})},jne=(n,t)=>{let o=[],i=0;for(;i>3,A=e.value&7,r=i;i+=e.bytes;let s=t.get(a),g=I=>I>n.length?!1:(o.push({num:a,bytes:n.subarray(r,I)}),i=I,!0),c=I=>I>n.length?!1:(i=I,!0);if(A===Kb.VARINT){let I=jU(n,i);if(!I.ok)return null;let d=i+I.bytes;if(!s){if(!c(d))return null;continue}if(!g(d))return null;continue}if(A===Kb.FIXED64){let I=i+8;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===Kb.FIXED32){let I=i+4;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===Kb.BYTES){let I=jU(n,i);if(!I.ok)return null;let d=i+I.bytes,B=d+I.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let f=jne(n.subarray(d,B),s.children??rVe);if(f===null)return null;if(f.length>0){let Q=xne(e.value),y=xne(f.length);o.push({num:a,bytes:Buffer.concat([Q,y,f])})}i=B;continue}o.push({num:a,bytes:n.subarray(r,B)}),i=B;continue}return null}return o.length===0?Buffer.alloc(0):(o.sort((e,a)=>e.num-a.num),Buffer.concat(o.map(e=>e.bytes)))},jU=(n,t)=>{let o=0,i=0,e=0;for(;t+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},xne=n=>{let t=[],o=n>>>0;for(;o>127;)t.push(o&127|128),o>>>=7;return t.push(o),Buffer.from(t)},Jne=async(n,t,o)=>{let i=t.messageContextInfo?.messageSecret;if(!i||!o.id)return null;let e=o.fromMe?o.remoteJid:o.participant||o.remoteJid,a=o.fromMe&&o.participant||o.remoteJid,A=iVe(aVe,o.id,e,a,i),r=jne(n,tVe);if(!r||r.length===0)return null;let s=eVe("sha256",A).update(r).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var oVe={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},qne={image:ne.Message.ImageMessage,video:ne.Message.VideoMessage,audio:ne.Message.AudioMessage,sticker:ne.Message.StickerMessage,document:ne.Message.DocumentMessage},nVe=n=>n.match(Ase)?.[0],sVe=async(n,t,o)=>{let i=nVe(n);if(t&&i)try{return await t(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},zne=async n=>{let t;if(typeof n=="number")t=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),t=parseInt(o,16),t}},Kf=async(n,t)=>{let o=t.logger,i;for(let F of tse)F in n&&(i=F);if(!i)throw new rc.Boom("Invalid media type",{statusCode:400});let e={...n,media:n[i]};delete e[i];let a=typeof e.media=="object"&&"url"in e.media&&!!e.media.url&&!!t.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=oVe[i]),a){let F=await t.mediaCache.get(a);if(F){o?.debug({cacheableKey:a},"got media cache hit");let L=ne.Message.decode(F),q=`${i}Message`;return Object.assign(L[q],{...e,media:void 0}),L}}if(!!t.jid&&tI(t.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:F,fileSha256:L,fileLength:q}=await Lb(e.media,t.mediaTypeOverride||i,o),z=L.toString("base64"),{mediaUrl:K,directPath:G}=await t.upload(F,{fileEncSha256B64:z,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});await qU.unlink(F);let V=ne.Message.fromObject({[`${i}Message`]:qne[i].fromObject({url:K,directPath:G,fileSha256:L,fileLength:q,...e,media:void 0})});return e.ptv&&(V.ptvMessage=V.videoMessage,delete V.videoMessage),V.stickerMessage&&(V.stickerMessage.stickerSentTs=Date.now()),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,ne.Message.encode(V).finish())),V}let r=i==="audio"&&typeof e.seconds>"u",s=(i==="image"||i==="video")&&typeof e.jpegThumbnail>"u",g=i==="audio"&&e.ptt===!0&&typeof e.waveform>"u",c=t.backgroundColor&&i==="audio"&&e.ptt===!0,I=r||s,{mediaKey:d,encFilePath:B,originalFilePath:f,fileEncSha256:Q,fileSha256:y,fileLength:m}=await vne(e.media,t.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:I,opts:t.options}),T=Q.toString("base64"),[{mediaUrl:_,directPath:R}]=await Promise.all([(async()=>{let F=await t.upload(B,{fileEncSha256B64:T,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),F})(),(async()=>{try{if(s){let{thumbnail:F,originalImageDimensions:L}=await kne(f,i,t);e.jpegThumbnail=F,!e.width&&L&&(e.width=L.width,e.height=L.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}r&&(e.seconds=await Nne(f),o?.debug("computed audio duration")),g&&(e.waveform=await Rne(f,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await zne(t.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(F){o?.warn({trace:F.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await qU.unlink(B),f&&await qU.unlink(f),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),H=ne.Message.fromObject({[`${i}Message`]:qne[i].fromObject({url:_,directPath:R,mediaKey:d,fileEncSha256:Q,fileSha256:y,fileLength:m,mediaKeyTimestamp:va(),...e,media:void 0})});return e.ptv&&(H.ptvMessage=H.videoMessage,delete H.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,ne.Message.encode(H).finish())),H},gVe=n=>{n=n||0;let t={ephemeralMessage:{message:{protocolMessage:{type:ne.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return ne.Message.fromObject(t)},cVe=(n,t)=>{let o=n.message;if(!o)throw new rc.Boom("no content in message",{statusCode:400});o=ya(o),o=ne.Message.decode(ne.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!t?0:1,i==="conversation"&&(o.extendedTextMessage={text:o[i]},delete o.conversation,i="extendedTextMessage");let a=o?.[i];return e>0?a.contextInfo={forwardingScore:e,isForwarded:!0}:a.contextInfo={},o},Qa=(n,t)=>typeof n=="object"&&n!==null&&t in n&&n[t]!==null&&n[t]!==void 0;function dd(n,t){return typeof n=="object"&&n!==null&&t in n&&n[t]!==null}var IVe=async(n,t)=>{var o,i;let e={};if(Qa(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await sVe(n.text,t.getUrlInfo,t.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let r=A.highQualityThumbnail;r&&(a.thumbnailDirectPath=r.directPath,a.mediaKey=r.mediaKey,a.mediaKeyTimestamp=r.mediaKeyTimestamp,a.thumbnailWidth=r.width,a.thumbnailHeight=r.height,a.thumbnailSha256=r.fileSha256,a.thumbnailEncSha256=r.fileEncSha256)}t.backgroundColor&&(a.backgroundArgb=await zne(t.backgroundColor)),t.font&&(a.font=t.font),e.extendedTextMessage=a}else if(Qa(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new rc.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=ne.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=ne.Message.ContactsArrayMessage.create(n.contacts)}else if(Qa(n,"location"))e.locationMessage=ne.Message.LocationMessage.create(n.location);else if(Qa(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=ne.Message.ReactionMessage.create(n.react);else if(Qa(n,"delete"))e.protocolMessage={key:n.delete,type:ne.Message.ProtocolMessage.Type.REVOKE};else if(Qa(n,"forward"))e=cVe(n.forward,n.force);else if(Qa(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?Yf:0:n.disappearingMessagesInChat;e=gVe(a)}else if(Qa(n,"groupInvite")){if(e.groupInviteMessage={},e.groupInviteMessage.inviteCode=n.groupInvite.inviteCode,e.groupInviteMessage.inviteExpiration=n.groupInvite.inviteExpiration,e.groupInviteMessage.caption=n.groupInvite.text,e.groupInviteMessage.groupJid=n.groupInvite.jid,e.groupInviteMessage.groupName=n.groupInvite.subject,t.getProfilePicUrl){let a=await t.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:t?.options?.dispatcher});if(A.ok){let r=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=r}}}}else if(Qa(n,"pin"))e.pinInChatMessage={},e.messageContextInfo={},e.pinInChatMessage.key=n.pin,e.pinInChatMessage.type=n.type,e.pinInChatMessage.senderTimestampMs=Date.now(),e.messageContextInfo.messageAddOnDurationInSecs=n.type===1?n.time||86400:0;else if(Qa(n,"buttonReply"))switch(n.type){case"template":e.templateButtonReplyMessage={selectedDisplayText:n.buttonReply.displayText,selectedId:n.buttonReply.id,selectedIndex:n.buttonReply.index};break;case"plain":e.buttonsResponseMessage={selectedButtonId:n.buttonReply.id,selectedDisplayText:n.buttonReply.displayText,type:ne.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(dd(n,"ptv")&&n.ptv){let{videoMessage:a}=await Kf({video:n.video},t);e.ptvMessage=a}else if(Qa(n,"product")){let{imageMessage:a}=await Kf({image:n.product.productImage},t);e.productMessage=ne.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(Qa(n,"listReply"))e.listResponseMessage={...n.listReply};else if(Qa(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&t.getCallLink){let A=await t.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?ese:$ne)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||JU(32)},e.eventMessage.name=n.event.name,e.eventMessage.description=n.event.description,e.eventMessage.startTime=a,e.eventMessage.endTime=n.event.endDate?n.event.endDate.getTime()/1e3:void 0,e.eventMessage.isCanceled=n.event.isCancelled??!1,e.eventMessage.extraGuestsAllowed=n.event.extraGuestsAllowed,e.eventMessage.isScheduleCall=n.event.isScheduleCall??!1,e.eventMessage.location=n.event.location}else if(Qa(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new rc.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new rc.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||JU(32)};let a={name:n.poll.name,selectableOptionsCount:n.poll.selectableCount,options:n.poll.values.map(A=>({optionName:A}))};n.poll.toAnnouncementGroup?e.pollCreationMessageV2=a:n.poll.selectableCount===1?e.pollCreationMessageV3=a:e.pollCreationMessage=a}else Qa(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:Qa(n,"sharePhoneNumber")?e.protocolMessage={type:ne.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:Qa(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:Qa(n,"limitSharing")?e.protocolMessage={type:ne.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await Kf(n,t);if(dd(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),dd(n,"mentions")&&n.mentions?.length||dd(n,"mentionAll")&&n.mentionAll){let a=Object.keys(e)[0],A=e[a];A&&"contextInfo"in A?(A.contextInfo=A.contextInfo||{},n.mentions?.length&&(A.contextInfo.mentionedJid=n.mentions),n.mentionAll&&(A.contextInfo.nonJidMentions=1)):A&&(A.contextInfo={mentionedJid:n.mentions,nonJidMentions:n.mentionAll?1:0})}if(dd(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:ne.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),dd(n,"contextInfo")&&n.contextInfo){let a=Object.keys(e)[0],A=e[a];"contextInfo"in A&&A.contextInfo?A.contextInfo={...A.contextInfo,...n.contextInfo}:A&&(A.contextInfo=n.contextInfo)}return dd(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:ne.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),xb(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=JU(32))),ne.Message.create(e)},lVe=(n,t,o)=>{o.timestamp||(o.timestamp=new Date);let i=ya(t),e=xf(i),a=va(o.timestamp),{quoted:A,userJid:r}=o;if(A&&!tI(n)){let g=A.key.fromMe?r:A.participant||A.key.participant||A.key.remoteJid,c=ya(A.message),I=xf(c);c=ne.Message.create({[I]:c[I]});let d=c[I];typeof d=="object"&&d&&"contextInfo"in d&&delete d.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=CA(g),B.stanzaId=A.key.id,B.quotedMessage=c,n!==A.key.remoteJid&&(B.remoteJid=A.key.remoteJid),B&&i[e]&&(i[e].contextInfo=B)}o?.ephemeralExpiration&&e!=="protocolMessage"&&e!=="ephemeralMessage"&&!tI(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||Yf}),t=ne.Message.create(t);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||zr()},message:t,messageTimestamp:a,messageStubParameters:[],participant:Jr(n)||Yg(n)?r:void 0,status:yh.PENDING};return ne.WebMessageInfo.fromObject(s)},Vne=async(n,t,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),lVe(n,await IVe(t,{...o,jid:n}),o)),xf=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},ya=n=>{if(!n)return;for(let o=0;o<5;o++){let i=t(n);if(!i)break;n=i.message}return n;function t(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},Wne=n=>{let t=o=>o.imageMessage?{imageMessage:o.imageMessage}:o.documentMessage?{documentMessage:o.documentMessage}:o.videoMessage?{videoMessage:o.videoMessage}:o.locationMessage?{locationMessage:o.locationMessage}:{conversation:"contentText"in o?o.contentText:"hydratedContentText"in o?o.hydratedContentText:""};return n=ya(n),n?.buttonsMessage?t(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?t(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?t(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?t(n?.templateMessage?.fourRowTemplate):n};var zU=(n,t)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===t.userJid);o?Object.assign(o,t):n.userReceipt.push(t)},VU=(n,t)=>{let o=Mh(t.key),i=(n.reactions||[]).filter(e=>Mh(e.key)!==o);t.text=t.text||"",i.push(t),n.reactions=i};var Zne=n=>{let t={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;t[A]||(t[A]={jid:o,participant:e,messageIds:[]}),t[A].messageIds.push(i)}return Object.values(t)},dVe=[410,404],WU=async(n,t,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&dVe.includes(A.status))return i.logger.info({key:n.key},"sending reupload media request..."),n=await i.reuploadRequest(n),await a();throw A});async function a(){let A=Wne(n.message);if(!A)throw new rc.Boom("No message present",{statusCode:400,data:n});let r=xf(A),s=r?.replace("Message",""),g=A[r];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new rc.Boom(`"${r}" message is not a media message`);let c;"thumbnailDirectPath"in g&&!("url"in g)?(c={directPath:g.thumbnailDirectPath,mediaKey:g.mediaKey},s="thumbnail-link"):c=g;let I=await QE(c,s,o);if(t==="buffer"){let d=[];for await(let B of I)d.push(B);return Buffer.concat(d)}return I}},Xne=n=>{n=Wne(n);let t=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!t)throw new rc.Boom("given message is not a media message",{statusCode:400,data:n});return t};var Yb=ze(jr(),1);import{createHash as uVe}from"crypto";function pVe(n,t){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:$o(t)}),hVe=async({get:n},t,o)=>{let i=[];for(let e=t;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=t-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=Dr.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,t]}},jf=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:qg(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),XU=(n,t)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:qg(t,3)},{tag:"value",attrs:{},content:n.public}]}),ZU=n=>typeof n=="number"&&Number.isInteger(n),ase=n=>{let t=le(n,"keys");if(!t)return null;let o=ka(t,"type");if(!o||o.length!==1||o[0]!==Jg[0])return null;let i=ka(t,"identity"),e=le(t,"skey");if(!i||i.length!==32||!e)return null;let a=rI(n,"registration",4);if(!ZU(a))return null;let A=ka(e,"value"),r=ka(e,"signature"),s=rI(e,"id",3);if(!A||A.length!==32||!r||!ZU(s))return null;let g=le(t,"key"),c;if(g){let I=ka(g,"value"),d=rI(g,"id",3);if(!I||I.length!==32||!ZU(d))return null;c={keyId:d,publicKey:$o(I)}}return{registrationId:a,identityKey:$o(i),signedPreKey:{keyId:s,publicKey:$o(A),signature:r},preKey:c}},ise=async(n,t)=>{let o=A=>A?{keyId:rI(A,"id",3),publicKey:$o(ka(A,"value")),signature:ka(A,"signature")}:void 0,i=PA(le(n,"list"),"user");for(let A of i)Vi(A);let a=pVe(i,100);for(let A of a)for(let r of A){let s=le(r,"skey"),g=le(r,"key"),c=ka(r,"identity"),I=r.attrs.jid,d=rI(r,"registration",4);await t.injectE2ESession({jid:I,session:{registrationId:d,identityKey:$o(c),signedPreKey:o(s),preKey:o(g)}})}},ose=(n,t,o,i)=>{let{user:e,device:a}=fA(t),A=[];for(let r of n){let{devices:s,id:g}=r,c=fA(g),{user:I,server:d}=c,{domainType:B}=c,f=s?.deviceList;if(Array.isArray(f))for(let{id:Q,keyIndex:y,isHosted:m}of f)(!i||Q!==0)&&(e!==I&&o!==I||a!==Q)&&(Q===0||y)&&(m&&(B=B===zt.LID?zt.HOSTED_LID:zt.HOSTED),A.push({user:I,device:Q,domainType:B,server:g$(d,B)}))}return A},$U=async({creds:n,keys:t},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=EVe(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await t.set({"pre-key":i});let r=await hVe(t,a[0],a[0]+a[1]);return{update:A,preKeys:r}},nse=async(n,t)=>{let{creds:o}=n,{update:i,preKeys:e}=await $U(n,t),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:OA},content:[{tag:"registration",attrs:{},content:qg(o.registrationId)},{tag:"type",attrs:{},content:Jg},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>XU(e[+A],+A))},jf(o.signedPreKey)]};return{update:i,node:a}};var CVe=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?ne.ClientPayload.UserAgent.Platform.ANDROID:ne.ClientPayload.UserAgent.Platform.WEB,releaseChannel:ne.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),sse={"Mac OS":ne.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:ne.ClientPayload.WebInfo.WebSubPlatform.WIN32},BVe=n=>{let t=ne.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&sse[n.browser[0]]&&n.browser[1]==="Desktop"&&(t=sse[n.browser[0]]),{webSubPlatform:t}},gse=n=>{let t={connectType:ne.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:ne.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:CVe(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(t.webInfo=BVe(n)),n.pushName&&(t.pushName=n.pushName),t},cse=(n,t)=>{let{user:o,device:i}=fA(n),e={...gse(t),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return ne.ClientPayload.fromObject(e)},fVe=n=>{let t=n.toUpperCase();return t==="ANDROID"?ne.DeviceProps.PlatformType.ANDROID_PHONE:ne.DeviceProps.PlatformType[t]||ne.DeviceProps.PlatformType.CHROME},Ise=({registrationId:n,signedPreKey:t,signedIdentityKey:o},i)=>{let e=uVe("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:fVe(i.browser[1]),requireFullSync:i.syncFullHistory,historySyncConfig:{storageQuotaMb:10240,inlineInitialPayloadInE2EeMsg:!0,recentSyncDaysLimit:void 0,supportCallLogHistory:!1,supportBotUserAgentChatHistory:!0,supportCagReactionsAndPolls:!0,supportBizHostedMsg:!0,supportRecentSyncChunkMessageCountTuning:!0,supportHostedGroupMsg:!0,supportFbidBotChatHistory:!0,supportAddOnHistorySyncMigration:void 0,supportMessageAssociation:!0,supportGroupHistory:!1,onDemandReady:void 0,supportGuestChat:void 0},version:{primary:10,secondary:15,tertiary:7}},A=ne.DeviceProps.encode(a).finish(),r={...gse(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:qg(n),eKeytype:Jg,eIdent:o.public,eSkeyId:qg(t.keyId,3),eSkeyVal:t.keyPair.public,eSkeySig:t.signature}};return ne.ClientPayload.fromObject(r)},lse=(n,{advSecretKey:t,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=le(n,"pair-success"),A=le(a,"device-identity"),r=le(a,"platform"),s=le(a,"device"),g=le(a,"biz");if(!A||!s)throw new Yb.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,I=s.attrs.jid,d=s.attrs.lid,{details:B,hmac:f,accountType:Q}=ne.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);Q!==void 0&&Q===ne.ADVEncryptionType.HOSTED&&(y=eH);let m=qn(Buffer.concat([y,B]),Buffer.from(t,"base64"));if(Buffer.compare(f,m)!==0)throw new Yb.Boom("Invalid account signature");let T=ne.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:_,accountSignature:R,details:H}=T,F=ne.ADVDeviceIdentity.decode(H),L=F.deviceType===ne.ADVEncryptionType.HOSTED?eH:dse,q=Buffer.concat([L,H,o.public]);if(!Dr.verify(_,q,R))throw new Yb.Boom("Failed to verify account signature");let z=Buffer.concat([pse,H,o.public,_]);T.deviceSignature=Dr.sign(o.private,z);let K=rse(d,_),G=Jf(T,!1),V={tag:"iq",attrs:{to:OA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":F.keyIndex.toString()},content:G}]}]};return{creds:{account:T,me:{id:I,name:c,lid:d},signalIdentities:[...i||[],K],platform:r?.attrs.name},reply:V}},Jf=(n,t)=>(n={...n},(!t||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),ne.ADVSignedDeviceIdentity.encode(n).finish());var yE=ze(jr(),1);var use=12,hse=Buffer.alloc(0),Ese=n=>{let t=new ArrayBuffer(use);return new DataView(t).setUint32(8,n),new Uint8Array(t)},AH=class{constructor(t,o){this.encKey=t,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(use)}encrypt(t){let o=this.writeCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,xl(t,this.encKey,this.iv,hse)}decrypt(t){let o=this.readCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,Yl(t,this.decKey,this.iv,hse)}},Cse=({keyPair:{private:n,public:t},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(Bse),A=a.byteLength===32?a:bh(a),r=A,s=A,g=A,c=0,I=!1,d=Buffer.alloc(0),B=null,f=!1,Q=null,y;e?(y=Buffer.alloc(7+e.byteLength+o.length),y.write("ED",0,"utf8"),y.writeUint8(0,2),y.writeUint8(1,3),y.writeUint8(e.byteLength>>16,4),y.writeUint16BE(e.byteLength&65535,5),y.set(e,7),y.set(o,7+e.byteLength)):y=Buffer.from(o);let m=q=>{B||(A=bh(Buffer.concat([A,q])))},T=q=>{if(B)return B.encrypt(q);let z=xl(q,s,Ese(c++),A);return m(z),z},_=q=>{if(B)return B.decrypt(q);let z=Yl(q,g,Ese(c++),A);return m(q),z},R=q=>{let z=Jn(Buffer.from(q),64,{salt:r,info:""});return[z.subarray(0,32),z.subarray(32)]},H=q=>{let[z,K]=R(q);r=z,s=K,g=K,c=0},F=async()=>{f=!0;let[q,z]=R(new Uint8Array(0));B=new AH(q,z),f=!1,i.trace("Noise handler transitioned to Transport state"),Q&&(i.trace({length:d.length},"Flushing buffered frames after transport ready"),await L(Q),Q=null)},L=async q=>{let z;for(;;){if(d.length<3||(z=d[0]<<16|d[1]<<8|d[2],d.length{m(q.ephemeral),H(Dr.sharedKey(n,q.ephemeral));let K=_(q.static);H(Dr.sharedKey(n,K));let G=_(q.payload),{intermediate:V,leaf:U}=ne.CertChain.decode(G);if(!U?.details||!U?.signature)throw new yE.Boom("invalid noise leaf certificate",{statusCode:400});if(!V?.details||!V?.signature)throw new yE.Boom("invalid noise intermediate certificate",{statusCode:400});let N=ne.CertChain.NoiseCertificate.Details.decode(V.details),{issuerSerial:k}=N,J=Dr.verify(N.key,U.details,U.signature),X=Dr.verify(tH.PUBLIC_KEY,V.details,V.signature);if(!J)throw new yE.Boom("noise certificate signature invalid",{statusCode:400});if(!X)throw new yE.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(k!==tH.SERIAL)throw new yE.Boom("certification match failed",{statusCode:400});let ae=T(z.public);return H(Dr.sharedKey(z.private,q.ephemeral)),ae},encodeFrame:q=>{B&&(q=B.encrypt(q));let z=q.byteLength,K=I?0:y.length,G=Buffer.allocUnsafe(K+3+z);return I||(G.set(y),I=!0),G[K]=z>>>16&255,G[K+1]=z>>>8&255,G[K+2]=z&255,G.set(q,K+3),G},decodeFrame:async(q,z)=>{if(f){d=Buffer.concat([d,q]),Q=z;return}d.length===0?d=Buffer.from(q):d=Buffer.concat([d,q]),await L(z)}}};import{pipeline as QVe}from"stream/promises";import{promisify as yVe}from"util";import{createInflate as mVe,inflate as SVe}from"zlib";var wVe=yVe(SVe),DVe=n=>{for(let t of n){let o=t.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(Tt(i)||wr(i)))return i}},OVe=async(n,t)=>{let o=await QE(n,"md-msg-hist",{options:t}),i=mVe(),e=[];i.on("data",r=>e.push(r)),await QVe(o,i);let a=Buffer.concat(e);return ne.HistorySync.decode(a)},bVe=(n,t)=>{let o=[],i=[],e=[],a=[];t?.trace({progress:n.progress},"processing history of type "+n.syncType?.toString());for(let A of n.phoneNumberToLidMappings||[])A.lidJid&&A.pnJid&&a.push({lid:A.lidJid,pn:A.pnJid});switch(n.syncType){case ne.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case ne.HistorySync.HistorySyncType.RECENT:case ne.HistorySync.HistorySyncType.FULL:case ne.HistorySync.HistorySyncType.ON_DEMAND:for(let A of n.conversations){i.push({id:A.id,name:A.displayName||A.name||A.username||void 0,username:A.username||void 0,lid:A.lidJid||A.accountLid||void 0,phoneNumber:A.pnJid||void 0});let r=A.id,s=qA(r)||Ea(r),g=Tt(r)||wr(r);if(s&&A.pnJid)a.push({lid:r,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:r});else if(s&&!A.pnJid){let I=DVe(A.messages||[]);I&&a.push({lid:r,pn:I})}let c=A.messages||[];delete A.messages;for(let I of c){let d=I.message;o.push(d),A.messages?.length||(A.messages=[{message:d}]),!d.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=qr(d.messageTimestamp)),(d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_BSP||d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_FB)&&d.messageStubParameters?.[0]&&i.push({id:d.key.participant||d.key.remoteJid,verifiedName:d.messageStubParameters?.[0]})}e.push(A)}break;case ne.HistorySync.HistorySyncType.PUSH_NAME:for(let A of n.pushnames)i.push({id:A.id,notify:A.pushname});break}return{chats:e,contacts:i,messages:o,lidPnMappings:a,pastParticipants:n.pastParticipants,syncType:n.syncType,progress:n.progress}},fse=async(n,t,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=ne.HistorySync.decode(await wVe(n.initialHistBootstrapInlinePayload)):i=await OVe(n,t),bVe(i,o)},jb=n=>(n?ya(n):void 0)?.protocolMessage?.historySyncNotification;var In=ze(jr(),1);var tg;(function(n){n.Chat="label_jid",n.Message="label_message"})(tg||(tg={}));var Qse=new wh;var yse=(n,t,o)=>{let i=[];if(!t)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=Tt(t),A=a?t:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:t,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&qA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:t}}),i},mse=(n,t)=>{for(let o of t)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var qf=n=>{let t=T$(n);return{indexKey:t.indexKey,valueEncryptionKey:t.valueEncryptionKey,valueMacKey:t.valueMacKey,snapshotMacKey:t.snapshotMacKey,patchMacKey:t.patchMacKey}},Sse=(n,t,o,i)=>{let e=n===ne.SyncdMutation.SyncdOperation.SET?1:2,a=typeof o=="string"?Buffer.from(o,"base64"):o,A=new Uint8Array(1+a.length);A[0]=e,A.set(a,1);let r=new Uint8Array(8);r[7]=A.length;let s=new Uint8Array(A.length+t.length+r.length);return s.set(A,0),s.set(t,A.length),s.set(r,A.length+t.length),qn(s,i,"sha512").subarray(0,32)},wse=n=>{let t=Buffer.alloc(8);return t.writeUint32BE(n,4),t},Dse=({indexValueMap:n,hash:t})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let r=Buffer.from(e).toString("base64"),s=n[r];if(A===ne.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[r]}else o.push(a),n[r]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=Qse.subtractThenAdd(t,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},rH=(n,t,o,i)=>{let e=Buffer.concat([n,wse(t),Buffer.from(o,"utf-8")]);return qn(e,i,"sha256")},Ose=(n,t,o,i,e)=>{let a=Buffer.concat([n,...t,wse(o),Buffer.from(i,"utf-8")]);return qn(a,e)},Jb=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),aH=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),iH=2,zf=n=>n?.data?.isMissingKey===!0,bse=(n,t)=>t>=iH||n?.name==="TypeError",Mse=async({type:n,index:t,syncAction:o,apiVersion:i,operation:e},a,A,r)=>{let s=a?await r(a):void 0;if(!s)throw new In.Boom(`myAppStateKey ("${a}") not present`,{data:{isMissingKey:!0}});let g=Buffer.from(a,"base64");A={...A,indexValueMap:{...A.indexValueMap}};let c=Buffer.from(JSON.stringify(t)),I=ne.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),d=ne.SyncActionData.encode(I).finish(),B=qf(s.keyData),f=L$(d,B.valueEncryptionKey),Q=Sse(e,f,g,B.valueMacKey),y=qn(c,B.indexKey),m=Dse(A);m.mix({indexMac:y,valueMac:Q,operation:e}),Object.assign(A,m.finish()),A.version+=1;let T=rH(A.hash,A.version,n,B.snapshotMacKey),_={patchMac:Ose(T,[Q],A.version,n,B.patchMacKey),snapshotMac:T,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([f,Q])},keyId:{id:g}}}]},R=y.toString("base64");return A.indexValueMap[R]={valueMac:Q},{patch:_,state:A}},_se=async(n,t,o,i,e)=>{let a=Dse(t),A=new Map;for(let s of n){let g="operation"in s?s.operation:ne.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,I;try{I=await r(c.keyId.id)}catch(T){if(zf(T))throw T;continue}let d=c.value.blob,B=d.subarray(0,-32),f=d.subarray(-32);if(e){let T=Sse(g,B,c.keyId.id,I.valueMacKey);if(Buffer.compare(T,f)!==0)continue}let Q;try{Q=F$(B,I.valueEncryptionKey)}catch{continue}let y=ne.SyncActionData.decode(Q);if(e){let T=qn(y.index,I.indexKey);if(Buffer.compare(T,c.index.blob)!==0)throw new In.Boom("HMAC index verification failed")}let m=Buffer.from(y.index).toString();i({syncAction:y,index:JSON.parse(m)}),a.mix({indexMac:c.index.blob,valueMac:f,operation:g})}return a.finish();async function r(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let I=await o(g);if(!I)throw new In.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let d=qf(I.keyData);return A.set(g,d),d}},MVe=async(n,t,o,i,e,a)=>{if(a){let r=Buffer.from(n.keyId.id).toString("base64"),s=await i(r);if(!s)throw new In.Boom(`failed to find key "${r}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=qf(s.keyData),c=n.mutations.map(d=>d.record.value.blob.slice(-32)),I=Ose(n.snapshotMac,c,qr(n.version.version),t,g.patchMacKey);if(Buffer.compare(I,n.patchMac)!==0)throw new In.Boom("Invalid patch mac")}return await _se(n.mutations,o,i,e,a)},Tse=async(n,t)=>{let o=le(n,"sync"),i=PA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=le(a,"patches"),r=PA(A||a,"patch"),s=le(a,"snapshot"),g=[],c=a.attrs.name,I=a.attrs.has_more_patches==="true",d;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=ne.ExternalBlobReference.decode(s.content),f=await Nse(B,t);d=ne.SyncdSnapshot.decode(f)}for(let{content:B}of r)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let f=ne.SyncdPatch.decode(B);f.version||(f.version={version:+a.attrs.version+1}),g.push(f)}e[c]={patches:g,hasMorePatches:I,snapshot:d}})),e},Nse=async(n,t)=>{let o=await QE(n,"md-app-state",{options:t}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},_Ve=async(n,t)=>{let o=await Nse(n,t);return ne.SyncdMutations.decode(o)},Rse=async(n,t,o,i,e=!0,a)=>{let A=Jb();A.version=qr(t.version.version);let r={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await _se(t.records,A,o,s?I=>{let d=I.syncAction.index?.toString();r[d]=I}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let I=Buffer.from(t.keyId.id).toString("base64"),d=await o(I);if(!d)throw new In.Boom(`failed to find key "${I}" to decode mutation`,{data:{isMissingKey:!0}});let B=qf(d.keyData),f=rH(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(t.mac,f)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:r}},oH=async(n,t,o,i,e,a,A,r=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of t){let{version:I,keyId:d,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:I},"downloading external patch");let m=await _Ve(c.externalMutations,e);A?.debug({name:n,version:I,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let f=qr(I.version);s.version=f;let Q=typeof a>"u"||f>a,y;try{y=await MVe(c,n,s,i,Q?m=>{let T=m.syncAction.index?.toString();g[T]=m}:()=>{},r)}catch(m){if(zf(m))throw m;A?.warn({name:n,version:f,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,r){let m=Buffer.from(d.id).toString("base64"),T=await i(m);if(!T)throw new In.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let _=qf(T.keyData),R=rH(s.hash,s.version,n,_.snapshotMacKey);if(Buffer.compare(B,R)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},kse=(n,t)=>{let o=ne.SyncdMutation.SyncdOperation,i=a=>{let A;return Array.isArray(a)?A={lastMessageTimestamp:a[a.length-1]?.messageTimestamp,messages:a?.length?a.map(s=>{if(!s.key?.id||!s.key?.remoteJid)throw new In.Boom("Incomplete key",{statusCode:400,data:s});if(Jr(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new In.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!qr(s.messageTimestamp))throw new In.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=CA(s.key.participant)),s}):void 0}:A=a,A},e;if("mute"in n)e={syncAction:{muteAction:{muted:!!n.mute,muteEndTimestamp:n.mute||void 0}},index:["mute",t],type:"regular_high",apiVersion:2,operation:o.SET};else if("archive"in n)e={syncAction:{archiveChatAction:{archived:!!n.archive,messageRange:i(n.lastMessages)}},index:["archive",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("markRead"in n)e={syncAction:{markChatAsReadAction:{read:n.markRead,messageRange:i(n.lastMessages)}},index:["markChatAsRead",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:r}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:r,messageTimestamp:a}},index:["deleteMessageForMe",t,A.id,A.fromMe?"1":"0","0"],type:"regular_high",apiVersion:3,operation:o.SET}}else if("clear"in n)e={syncAction:{clearChatAction:{messageRange:i(n.lastMessages)}},index:["clearChat",t,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",t],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",t],type:"critical_unblock_low",apiVersion:2,operation:n.contact?o.SET:o.REMOVE};else if("disableLinkPreviews"in n)e={syncAction:{privacySettingDisableLinkPreviewsAction:n.disableLinkPreviews||{}},index:["setting_disableLinkPreviews"],type:"regular",apiVersion:8,operation:o.SET};else if("star"in n){let a=n.star.messages[0];e={syncAction:{starAction:{starred:!!n.star.star}},index:["star",t,a.id,a.fromMe?"1":"0","0"],type:"regular_low",apiVersion:2,operation:o.SET}}else if("delete"in n)e={syncAction:{deleteChatAction:{messageRange:i(n.lastMessages)}},index:["deleteChat",t,"1"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pushNameSetting"in n)e={syncAction:{pushNameSetting:{name:n.pushNameSetting}},index:["setting_pushName"],type:"critical_block",apiVersion:1,operation:o.SET};else if("quickReply"in n)e={syncAction:{quickReplyAction:{count:0,deleted:n.quickReply.deleted||!1,keywords:[],message:n.quickReply.message||"",shortcut:n.quickReply.shortcut||""}},index:["quick_reply",n.quickReply.timestamp||String(Math.floor(Date.now()/1e3))],type:"regular",apiVersion:2,operation:o.SET};else if("addLabel"in n)e={syncAction:{labelEditAction:{name:n.addLabel.name,color:n.addLabel.color,predefinedId:n.addLabel.predefinedId,deleted:n.addLabel.deleted}},index:["label_edit",n.addLabel.id],type:"regular",apiVersion:3,operation:o.SET};else if("addChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[tg.Chat,n.addChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[tg.Chat,n.removeChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[tg.Message,n.addMessageLabel.labelId,t,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[tg.Message,n.removeMessageLabel.labelId,t,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new In.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},vse=(n,t,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:r},index:[s,g,c,I]}=n;if(r?.muteAction)t.emit("chats.update",[{id:g,muteEndTime:r.muteAction?.muted?qr(r.muteAction.muteEndTimestamp):null,conditional:d(g,void 0)}]);else if(r?.archiveChatAction||s==="archive"||s==="unarchive"){let f=r?.archiveChatAction,Q=f?f.archived:s==="archive",y=A?.unarchiveChats?f?.messageRange:void 0;t.emit("chats.update",[{id:g,archived:Q,conditional:d(g,y)}])}else if(r?.markChatAsReadAction){let f=r.markChatAsReadAction,Q=a&&f.read;t.emit("chats.update",[{id:g,unreadCount:Q?null:f?.read?0:-1,conditional:d(g,f?.messageRange)}])}else if(r?.deleteMessageForMeAction||s==="deleteMessageForMe")t.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:I==="1"}]});else if(r?.contactAction){let f=yse(r.contactAction,g,e);mse(t,f)}else if(r?.pushNameSetting){let f=r?.pushNameSetting?.name;f&&o?.name!==f&&t.emit("creds.update",{me:{...o,name:f}})}else if(r?.pinAction)t.emit("chats.update",[{id:g,pinned:r.pinAction?.pinned?qr(r.timestamp):null,conditional:d(g,void 0)}]);else if(r?.unarchiveChatsSetting){let f=!!r.unarchiveChatsSetting.unarchiveChats;t.emit("creds.update",{accountSettings:{unarchiveChats:f}}),e?.info(`archive setting updated => '${r.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=f)}else if(r?.starAction||s==="star"){let f=r?.starAction?.starred;typeof f!="boolean"&&(f=n.index[n.index.length-1]==="1"),t.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:I==="1"},update:{starred:f}}])}else if(r?.deleteChatAction||s==="deleteChat")a||t.emit("chats.delete",[g]);else if(r?.labelEditAction){let{name:f,color:Q,deleted:y,predefinedId:m}=r.labelEditAction;t.emit("labels.edit",{id:g,name:f,color:Q,deleted:y,predefinedId:m?String(m):void 0})}else r?.labelAssociationAction?t.emit("labels.association",{type:r.labelAssociationAction.labeled?"add":"remove",association:s===tg.Chat?{type:tg.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:tg.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):r?.localeSetting?.locale?t.emit("settings.update",{setting:"locale",value:r.localeSetting.locale}):r?.timeFormatAction?t.emit("settings.update",{setting:"timeFormat",value:r.timeFormatAction}):r?.pnForLidChatAction?r.pnForLidChatAction.pnJid&&t.emit("lid-mapping.update",{lid:g,pn:r.pnForLidChatAction.pnJid}):r?.privacySettingRelayAllCalls?t.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:r.privacySettingRelayAllCalls}):r?.statusPrivacy?t.emit("settings.update",{setting:"statusPrivacy",value:r.statusPrivacy}):r?.lockChatAction?t.emit("chats.lock",{id:g,locked:!!r.lockChatAction.locked}):r?.privacySettingDisableLinkPreviewsAction?t.emit("settings.update",{setting:"disableLinkPreviews",value:r.privacySettingDisableLinkPreviewsAction}):r?.notificationActivitySettingAction?.notificationActivitySetting?t.emit("settings.update",{setting:"notificationActivitySetting",value:r.notificationActivitySettingAction.notificationActivitySetting}):r?.lidContactAction?t.emit("contacts.upsert",[{id:g,name:r.lidContactAction.fullName||r.lidContactAction.firstName||r.lidContactAction.username||void 0,username:r.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):r?.privacySettingChannelsPersonalisedRecommendationAction?t.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:r.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function d(f,Q){return a?y=>{let m=y.historySets.chats[f]||y.chatUpserts[f];if(m)return Q?B(m,Q):!0}:void 0}function B(f,Q){let y=Number(Q?.lastMessageTimestamp||Q?.lastSystemMessageTimestamp||0),m=Number(f?.lastMessageRecvTimestamp||0);return y>=m}};var TVe=class{_eventListeners;_maxListeners;_logger;_throwOnEmitError=!1;_throwOnEmptyListeners=!1;_errorEvent="error";constructor(n){this._eventListeners=new Map,this._maxListeners=100,this._logger=n?.logger,n?.throwOnEmitError!==void 0&&(this._throwOnEmitError=n.throwOnEmitError),n?.throwOnEmptyListeners!==void 0&&(this._throwOnEmptyListeners=n.throwOnEmptyListeners)}get logger(){return this._logger}set logger(n){this._logger=n}get throwOnEmitError(){return this._throwOnEmitError}set throwOnEmitError(n){this._throwOnEmitError=n}get throwOnEmptyListeners(){return this._throwOnEmptyListeners}set throwOnEmptyListeners(n){this._throwOnEmptyListeners=n}once(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let t=this._eventListeners.get(n);return t?t.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,t){let o=this._eventListeners.get(n)??[];return o.unshift(t),this._eventListeners.set(n,o),this}prependOnceListener(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,t){return this.on(n,t),this}on(n,t){this._eventListeners.has(n)||this._eventListeners.set(n,[]);let o=this._eventListeners.get(n);return o&&(o.length>=this._maxListeners&&console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${o.length+1} ${n} listeners added. Use setMaxListeners() to increase limit.`),o.push(t)),this}removeListener(n,t){return this.off(n,t),this}off(n,t){let o=this._eventListeners.get(n)??[],i=o.indexOf(t);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...t){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...t),o=!0;if(n===this._errorEvent){let e=t[0]instanceof Error?t[0]:new Error(`${t[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,t),o}listeners(n){return this._eventListeners.get(n)??[]}removeAllListeners(n){return n!==void 0?this._eventListeners.delete(n):this._eventListeners.clear(),this}setMaxListeners(n){this._maxListeners=n;for(let t of this._eventListeners.values())t.length>n&&t.splice(n)}getAllListeners(){let n=[];for(let t of this._eventListeners.values())n=[...n,...t];return n}sendLog(n,t){if(!this._logger)return;let o;switch(typeof t=="string"?o=t:Array.isArray(t)&&t.length>0&&t[0]instanceof Error?o=t[0].message:t instanceof Error?o=t.message:Array.isArray(t)&&t.length>0&&typeof t[0]?.message=="string"?o=t[0].message:o=JSON.stringify(t),n){case"error":{this._logger.error?.(o,{event:n,data:t});break}case"warn":{this._logger.warn?.(o,{event:n,data:t});break}case"trace":{this._logger.trace?.(o,{event:n,data:t});break}case"debug":{this._logger.debug?.(o,{event:n,data:t});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:t});break}default:{this._logger.info?.(o,{event:n,data:t});break}}}},OI=class extends TVe{_hooks;_throwOnHookError=!1;_enforceBeforeAfter=!1;_deprecatedHooks;_allowDeprecated=!0;constructor(n){super({logger:n?.logger,throwOnEmitError:n?.throwOnEmitError,throwOnEmptyListeners:n?.throwOnEmptyListeners}),this._hooks=new Map,this._deprecatedHooks=n?.deprecatedHooks?new Map(n.deprecatedHooks):new Map,n?.throwOnHookError!==void 0?this._throwOnHookError=n.throwOnHookError:n?.throwHookErrors!==void 0&&(this._throwOnHookError=n.throwHookErrors),n?.enforceBeforeAfter!==void 0&&(this._enforceBeforeAfter=n.enforceBeforeAfter),n?.allowDeprecated!==void 0&&(this._allowDeprecated=n.allowDeprecated)}get hooks(){return this._hooks}get throwHookErrors(){return this._throwOnHookError}set throwHookErrors(n){this._throwOnHookError=n}get throwOnHookError(){return this._throwOnHookError}set throwOnHookError(n){this._throwOnHookError=n}get enforceBeforeAfter(){return this._enforceBeforeAfter}set enforceBeforeAfter(n){this._enforceBeforeAfter=n}get deprecatedHooks(){return this._deprecatedHooks}set deprecatedHooks(n){this._deprecatedHooks=n}get allowDeprecated(){return this._allowDeprecated}set allowDeprecated(n){this._allowDeprecated=n}validateHookName(n){if(this._enforceBeforeAfter){let t=n.trim().toLocaleLowerCase();if(!t.startsWith("before")&&!t.startsWith("after"))throw new Error(`Hook event "${n}" must start with "before" or "after" when enforceBeforeAfter is enabled`)}}checkDeprecatedHook(n){if(this._deprecatedHooks.has(n)){let t=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${t?`: ${t}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,t){this.onHookEntry({event:n,handler:t})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let t=this._hooks.get(n.event);t?t.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,t){this.onHookEntry({event:n,handler:t})}onHooks(n){for(let t of n)this.onHook(t.event,t.handler)}prependHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(t):this._hooks.set(n,[t])}prependOnceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.prependHook(n,o)}onceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.onHook(n,o)}removeHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let t of n)this.removeHook(t.event,t.handler)}async hook(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){for(let i of o)if(i.constructor.name!=="AsyncFunction")try{i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...t){await this.hook(`before:${n}`,...t)}async afterHook(n,...t){await this.hook(`after:${n}`,...t)}async callHook(n,...t){await this.hook(n,...t)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var NVe=class{_enabled=!0;_maxSize=4e3;_store=new Map;_keys=[];constructor(n){n?.enabled!==void 0&&(this._enabled=n.enabled),n?.maxSize!==void 0&&(this._maxSize=n.maxSize)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get maxSize(){return this._maxSize}set maxSize(n){this._maxSize=n}get store(){return this._store}get size(){return this._store.size}get(n){return this._store.get(n)}set(n,t){if(this._enabled){if(this._store.has(n)){this._store.set(n,t);return}if(this._store.size>=this._maxSize){let o=this._keys.shift();o&&this._store.delete(o)}this._keys.push(n),this._store.set(n,t)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},RVe=class{get name(){return"crc32"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;t=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}let o=3988292384,i=4294967295;for(let a=0;a>>1^o&-(i&1)}return i=(i^4294967295)>>>0,i.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},qb=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let t=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}},kVe=class{get name(){return"djb2"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let o=5381;for(let e=0;e>>0;return o.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},vVe=class{get name(){return"fnv1"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;t=new Uint8Array(A.buffer,A.byteOffset,A.byteLength)}let o=2166136261,i=16777619,e=o;for(let A=0;A>>0;return e.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},PVe=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;t=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=t.length,a=Math.floor(e/4),A=this._seed;for(let c=0;c>>16,A=this._imul(A,2246822507),A^=A>>>13,A=this._imul(A,3266489909),A^=A>>>16,A=A>>>0,A.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}_imul(n,t){if(Math.imul)return Math.imul(n,t);let o=n>>>16&65535,i=n&65535,e=t>>>16&65535,a=t&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,t){return n<>>32-t}},GVe=class{_providers=new Map;_getFuzzy=!0;constructor(n){n?.providers&&this.loadProviders(n?.providers),n?.getFuzzy!==void 0&&(this._getFuzzy=!!n?.getFuzzy)}loadProviders(n){for(let t of n)this._providers.set(t.name,t)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,t){let o=t?.fuzzy??this._getFuzzy;n=n.trim();let i=this._providers.get(n);return i===void 0&&o===!0&&(n=n.toLowerCase(),i=this._providers.get(n)),i===void 0&&o===!0&&(n=n.replaceAll("-",""),i=this._providers.get(n)),i}add(n){this._providers.set(n.name,n)}remove(n){return this._providers.delete(n)}},nH=class extends OI{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new GVe;_defaultAlgorithm="SHA-256";_defaultAlgorithmSync="djb2";_cache;constructor(n){super(n),n?.parse&&(this._parse=n.parse),n?.stringify&&(this._stringify=n.stringify),n?.defaultAlgorithm&&(this._defaultAlgorithm=n.defaultAlgorithm),n?.defaultAlgorithmSync&&(this._defaultAlgorithmSync=n.defaultAlgorithmSync),this._cache=new NVe(n?.cache),this.loadProviders(n?.providers,{includeBase:n?.includeBase??!0})}get parse(){return this._parse}set parse(n){this._parse=n}get stringify(){return this._stringify}set stringify(n){this._stringify=n}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return this._providers.names}get defaultAlgorithm(){return this._defaultAlgorithm}set defaultAlgorithm(n){this._defaultAlgorithm=n}get defaultAlgorithmSync(){return this._defaultAlgorithmSync}set defaultAlgorithmSync(n){this._defaultAlgorithmSync=n}get cache(){return this._cache}async toHash(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithm,maxLength:t?.maxLength};await this.beforeHook("toHash",o);let i=this._stringify(o.data),e=`${o.algorithm}:${i}`;if(this._cache.enabled){let c=this._cache.get(e);if(c!==void 0){let I=c;t?.maxLength&&I.length>t.maxLength&&(I=I.substring(0,t.maxLength));let d={hash:I,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",d),d.hash}}let A=new TextEncoder().encode(i),r=this._providers.get(o.algorithm);r||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),r=new qb({algorithm:this._defaultAlgorithm}));let s=await r.toHash(A);this._cache.enabled&&this._cache.set(e,s),t?.maxLength&&s.length>t?.maxLength&&(s=s.substring(0,t.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}toHashSync(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithmSync,maxLength:t?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let I=this._cache.get(a);if(I!==void 0){let d=I;t?.maxLength&&d.length>t.maxLength&&(d=d.substring(0,t.maxLength));let B={hash:d,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let r=new TextEncoder().encode(e),s=this._providers.get(i);if(!s&&(this.emit("warn",`Invalid algorithm '${i}' not found. Falling back to default algorithm '${this._defaultAlgorithmSync}'.`),s=this._providers.get(this._defaultAlgorithmSync),!s))throw new Error(`Hash provider '${this._defaultAlgorithmSync}' (default) not found`);if(!s.toHashSync)throw new Error(`Hash provider '${i}' does not support synchronous hashing. Use toHash() instead or choose a different algorithm (djb2, fnv1, murmur, crc32).`);let g=s.toHashSync(r);this._cache.enabled&&this._cache.set(a,g),t?.maxLength&&g.length>t?.maxLength&&(g=g.substring(0,t.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}loadProviders(n,t={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);t.includeBase&&(this.providers.add(new qb({algorithm:"SHA-256"})),this.providers.add(new qb({algorithm:"SHA-384"})),this.providers.add(new qb({algorithm:"SHA-512"})),this.providers.add(new RVe),this.providers.add(new kVe),this.providers.add(new vVe),this.providers.add(new PVe))}};var cH=n=>{let t;if(n!==void 0){if(typeof n=="number")t=n;else{if(typeof n!="string")return;if(n=n.trim(),Number.isNaN(Number(n))){let o=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(n);if(!o)throw new Error(`Unsupported time format: "${n}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,e]=o,a=Number.parseFloat(i);switch(e.toLowerCase()){case"ms":t=a;break;case"s":t=a*1e3;break;case"m":t=a*1e3*60;break;case"h":t=a*1e3*60*60;break;case"hr":t=a*1e3*60*60;break;case"d":t=a*1e3*60*60*24;break;default:t=Number(n)}}else t=Number(n)}return t}},pd=(n,t)=>{t??=new Date;let o=cH(n);return o===void 0?t.getTime():t.getTime()+o};var Vf=(function(n){return n.SHA256="SHA-256",n.SHA384="SHA-384",n.SHA512="SHA-512",n.DJB2="djb2",n.FNV1="fnv1",n.MURMER="murmer",n.CRC32="crc32",n})({});function sH(n,t={algorithm:"djb2",serialize:JSON.stringify}){let o=t?.algorithm??"djb2",i=(t?.serialize??JSON.stringify)(n);return new nH().toHashSync(i,{algorithm:o})}function Pse(n,t={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=t?.min??0,i=t?.max??10,e=t?.algorithm??"djb2",a=t?.serialize??JSON.stringify,A=t?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let r=a(n);return new nH().toNumberSync(r,{algorithm:e,min:o,max:i,hashLength:A})}function IH(n,t){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=t;return(...A)=>{let r=FVe(n,A,{keyPrefix:i,serialize:a});t.createKey&&(r=t.createKey(n,A,t));let s=e.get(r);if(s===void 0)try{s=n(...A),e.set(r,s,o)}catch(g){e.emit("error",g),t.cacheErrors&&e.set(r,g,o)}return s}}function lH(n,t,o){let i=typeof n=="function"?n(o):n,e;try{e=o.cache.get(i)}catch(a){if(o.cache.emit("error",a),o.throwErrors===!0||o.throwErrors==="store")throw a}if(e===void 0)try{try{e=t()}catch(a){throw new zb(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new zb(a,"store")}}catch(a){let A=a instanceof zb?a.context:void 0,r=a instanceof zb?a.error:a;if(o.cache.emit("error",r),o.cacheErrors&&A==="function")try{o.cache.set(i,r,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw r}return e}function FVe(n,t,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${sH(t,{serialize:e})}`:`${n.name}::${sH(t,{serialize:e})}`}var zb=class{error;context;constructor(n,t){this.error=n,this.context=t}};var bI=class{_counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0};_vsize=0;_ksize=0;_enabled=!1;_lastUpdated;_lastReset;_subscriptions=[];_trackedKeys=new Map;_trackKeys=!1;_maxTrackedKeys;constructor(n){n?.enabled&&(this._enabled=n.enabled),n?.trackKeys&&(this._trackKeys=n.trackKeys),n?.maxTrackedKeys!==void 0&&(this._maxTrackedKeys=n.maxTrackedKeys),n?.emitter&&n?.eventMap&&this.subscribe(n.emitter,n.eventMap)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get trackKeys(){return this._trackKeys}set trackKeys(n){this._trackKeys=n}get maxTrackedKeys(){return this._maxTrackedKeys}set maxTrackedKeys(n){this._maxTrackedKeys=n}get trackedKeys(){return this._trackedKeys}get hits(){return this._counters.hits}get misses(){return this._counters.misses}get gets(){return this._counters.gets}get sets(){return this._counters.sets}get deletes(){return this._counters.deletes}get clears(){return this._counters.clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._counters.count}get hitRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.hits/n}get missRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.misses/n}get lastUpdated(){return this._lastUpdated}get lastReset(){return this._lastReset}increment(n,t=1){this._enabled&&(this._counters[n]+=t,this.touch())}decrement(n,t=1){this._enabled&&(this._counters[n]-=t,this.touch())}incrementHits(n=1){this.increment("hits",n)}incrementMisses(n=1){this.increment("misses",n)}incrementGets(n=1){this.increment("gets",n)}incrementSets(n=1){this.increment("sets",n)}incrementDeletes(n=1){this.increment("deletes",n)}incrementClears(n=1){this.increment("clears",n)}incrementVSize(n){this._enabled&&(this._vsize+=this.roughSizeOfObject(n),this.touch())}decreaseVSize(n){this._enabled&&(this._vsize=Math.max(0,this._vsize-this.roughSizeOfObject(n)),this.touch())}incrementKSize(n){this._enabled&&(this._ksize+=this.roughSizeOfString(n),this.touch())}decreaseKSize(n){this._enabled&&(this._ksize=Math.max(0,this._ksize-this.roughSizeOfString(n)),this.touch())}incrementCount(n=1){this.increment("count",n)}decreaseCount(n=1){this._enabled&&(this._counters.count=Math.max(0,this._counters.count-n),this.touch())}setCount(n){this._enabled&&(this._counters.count=n,this.touch())}roughSizeOfString(n){return n.length*2}roughSizeOfObject(n){let t=[],o=[n],i=0;for(;o.length>0;){let e=o.pop();if(typeof e=="boolean")i+=4;else if(typeof e=="string")i+=e.length*2;else if(typeof e=="number")i+=8;else{if(e==null){i+=4;continue}if(t.includes(e))continue;t.push(e);for(let a in e)i+=a.length*2,o.push(e[a])}}return i}enable(){this._enabled=!0}disable(){this._enabled=!1}clear(){this.reset()}reset(){this._counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0},this._vsize=0,this._ksize=0,this._trackedKeys.clear(),this._lastReset=Date.now(),this._lastUpdated=void 0}resetStoreValues(){this._vsize=0,this._ksize=0,this._counters.count=0}toJSON(){return{enabled:this._enabled,hits:this._counters.hits,misses:this._counters.misses,gets:this._counters.gets,sets:this._counters.sets,deletes:this._counters.deletes,clears:this._counters.clears,vsize:this._vsize,ksize:this._ksize,count:this._counters.count,hitRate:this.hitRate,missRate:this.missRate,trackedKeys:this._trackedKeys.size,lastUpdated:this._lastUpdated,lastReset:this._lastReset}}snapshot(){return this.toJSON()}recordKey(n,t,o=1){if(!this._enabled||!this._trackKeys)return;let i=this._trackedKeys.get(n);i||(i={hits:0,misses:0,gets:0,sets:0,deletes:0},this._trackedKeys.set(n,i),this.pruneTrackedKeys(n)),i[t]+=o,this.touch()}mostUsedKeys(n=100,t){return this.sortedKeyEntries(t,"desc").slice(0,n)}leastUsedKeys(n=100,t){return this.sortedKeyEntries(t,"asc").slice(0,n)}keyStats(n){let t=this._trackedKeys.get(n);return t?this.toKeyEntry(n,t):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,t){let o=t.hits+t.misses;return{key:n,count:this.totalOf(t),hits:t.hits,misses:t.misses,gets:t.gets,sets:t.sets,deletes:t.deletes,hitRate:o===0?0:t.hits/o}}sortedKeyEntries(n,t){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=t==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,r=n?a[n]:a.count;return A!==r?(A-r)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=t)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,t){for(let[o,i]of Object.entries(t)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let t=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){t.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=t}applyEvent(n,t){if(this._enabled){if(typeof n=="function"){n(this,...t);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var LVe=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},dH=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let t=new LVe(n);this.head?(t.next=this.head,this.head.prev=t,this.head=t):this.head=this.tail=t,this.nodesMap.set(n,t)}moveToFront(n){let t=this.nodesMap.get(n);if(!t||this.head===t)return;t.prev&&(t.prev.next=t.next);t.next&&(t.next.prev=t.prev);t===this.tail&&(this.tail=t.prev),t.prev=void 0,t.next=this.head;this.head&&(this.head.prev=t),this.head=t,this.tail??=t}getOldest(){return this.tail?this.tail.value:void 0}removeOldest(){if(!this.tail)return;let n=this.tail.value;return this.tail.prev?(this.tail=this.tail.prev,this.tail.next=void 0):this.head=this.tail=void 0,this.nodesMap.delete(n),n}remove(n){let t=this.nodesMap.get(n);return t?(t.prev?t.prev.next=t.next:(this.head=t.next,this.head&&(this.head.prev=void 0)),t.next?t.next.prev=t.prev:(this.tail=t.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var Gse=16777216,pH=class extends OI{_lru=new dH;_storeHashSize=16;_storeHashAlgorithm=Vf.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new bI({enabled:!1});constructor(n){super(),n?.ttl&&this.setTtl(n.ttl),n?.maxTtl!==void 0&&this.setMaxTtl(n.maxTtl),n?.useClone!==void 0&&(this._useClone=n.useClone),n?.stats&&(this._stats.enabled=n.stats),n?.storeHashSize&&n.storeHashSize>0&&(this._storeHashSize=n.storeHashSize),n?.lruSize&&(n.lruSize>16777216?this.emit("error",new Error(`LRU size cannot be larger than ${Gse} due to Map limitations.`)):this._lruSize=n.lruSize),n?.checkInterval&&(this._checkInterval=n.checkInterval),n?.storeHashAlgorithm&&(this._storeHashAlgorithm=n.storeHashAlgorithm),this._store=Array.from({length:this._storeHashSize},()=>new Map),this.startIntervalCheck()}get ttl(){return this._ttl}set ttl(n){this.setTtl(n)}get maxTtl(){return this._maxTtl}set maxTtl(n){this.setMaxTtl(n)}get useClone(){return this._useClone}set useClone(n){this._useClone=n}get lruSize(){return this._lruSize}set lruSize(n){if(n>16777216){this.emit("error",new Error(`LRU size cannot be larger than ${Gse} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new dH;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let t of this._store)n+=t.size;return n}get stats(){return this._stats}get storeHashSize(){return this._storeHashSize}set storeHashSize(n){n!==this._storeHashSize&&(this._storeHashSize=n,this._store=Array.from({length:this._storeHashSize},()=>new Map),this._stats.enabled&&this._stats.resetStoreValues())}get storeHashAlgorithm(){return this._storeHashAlgorithm}set storeHashAlgorithm(n){this._storeHashAlgorithm=n}get keys(){let n=[];for(let t of this._store)for(let o of t.keys()){let i=t.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),t.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let t of this._store)for(let o of t.values()){if(this.hasExpired(o)){this.recordExpiration(o),t.delete(o.key),this.lruRemove(o.key);continue}n.push(o)}return n.values()}get store(){return this._store}get(n){this.hookSync("BEFORE_GET",n);let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}this.lruMoveToFront(n);let i;return this._useClone?i=this.clone(o.value):i=o.value,this.recordRead(!0),this.hookSync("AFTER_GET",{key:n,result:i}),i}getMany(n){this.hookSync("BEFORE_GET_MANY",n);let t=[];for(let o of n)t.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:t}),t}getRaw(n){let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let t=[];for(let o of n)t.push(this.getRaw(o));return t}set(n,t,o){let i={key:n,value:t,ttl:o};this.hookSync("BEFORE_SET",i);let e=this.getStore(i.key),a,A=i.ttl;if(A!==void 0||this._ttl!==void 0)if(typeof A=="object"){if(A.expire&&(a=typeof A.expire=="number"?A.expire:A.expire.getTime()),A.ttl){let s=pd(A.ttl);s!==void 0&&(a=s)}}else{let s=pd(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=pd(this._maxTtl);(a===void 0||a>s)&&(a=s)}if(this._lruSize>0){if(e.has(i.key))this.lruMoveToFront(i.key);else if(this.lruAddToFront(i.key),this._lru.size>this._lruSize){let s=this._lru.getOldest();s&&(this._lru.removeOldest(),this.delete(s))}}if(this._stats.enabled){let s=e.get(i.key);s?this._stats.decreaseVSize(s.value):(this._stats.incrementKSize(i.key),this._stats.incrementCount()),this._stats.incrementVSize(i.value),this._stats.incrementSets()}let r={key:i.key,value:i.value,expires:a};e.set(i.key,r),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let t of n)this.set(t.key,t.value,t.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let t=[];for(let o of n){let i=this.get(o);t.push(!!i)}return t}take(n){let t=this.get(n);if(t)return this.delete(n),t}takeMany(n){let t=[];for(let o of n)t.push(this.take(o));return t}delete(n){this.hookSync("BEFORE_DELETE",n);let t=this.getStore(n);if(this._stats.enabled){let o=t.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}t.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let t of n)this.delete(t);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new dH,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let t=this.getKeyStoreHash(n);return this._store[t]||=new Map,this._store[t]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):Pse(n,{min:0,max:this._storeHashSize-1,algorithm:this._storeHashAlgorithm})}clone(n){return this.isPrimitive(n)?n:structuredClone(n)}lruAddToFront(n){this._lruSize!==0&&this._lru.addToFront(n)}lruMoveToFront(n){this._lruSize!==0&&this._lru.moveToFront(n)}lruRemove(n){this._lruSize!==0&&this._lru.remove(n)}lruResize(){for(;this._lru.size>this._lruSize;){let n=this._lru.getOldest();n&&(this._lru.removeOldest(),this.delete(n))}}checkExpiration(){for(let n of this._store)for(let t of n.values())t.expires&&Date.now()>t.expires&&(this.recordExpiration(t),n.delete(t.key),this.lruRemove(t.key))}startIntervalCheck(){if(this._checkInterval>0){this._interval&&clearInterval(this._interval),this._interval=setInterval(()=>{this.checkExpiration()},this._checkInterval).unref()}}stopIntervalCheck(){this._interval&&clearInterval(this._interval),this._interval=0,this._checkInterval=0}wrap(n,t){return IH(n,{ttl:t?.ttl??this._ttl,keyPrefix:t?.keyPrefix,createKey:t?.createKey,cache:this})}getOrSet(n,t,o){return lH(n,t,{cache:this,ttl:o?.ttl??this._ttl,cacheErrors:o?.cacheErrors,throwErrors:o?.throwErrors})}recordRead(n){this._stats.enabled&&(n?this._stats.incrementHits():this._stats.incrementMisses(),this._stats.incrementGets())}recordExpiration(n){this._stats.enabled&&(this._stats.decreaseKSize(n.key),this._stats.decreaseVSize(n.value),this._stats.decreaseCount())}isPrimitive(n){return n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}setTtl(n){typeof n=="string"||n===void 0?this._ttl=n:n>0?this._ttl=n:this._ttl=void 0}setMaxTtl(n){typeof n=="string"||n===void 0?this._maxTtl=n:n>0?this._maxTtl=n:this._maxTtl=void 0}hasExpired(n){return!!(n.expires&&Date.now()>n.expires)}};var JVe=class extends OI{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new bI({enabled:!0});_cacheable=new pH;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,t,o=0){if(typeof n!="string"&&typeof n!="number")throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`",n);if(o&&typeof o!="number"&&typeof o!="string")throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.",this.formatKey(n));let i=this.formatKey(n),e=0;this.options.stdTTL&&(e=this.getExpirationTimestamp(this.options.stdTTL)),o&&(e=this.getExpirationTimestamp(o));let a=0;if(e&&e>0&&(a=e),this.options.maxKeys){let{maxKeys:A}=this.options;if(A>-1&&this.store.size>=A)throw this.createError("Cache max keys amount exceeded",this.formatKey(n))}return this.store.set(i,{key:i,value:t,ttl:a}),this.emit("set",i,t,e),this._stats.incrementKSize(i),this._stats.incrementVSize(t),this._stats.setCount(this.store.size),!0}mset(n){if(!Array.isArray(n))throw this.createError("The keys argument has to be an array.");for(let t of n)this.set(t.key,t.value,t.ttl);return!0}get(n){let t=this.store.get(this.formatKey(n));if(t){if(t.ttl>0){if(t.ttl0){let n=this.options.checkperiod*1e3;this.intervalId=setInterval(()=>{this.checkData()},n).unref();return}this.intervalId=0}stopInterval(){this.intervalId!==0&&(clearInterval(this.intervalId),this.intervalId=0)}formatKey(n){return n.toString()}getExpirationTimestamp(n){if(typeof n=="string")return pd(n);let t=Date.now(),o=n*1e3;return t+o}checkData(){for(let[n,t]of this.store.entries())t.ttl>0&&t.ttl{let a={resolve:i,reject:e,weight:t,priority:o},A=Lse(this._queue,r=>o<=r.priority);A===-1&&t<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(t){return zVe(this,arguments,void 0,function*(o,i=1,e=0){let[a,A]=yield this.acquire(i,e);try{return yield o(a)}finally{A()}})}waitForUnlock(t=1,o=0){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return this._couldLockImmediately(t,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),VVe(this._weightedWaiters[t-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatchQueue()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatchQueue()}cancel(){this._queue.forEach(t=>t.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(t){let o=this._value;this._value-=t.weight,t.resolve([o,this._newReleaser(t.weight)])}_newReleaser(t){let o=!1;return()=>{o||(o=!0,this.release(t))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let t=this._value;t>0;t--){let o=this._weightedWaiters[t-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[t-1]=[])}else{let t=this._queue[0].priority;for(let o=this._value;o>0;o--){let i=this._weightedWaiters[o-1];if(!i)continue;let e=i.findIndex(a=>a.priority<=t);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(t,o){return(this._queue.length===0||this._queue[0].priorityt.priority<=i.priority);n.splice(o+1,0,t)}function Lse(n,t){for(let o=n.length-1;o>=0;o--)if(t(n[o]))return o;return-1}var WVe=function(n,t,o,i){function e(a){return a instanceof o?a:new o(function(A){A(a)})}return new(o||(o=Promise))(function(a,A){function r(c){try{g(i.next(c))}catch(I){A(I)}}function s(c){try{g(i.throw(c))}catch(I){A(I)}}function g(c){c.done?a(c.value):e(c.value).then(r,s)}g((i=i.apply(n,t||[])).next())})},ic=class{constructor(t){this._semaphore=new hH(1,t)}acquire(){return WVe(this,arguments,void 0,function*(t=0){let[,o]=yield this._semaphore.acquire(1,t);return o})}runExclusive(t,o=0){return this._semaphore.runExclusive(()=>t(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(t=0){return this._semaphore.waitForUnlock(1,t)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as AWe}from"crypto";var uH=ze(Hse(),1);var CH=class n extends Error{name="TimeoutError";constructor(t,o){super(t,o),Error.captureStackTrace?.(this,n)}},Kse=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function BH(n,t){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=t,r,s,c=new Promise((I,d)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){d(Kse(A));return}if(A&&(s=()=>{d(Kse(A))},A.addEventListener("abort",s,{once:!0})),n.then(I,d),o===Number.POSITIVE_INFINITY)return;let B=new CH;r=a.setTimeout.call(void 0,()=>{if(i){try{I(i())}catch(f){d(f)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?I():e instanceof Error?d(e):(B.message=e??`Promise timed out after ${o} milliseconds`,d(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,r),r=void 0},c}function fH(n,t,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],t)<=0?(i=++A,e-=a+1):e=a}return i}var $Ve=100,mE=class{#e=[];#A=0;enqueue(t,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:t};if(a===0){this.#e.length=0,this.#A=0,this.#e.push(A);return}if(this.#e.at(-1).priority>=i){this.#e.push(A);return}this.#t();let r=fH(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(r,0,A)}setPriority(t,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===t);if(i===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:t})}remove(t){let o=this.#e.findIndex((i,e)=>e$Ve&&this.#A>this.#e.length/2&&this.#t(),t?.run}filter(t){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);if(t.strict&&t.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(t.strict&&t.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=t.carryoverIntervalCount??t.carryoverConcurrencyCount??!1,this.#A=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#r=t.intervalCap,this.#i=t.interval,this.#d=t.strict,this.#I=new t.queueClass,this.#p=t.queueClass,this.concurrency=t.concurrency,t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);this.timeout=t.timeout,this.#C=t.autoStart===!1,this.#J()}#S(t){for(;this.#g=this.#i)this.#g++;else break}(this.#g>100&&this.#g>this.#c.length/2||this.#g===this.#c.length)&&(this.#c=this.#c.slice(this.#g),this.#g=0)}#m(t){this.#d?this.#c.push(t):this.#t++}#y(){this.#d?this.#c.length>this.#g&&this.#c.pop():this.#t>0&&this.#t--}#b(){return this.#c.length-this.#g}get#h(){return this.#A?!0:this.#d?this.#b()=this.#r){let i=this.#c[this.#g],e=this.#i-(t-i);return this.#T(e),!0}return!1}if(this.#n===void 0){let o=this.#a-t;if(o<0)this.#t=this.#e?this.#E:0;else return this.#T(o),!0}return!1}#T(t){this.#s===void 0&&(this.#s=setTimeout(()=>{this.#D()},t))}#M(){this.#n&&(clearInterval(this.#n),this.#n=void 0)}#P(){this.#s&&(clearTimeout(this.#s),this.#s=void 0)}#N(){if(this.#I.size===0){if(this.#M(),this.emit("empty"),this.#E===0){if(this.#P(),this.#d&&this.#g>0){let o=Date.now();this.#S(o)}this.emit("idle")}return!1}let t=!1;if(!this.#C){let o=Date.now(),i=!this.#w(o);if(this.#h&&this.#R){let e=this.#I.dequeue();this.#A||(this.#m(o),this.#x()),i&&this.#F(),this.emit("active"),e(),t=!0}}return t}#F(){this.#A||this.#n!==void 0||this.#d||(this.#n=setInterval(()=>{this.#k()},this.#i),this.#a=Date.now()+this.#i)}#k(){this.#d||(this.#n!==void 0&&(this.#t===0&&this.#E===0?this.#M():this.#a=Date.now()+this.#i),this.#t=this.#e?this.#E:0),this.#K(),this.#x()}#K(){for(;this.#N(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#K()}setPriority(t,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#I.setPriority(t,o)}async add(t,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#B++).toString()},o.timeout!==void 0&&!(Number.isFinite(o.timeout)&&o.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${o.timeout}\` (${typeof o.timeout})`);return new Promise((i,e)=>{let a=Symbol(`task-${o.id}`),A=()=>{},r=async()=>{A(),this.#E++,this.#f.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(d){throw this.#G(),this.#f.delete(a),d}let c=t({signal:o.signal});if(o.timeout!==void 0&&(c=BH(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#E} running, ${this.#I.size} waiting)`})),o.signal){let{signal:d}=o;c=Promise.race([c,new Promise((B,f)=>{g=()=>{f(d.reason)},d.addEventListener("abort",g,{once:!0})})])}let I=await c;i(I),this.emit("completed",I)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#f.delete(a),queueMicrotask(()=>{this.#_()})}};this.#I.enqueue(r,o);let s=()=>{if(this.#I instanceof mE){this.#I.remove(r);return}this.#I.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#N(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#Q.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#Q.add(A)}this.emit("add"),this.#N()})}async addAll(t,o){return Promise.all(t.map(async i=>this.add(i,o)))}start(){return this.#C?(this.#C=!1,this.#K(),this):this}pause(){this.#C=!0}clear(){for(let t of this.#Q)t();this.#I=new this.#p,this.#M(),this.#L(),this.emit("empty"),this.#E===0&&(this.#P(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#I.size!==0&&await this.#U("empty")}async onSizeLessThan(t){this.#I.sizethis.#I.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#U(t,o){let i=Array.isArray(t)?t:[t];return new Promise(e=>{let a=()=>{if(!(o&&!o())){for(let A of i)this.off(A,a);e()}};for(let A of i)this.on(A,a)})}get size(){return this.#I.size}sizeBy(t){return this.#I.filter(t).length}get pending(){return this.#E}get isPaused(){return this.#C}#J(){this.#A||(this.on("add",()=>{this.#I.size>0&&this.#x()}),this.on("next",()=>{this.#x()}))}#x(){this.#A||this.#o||(this.#o=!0,queueMicrotask(()=>{this.#o=!1,this.#L()}))}#G(){this.#A||(this.#y(),this.#x())}#L(){let t=this.#l;if(this.#A||this.#I.size===0){t&&(this.#l=!1,this.emit("rateLimitCleared"));return}let o;if(this.#d){let e=Date.now();this.#S(e),o=this.#b()}else o=this.#t;let i=o>=this.#r;i!==t&&(this.#l=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#l}get isSaturated(){return this.#E===this.#u&&this.#I.size>0||this.isRateLimited&&this.#I.size>0}get runningTasks(){return[...this.#f.values()].map(t=>({...t,timeoutRemaining:t.timeout?Math.max(0,t.startTime+t.timeout-Date.now()):void 0}))}};var Wb=class{constructor(t,o){this.store=t,this.logger=o,this.queues=new Map}getQueue(t){return this.queues.has(t)||this.queues.set(t,new hd({concurrency:1})),this.queues.get(t)}async processOperations(t,o,i,e,a){let A=t[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let r=[],s={};for(let g in A)A[g]===null?r.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),r.length>0&&await this.processDeletions(o,r,i,e,a)})}async processDeletions(t,o,i,e,a){if(a)for(let A of o)i[t]?.[A]?(i[t][A]=null,e[t][A]=null):this.logger.warn(`Skipping deletion of non-existent ${t} in transaction: ${A}`);else{let A=await this.store.get(t,o);for(let r of o)A[r]?(i[t][r]=null,e[t][r]=null):this.logger.warn(`Skipping deletion of non-existent ${t}: ${r}`)}}async validateDeletions(t,o){let i=t[o];if(i)return this.getQueue(o).add(async()=>{let e=Object.keys(i).filter(A=>i[A]===null);if(e.length===0)return;let a=await this.store.get(o,e);for(let A of e)a[A]||(this.logger.warn(`Skipping deletion of non-existent ${o}: ${A}`),delete t[o][A])})}};var Yse=(n,t,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new eWe,a=new Map,A=new Map,r=new Map,s=new Wb(n,t);function g(Q){return a.has(Q)||a.set(Q,new hd({concurrency:1})),a.get(Q)}function c(Q){return A.has(Q)||(A.set(Q,new ic),r.set(Q,0)),A.get(Q)}function I(Q){let y=r.get(Q)??0;r.set(Q,y+1)}function d(Q){let y=(r.get(Q)??1)-1;if(r.set(Q,y),y<=0){let m=A.get(Q);m&&!m.isLocked()&&(A.delete(Q),r.delete(Q))}}function B(){return!!e.getStore()}async function f(Q){if(Object.keys(Q).length===0){t.trace("no mutations in transaction");return}t.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(Q,y);let T=m.cache[Q]||{},_=y.filter(H=>!(H in T));if(_.length>0){m.dbQueries++,t.trace({type:Q,count:_.length},"fetching missing keys in transaction");let H=await c(Q).runExclusive(()=>n.get(Q,_));m.cache[Q]=m.cache[Q]||{},Object.assign(m.cache[Q],H)}let R={};for(let H of y){let F=m.cache[Q]?.[H];F!=null&&(R[H]=F)}return R},set:async Q=>{let y=e.getStore();if(!y){let m=Object.keys(Q);for(let T of m){let _=T;_==="pre-key"&&await s.validateDeletions(Q,_)}await Promise.all(m.map(T=>g(T).add(async()=>{let _={[T]:Q[T]};await n.set(_)})));return}t.trace({types:Object.keys(Q)},"caching in transaction");for(let m in Q){let T=m;y.cache[T]=y.cache[T]||{},y.mutations[T]=y.mutations[T]||{},T==="pre-key"?await s.processOperations(Q,T,y.cache,y.mutations,!0):(Object.assign(y.cache[T],Q[T]),Object.assign(y.mutations[T],Q[T]))}},isInTransaction:B,transaction:async(Q,y)=>{if(e.getStore())return t.trace("reusing existing transaction context"),Q();let T=c(y);I(y);try{return await T.runExclusive(async()=>{let _={cache:{},mutations:{},dbQueries:0};t.trace("entering transaction");try{let R=await e.run(_,Q);return await f(_.mutations),t.trace({dbQueries:_.dbQueries},"transaction completed"),R}catch(R){throw t.error({error:R},"transaction failed, rolling back"),R}})}finally{d(y)}}}},jse=n=>{let t=n.me?.id;if(!t)throw new xse.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return t},Jse=()=>{let n=Dr.generateKeyPair();return{noiseKey:Dr.generateKeyPair(),pairingEphemeralKeyPair:Dr.generateKeyPair(),signedIdentityKey:n,signedPreKey:PD(n,1),registrationId:j$(),advSecretKey:AWe(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},registered:!1,pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0,additionalData:void 0}};import{mkdir as tWe,readFile as rWe,stat as aWe,unlink as iWe,writeFile as oWe}from"fs/promises";import{join as QH}from"path";var qse=new Map,yH=n=>{let t=qse.get(n);return t||(t=new ic,qse.set(n,t)),t},zse=async n=>{let t=async(r,s)=>{let g=QH(n,a(s));return yH(g).acquire().then(async I=>{try{await oWe(g,JSON.stringify(r,jB.replacer))}finally{I()}})},o=async r=>{try{let s=QH(n,a(r));return await yH(s).acquire().then(async c=>{try{let I=await rWe(s,{encoding:"utf-8"});return JSON.parse(I,jB.reviver)}finally{c()}})}catch{return null}},i=async r=>{try{let s=QH(n,a(r));return yH(s).acquire().then(async c=>{try{await iWe(s)}catch{}finally{c()}})}catch{}},e=await aWe(n).catch(()=>{});if(e){if(!e.isDirectory())throw new Error(`found something that is not a directory at ${n}, either delete it or specify a different location`)}else await tWe(n,{recursive:!0});let a=r=>r?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||Jse();return{state:{creds:A,keys:{get:async(r,s)=>{let g={};return await Promise.all(s.map(async c=>{let I=await o(`${r}-${c}.json`);r==="app-state-sync-key"&&I&&(I=ne.Message.AppStateSyncKeyData.fromObject(I)),g[c]=I})),g},set:async r=>{let s=[];for(let g in r)for(let c in r[g]){let I=r[g][c],d=`${g}-${c}.json`;s.push(I?t(I,d):i(d))}await Promise.all(s)}}},saveCreds:async()=>t(A,"creds.json")}};var nWe=192,sWe=async(n,{thumbnailWidth:t,fetchOpts:o})=>{let i=await Hb(n,o);return await HU(i,t)},Vse=async(n,t={thumbnailWidth:nWe,fetchOpts:{timeout:3e3}})=>{try{let o=0,i=5,{getLinkPreview:e}=await import("link-preview-js"),a=n;!n.startsWith("https://")&&!n.startsWith("http://")&&(a="https://"+a);let A=await e(a,{...t.fetchOpts,followRedirects:"follow",handleRedirects:(r,s)=>{let g=new URL(r),c=new URL(s);return o>=i?!1:c.hostname===g.hostname||c.hostname==="www."+g.hostname||"www."+c.hostname===g.hostname?(o+=1,!0):!1},headers:t.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[r]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:r};if(t.uploadImage){let{imageMessage:g}=await Kf({image:{url:r}},{upload:t.uploadImage,mediaTypeOverride:"thumbnail-link",options:t.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=r?(await sWe(r,t)).buffer:void 0}catch(g){t.logger?.debug({err:g.stack,url:a},"error in generating thumbnail")}return s}}catch(o){if(!o.message.includes("receive a valid"))throw o}};import CWe from"events";var SH=ze(jr(),1);var gWe=/^1313555\d{4}$|^131655500\d{2}$/;function cWe(n){if(!n)return!1;let t=n.split("@")[0]??"";return t==="0"||gWe.test(t)||mh(n)?!1:!!(Tt(n)||qA(n)||wr(n)||Ea(n)||n.endsWith("@c.us"))}var Zb=604800,IWe=4,_I="__index";async function Xb(n){let o=(await n.get("tctoken",[_I]))[_I];if(!o?.token?.length)return[];try{let i=JSON.parse(Buffer.from(o.token).toString());return Array.isArray(i)?i.filter(e=>typeof e=="string"&&e.length>0&&e!==_I):[]}catch{return[]}}async function SE(n,t){let o=await Xb(n),i=new Set(o);for(let e of t)e&&e!==_I&&i.add(e);return{[_I]:{token:Buffer.from(JSON.stringify([...i]))}}}function Ed(n){if(n==null)return!0;let t=typeof n=="string"?parseInt(n):n;if(isNaN(t))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/Zb)-(IWe-1))*Zb;return ti}async function rg(n,t){return qA(n)?n:await t(n)??n}async function Zf(n,t,o,i){return t?qA(n)?n:await o(n)??n:qA(n)&&i?await i(n)??n:n}async function mH({authState:n,jid:t,baseContent:o=[],getLIDForPN:i}){try{let e=await rg(t,i),A=(await n.keys.get("tctoken",[e]))?.[e],r=A?.token,s=A?.timestamp;if(!r?.length||s===void 0||Ed(s)){if(r){let g=A?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:A.senderTimestamp}:null;await n.keys.set({tctoken:{[e]:g}})}return o.length>0?o:void 0}return o.push({tag:"tctoken",attrs:{t:String(s)},content:r}),o}catch{return o.length>0?o:void 0}}async function wE({result:n,fallbackJid:t,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=le(n,"tokens");if(!a)return;let A=PA(a,"token");for(let r of A){if(r.attrs.type!=="trusted_contact"||!(r.content instanceof Uint8Array))continue;let s=CA(t||r.attrs.jid);if(!cWe(s))continue;let g=await rg(s,i),I=(await o.get("tctoken",[g]))[g],d=I?.timestamp?Number(I.timestamp):0,B=r.attrs.t?Number(r.attrs.t):0;B&&(d>0&&d>B||(await o.set({tctoken:{[g]:{...I,token:Buffer.from(r.content),timestamp:r.attrs.t}}}),e?.(g)))}}var lWe=new Set([RA.CALL_MISSED_GROUP_VIDEO,RA.CALL_MISSED_GROUP_VOICE,RA.CALL_MISSED_VIDEO,RA.CALL_MISSED_VOICE]),dWe=new Set([RA.GROUP_PARTICIPANT_ADD]);async function pWe(n,t,o,i){let e=t.lidMapping.getLIDForPN.bind(t.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?qr(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let I=CA(g.id),d=await rg(I,e);a.push({storageJid:d,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?qr(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),r=await o.get("tctoken",A),s={};for(let g of a){let c=r[g.storageJid],I=c?.timestamp?Number(c.timestamp):0;I>0&&I>=g.ts||(s[g.storageJid]={...c,token:g.token,timestamp:String(g.ts),...g.senderTs!==void 0?{senderTimestamp:g.senderTs}:{}})}if(Object.keys(s).length){i?.debug({count:Object.keys(s).length},"storing tctokens from history sync");try{let g=await SE(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Zse=(n,t,o)=>{wr(n.key.remoteJid)||Ea(n.key.remoteJid)?n.key.remoteJid=Sr(fA(n.key?.remoteJid)?.user,wr(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=CA(n.key.remoteJid),wr(n.key.participant)||Ea(n.key.participant)?n.key.participant=Sr(fA(n.key.participant)?.user,wr(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=CA(n.key.participant);let i=ya(n.message);i?.reactionMessage&&e(i.reactionMessage.key),i?.pollUpdateMessage&&e(i.pollUpdateMessage.pollCreationMessageKey);function e(a){n.key.fromMe||(a.fromMe=a.fromMe?!1:kt(a.participant||a.remoteJid,t)||kt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},wH=n=>{let t=ya(n.message),o=!!xf(t);return(!!t||lWe.has(n.messageStubType)||dWe.has(n.messageStubType))&&o&&!t?.protocolMessage&&!t?.reactionMessage&&!t?.pollUpdateMessage},DH=n=>!n.key.fromMe&&!n.messageStubType,hWe=({remoteJid:n,participant:t,fromMe:o})=>{if(!n)throw new SH.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:t,fromMe:o}});if(PB(n)&&!Yg(n)&&!o){if(!t)throw new SH.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return t}return n};function EWe({encPayload:n,encIv:t},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([I(i),I(o),I(a),I("Event Response"),new Uint8Array([1])]),r=qn(e,new Uint8Array(32),"sha256"),s=qn(A,r,"sha256"),g=I(`${i}\0${a}`),c=Yl(n,s,t,g);return ne.Message.EventResponseMessage.decode(c);function I(d){return Buffer.from(d)}}var uWe=async(n,{shouldProcessHistoryMsg:t,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:r,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:I}=e,d={id:CA(hWe(n.key))},B=wH(n);B&&(d.messages=[{message:n}],d.conversationTimestamp=qr(n.messageTimestamp),DH(n)&&(d.unreadCount=(d.unreadCount||0)+1));let f=ya(n.message);(B||f?.reactionMessage?.key?.fromMe)&&I?.unarchiveChats&&(d.archived=!1,d.readOnly=!1);let Q=f?.protocolMessage;if(Q){let y=new Set([ne.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,ne.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,ne.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,ne.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(Q.type!==null&&Q.type!==void 0&&y.has(Q.type)&&!n.key.fromMe){r?.warn({msgId:n.key.id,type:Q.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(Q.type){case ne.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=Q.historySyncNotification,T=t,_=!e.processedHistoryMessages?.length;if(r?.info({histNotification:m,process:T,id:n.key.id,isLatest:_},"got history notification"),T){m.syncType!==ne.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let G=await fse(m,s,r);G.lidPnMappings?.length&&(r?.debug({count:G.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(G.lidPnMappings).catch(V=>r?.warn({err:V},"failed to store LID-PN mappings from history sync"))),await pWe(G.chats,a,A,r),i.emit("messaging-history.set",{...G,isLatest:m.syncType!==ne.HistorySync.HistorySyncType.ON_DEMAND?_:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case ne.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let R=Q.appStateSyncKeyShare.keys;if(R?.length){let G="";await A.transaction(async()=>{let V=[];for(let{keyData:U,keyId:N}of R){let k=Buffer.from(N.keyId).toString("base64");V.push(k),await A.set({"app-state-sync-key":{[k]:U}}),G=k}r?.info({newAppStateSyncKeyId:G,newKeys:V},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:G})}else r?.info({protocolMsg:Q},"recv app state sync with 0 keys");break;case ne.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:Q.key.id},update:{message:null,messageStubType:RA.REVOKE,key:n.key}}]);break;case ne.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(d,{ephemeralSettingTimestamp:qr(n.messageTimestamp),ephemeralExpiration:Q.ephemeralExpiration||null});break;case ne.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let H=Q.peerDataOperationRequestResponseMessage;if(H){let G=H.peerDataOperationResult||[];for(let V of G){let U=V?.placeholderMessageResendResponse;if(U?.webMessageInfoBytes)try{let N=ne.WebMessageInfo.decode(U.webMessageInfoBytes),k=N.key?.id,J=k?await o?.get(k):void 0;k&&await o?.del(k);let X;J&&typeof J=="object"?(J.message=N.message,N.messageTimestamp&&(J.messageTimestamp=N.messageTimestamp),X=J):X=N,r?.debug({msgId:k,requestId:H.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[X],type:"notify",requestId:H.stanzaId})}catch(N){r?.warn({err:N,stanzaId:H.stanzaId},"failed to decode placeholder resend response")}}}break;case ne.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:Q.key?.id},update:{message:{editedMessage:{message:Q.editedMessage}},messageTimestamp:Q.timestampMs?Math.floor(qr(Q.timestampMs)/1e3):n.messageTimestamp}}]);break;case ne.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let F=Q.memberLabel;F?.label&&i.emit("group.member-tag.update",{groupId:d.id,label:F.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case ne.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let L=Q.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:z}=ne.LIDMigrationMappingSyncPayload.decode(L);r?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:z},"got lid mappings and chat db migration timestamp");let K=[];for(let{pn:G,latestLid:V,assignedLid:U}of q){let N=V||U;K.push({lid:`${N}@lid`,pn:`${G}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(K),K.length)for(let{pn:G,lid:V}of K)await a.migrateSession(G,V)}}else if(f?.reactionMessage){let y={...f.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:f.reactionMessage?.key}])}else if(f?.encEventResponseMessage){let y=f.encEventResponseMessage,m=y.eventCreationMessageKey,T=await g(m);if(T)try{let _=CA(c),R=m.participant||m.remoteJid,H=qA(R)?await a.lidMapping.getPNForLID(R):R,F=Mh({remoteJid:CA(H),fromMe:_===H},_),L=Mh(n.key,_),q=T?.messageContextInfo?.messageSecret;if(!q)r?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let z=EWe(y,{eventEncKey:q,eventCreatorJid:F,eventMsgId:m.id,responderJid:L}),K={eventResponseMessageKey:n.key,senderTimestampMs:z.timestampMs,response:z};i.emit("messages.update",[{key:m,update:{eventResponses:[K]}}])}}catch(_){r?.warn({err:_,creationMsgKey:m},"failed to decrypt event response")}else r?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,T=F=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:F}),_=F=>{i.emit("groups.update",[{id:y,...F,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},R=(F,L,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:F.lid,participantPn:F.pn,action:L,method:q})},H=()=>m.find(F=>kt(c,F.phoneNumber));switch(n.messageStubType){case RA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("modify");break;case RA.GROUP_PARTICIPANT_LEAVE:case RA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("remove"),H()&&(d.readOnly=!0);break;case RA.GROUP_PARTICIPANT_ADD:case RA.GROUP_PARTICIPANT_INVITE:case RA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],H()&&(d.readOnly=!1),T("add");break;case RA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("demote");break;case RA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("promote");break;case RA.GROUP_CHANGE_ANNOUNCE:let F=n.messageStubParameters?.[0];_({announce:F==="true"||F==="on"});break;case RA.GROUP_CHANGE_RESTRICT:let L=n.messageStubParameters?.[0];_({restrict:L==="true"||L==="on"});break;case RA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];d.name=q,_({subject:q});break;case RA.GROUP_CHANGE_DESCRIPTION:let z=n.messageStubParameters?.[0];d.description=z,_({desc:z});break;case RA.GROUP_CHANGE_INVITE_LINK:let K=n.messageStubParameters?.[0];_({inviteCode:K});break;case RA.GROUP_MEMBER_ADD_MODE:let G=n.messageStubParameters?.[0];_({memberAddMode:G==="all_member_add"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let V=n.messageStubParameters?.[0];_({joinApprovalMode:V==="on"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let U=JSON.parse(n.messageStubParameters?.[0]),N=n.messageStubParameters?.[1],k=n.messageStubParameters?.[2];R(U,N,k);break}}Object.keys(d).length>1&&i.emit("chats.update",[d])},Xse=uWe;var BWe=["messaging-history.set","chats.upsert","chats.update","chats.delete","contacts.upsert","contacts.update","messages.upsert","messages.update","messages.delete","messages.reaction","message-receipt.update","groups.update"],fWe=new Set(BWe),$se=n=>{let t=new CWe,o=new Set,i=OH(),e=!1,a=null,A=null,r=0,s=1e4,g=3e4;t.on("event",d=>{for(let B in d)t.emit(B,d[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,r=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),I())},g)),r++}function I(){if(!e)return!1;n.debug({bufferCount:r},"Flushing event buffer"),e=!1,r=0,a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.size>s&&(n.debug({cacheSize:o.size},"Clearing history cache"),o.clear());let d=OH(),B=Object.values(i.chatUpdates),f=0;for(let y of B)y.conditional&&(f+=1,d.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let Q=yWe(i);return Object.keys(Q).length&&t.emit("event",Q),i=d,n.trace({conditionalChatUpdatesLeft:f},"released buffered events"),!0}return{process(d){let B=async f=>{await d(f)};return t.on("event",B),()=>{t.off("event",B)}},emit(d,B){if(d==="messages.upsert"){let{type:f}=B,Q=Object.values(i.messageUpserts);if(Q.length>0){let y=Q[0].type;y!==f&&(n.debug({bufferedType:y,newType:f},"messages.upsert type mismatch, emitting buffered messages"),t.emit("event",{"messages.upsert":{messages:Q.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&fWe.has(d)?(QWe(i,o,d,B,n),!0):t.emit("event",{[d]:B})},isBuffering(){return e},buffer:c,flush:I,createBufferedFunction(d){return async(...B)=>{c();try{let f=await d(...B);return r===1&&setTimeout(()=>{e&&r===1&&I()},100),f}catch(f){throw f}finally{r=Math.max(0,r-1),r===0&&(A||(A=setTimeout(I,100)))}}},on:(...d)=>t.on(...d),off:(...d)=>t.off(...d),removeAllListeners:(...d)=>t.removeAllListeners(...d),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=OH(),e=!1,r=0,t.removeAllListeners(),n.debug("Event buffer destroyed")}}},OH=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function QWe(n,t,o,i,e){switch(o){case"messaging-history.set":for(let Q of i.chats){let y=Q.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=Q.endOfHistoryTransferType),!m&&!t.has(y)&&(n.historySets.chats[y]=Q,t.add(y),a(Q))}for(let Q of i.contacts){let y=n.historySets.contacts[Q.id];if(y)Object.assign(y,LD(Q));else{let m=`c:${Q.id}`,T=Q.notify||Q.name||Q.verifiedName;(!t.has(m)||T)&&(n.historySets.contacts[Q.id]=Q,t.add(m))}}for(let Q of i.messages){let y=DE(Q.key);!n.historySets.messages[y]&&!t.has(y)&&(n.historySets.messages[y]=Q,t.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let Q=new Map,y=T=>`${T.userJid||""}:${T.leaveTs||""}:${T.leaveReason||""}`,m=T=>{let _=T.groupJid??JSON.stringify(T),R=Q.get(_);if(!R){Q.set(_,{...T,pastParticipants:[...T.pastParticipants||[]]});return}let H=new Set((R.pastParticipants||[]).map(y));for(let F of T.pastParticipants||[]){let L=y(F);H.has(L)||(R.pastParticipants.push(F),H.add(L))}};for(let T of n.historySets.pastParticipants||[])m(T);for(let T of i.pastParticipants)m(T);n.historySets.pastParticipants=[...Q.values()]}n.historySets.progress=i.progress,n.historySets.chunkOrder=i.chunkOrder,n.historySets.peerDataRequestSessionId=i.peerDataRequestSessionId,n.historySets.isLatest=i.isLatest||n.historySets.isLatest;break;case"chats.upsert":for(let Q of i){let y=Q.id||"",m=n.chatUpserts[y];y&&!m&&(m=n.historySets.chats[y],m&&e.debug({chatId:y},"absorbed chat upsert in chat set")),m?m=$b(m,Q):(m=Q,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let Q of i){let y=Q.id,m=Q.conditional?Q.conditional(n):!0;if(m){delete Q.conditional;let T=n.historySets.chats[y]||n.chatUpserts[y];if(T)$b(T,Q);else{let _=n.chatUpdates[y]||{};n.chatUpdates[y]=$b(_,Q)}}else m===void 0&&(n.chatUpdates[y]=Q);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let Q of i)n.chatDeletes.has(Q)||n.chatDeletes.add(Q),n.chatUpdates[Q]&&delete n.chatUpdates[Q],n.chatUpserts[Q]&&delete n.chatUpserts[Q],n.historySets.chats[Q]&&delete n.historySets.chats[Q];break;case"contacts.upsert":for(let Q of i){let y=n.contactUpserts[Q.id];y||(y=n.historySets.contacts[Q.id],y&&e.debug({contactId:Q.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,LD(Q)):(y=Q,n.contactUpserts[Q.id]=y),n.contactUpdates[Q.id]&&(y=Object.assign(n.contactUpdates[Q.id],LD(Q)),delete n.contactUpdates[Q.id])}break;case"contacts.update":let r=i;for(let Q of r){let y=Q.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,Q);else{let T=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(T,Q)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let Q of s){let y=DE(Q.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(Q.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(Q,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=Q:n.messageUpserts[y]={message:Q,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:Q,update:y}of c){let m=DE(Q),T=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(T)Object.assign(T,y),y.status===yh.READ&&!Q.fromMe&&A(T);else{let _=n.messageUpdates[m]||{key:Q,update:{}};Object.assign(_.update,y),n.messageUpdates[m]=_}}break;case"messages.delete":let I=i;if("keys"in I){let{keys:Q}=I;for(let y of Q){let m=DE(y);n.messageDeletes[m]||(n.messageDeletes[m]=y),n.messageUpserts[m]&&delete n.messageUpserts[m],n.messageUpdates[m]&&delete n.messageUpdates[m]}}break;case"messages.reaction":let d=i;for(let{key:Q,reaction:y}of d){let m=DE(Q),T=n.messageUpserts[m];T?VU(T.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:Q,reactions:[]},VU(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:Q,receipt:y}of B){let m=DE(Q),T=n.messageUpserts[m];T?zU(T.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:Q,userReceipt:[]},zU(n.messageReceipts[m],y))}break;case"groups.update":let f=i;for(let Q of f){let y=Q.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,Q))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(r){let s=r.id||"",g=n.chatUpdates[s];if(g){let c=g.conditional?g.conditional(n):!0;c?(delete g.conditional,e.debug({chatId:s},"absorbed chat update in existing chat"),Object.assign(r,$b(g,r)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(r){let s=r.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];wH(r)&&DH(r)&&typeof g?.unreadCount=="number"&&g.unreadCount>0&&(e.debug({chatId:g.id},"decrementing chat counter"),g.unreadCount-=1,g.unreadCount===0&&delete g.unreadCount)}}function yWe(n){let t={};n.historySets.empty||(t["messaging-history.set"]={chats:Object.values(n.historySets.chats),messages:Object.values(n.historySets.messages),contacts:Object.values(n.historySets.contacts),pastParticipants:n.historySets.pastParticipants,syncType:n.historySets.syncType,progress:n.historySets.progress,isLatest:n.historySets.isLatest,chunkOrder:n.historySets.chunkOrder,peerDataRequestSessionId:n.historySets.peerDataRequestSessionId});let o=Object.values(n.chatUpserts);o.length&&(t["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(t["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(t["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;t["messages.upsert"]={messages:a.map(f=>f.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(t["messages.update"]=A);let r=Object.values(n.messageDeletes);r.length&&(t["messages.delete"]={keys:r});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:f})=>f.flatMap(Q=>({key:B,reaction:Q})));s.length&&(t["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:f})=>f.flatMap(Q=>({key:B,receipt:Q})));g.length&&(t["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(t["contacts.upsert"]=c);let I=Object.values(n.contactUpdates);I.length&&(t["contacts.update"]=I);let d=Object.values(n.groupUpdates);return d.length&&(t["groups.update"]=d),t}function $b(n,t){return t.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,t.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof t.unreadCount=="number"&&(t={...t},t.unreadCount>=0&&(t.unreadCount=Math.max(t.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,t)}var DE=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var mWe=512,bH="\0",ege=3600*1e3,SWe=3e3,oc;(function(n){n[n.UnknownError=0]="UnknownError",n[n.SignalErrorNoSession=1]="SignalErrorNoSession",n[n.SignalErrorInvalidKey=2]="SignalErrorInvalidKey",n[n.SignalErrorInvalidKeyId=3]="SignalErrorInvalidKeyId",n[n.SignalErrorInvalidMessage=4]="SignalErrorInvalidMessage",n[n.SignalErrorInvalidSignature=5]="SignalErrorInvalidSignature",n[n.SignalErrorFutureMessage=6]="SignalErrorFutureMessage",n[n.SignalErrorBadMac=7]="SignalErrorBadMac",n[n.SignalErrorInvalidSession=8]="SignalErrorInvalidSession",n[n.SignalErrorInvalidMsgKey=9]="SignalErrorInvalidMsgKey",n[n.BadBroadcastEphemeralSetting=10]="BadBroadcastEphemeralSetting",n[n.UnknownCompanionNoPrekey=11]="UnknownCompanionNoPrekey",n[n.AdvFailure=12]="AdvFailure",n[n.StatusRevokeDelay=13]="StatusRevokeDelay"})(oc||(oc={}));var Age=new Set([oc.SignalErrorInvalidMessage,oc.SignalErrorBadMac]),eM=class{constructor(t,o){this.logger=t,this.recentMessagesMap=new Kg({max:mWe,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(bH);if(a>-1){let A=e.slice(a+bH.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Kg({ttl:ege*2,ttlAutopurge:!0}),this.retryCounters=new Kg({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Kg({max:1024,ttl:900*1e3,ttlAutopurge:!0}),this.pendingPhoneRequests={},this.maxMsgRetryCount=5,this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0},this.maxMsgRetryCount=o}addRecentMessage(t,o,i){let e={to:t,id:o},a=this.keyToString(e);this.recentMessagesMap.set(a,{message:i,timestamp:Date.now()}),this.messageKeyIndex.set(o,a),this.logger.debug(`Added message to retry cache: ${t}/${o}`)}getRecentMessage(t,o){let i={to:t,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(t,o,i){if(!o)return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&Age.has(i))return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:t,errorCode:oc[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${oc[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(t);return!a||e-a>ege?(this.sessionRecreateHistory.set(t,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(t){if(t===void 0||t==="")return;let o=parseInt(t,10);if(!Number.isNaN(o))return o>=oc.UnknownError&&o<=oc.StatusRevokeDelay?o:oc.UnknownError}isMacError(t){return t!==void 0&&Age.has(t)}incrementRetryCount(t){return this.retryCounters.set(t,(this.retryCounters.get(t)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(t)}getRetryCount(t){return this.retryCounters.get(t)||0}hasExceededMaxRetries(t){return this.getRetryCount(t)>=this.maxMsgRetryCount}markRetrySuccess(t){this.statistics.successfulRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}markRetryFailed(t){this.statistics.failedRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}schedulePhoneRequest(t,o,i=SWe){this.cancelPendingPhoneRequest(t),this.pendingPhoneRequests[t]=setTimeout(()=>{delete this.pendingPhoneRequests[t],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${t} with ${i}ms delay`)}cancelPendingPhoneRequest(t){let o=this.pendingPhoneRequests[t];o&&(clearTimeout(o),delete this.pendingPhoneRequests[t],this.logger.debug(`Cancelled pending phone request for message ${t}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let t of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(t);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(t,o,i){this.baseKeys.set(`${t}:${o}`,i)}hasSameBaseKey(t,o,i){let e=this.baseKeys.get(`${t}:${o}`);if(!e||e.length!==i.length)return!1;for(let a=0;a["Ubuntu",n,"22.04.4"],macOS:n=>["Mac OS",n,"14.4.1"],baileys:n=>["Baileys",n,"6.5.0"],windows:n=>["Windows",n,"10.0.22631"],android:n=>[n,"Android",""],appropriate:n=>[OWe[wWe()]||"Ubuntu",n,DWe()]};var Wn;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.CHROME=1]="CHROME",n[n.EDGE=2]="EDGE",n[n.FIREFOX=3]="FIREFOX",n[n.IE=4]="IE",n[n.OPERA=5]="OPERA",n[n.SAFARI=6]="SAFARI",n[n.ELECTRON=7]="ELECTRON",n[n.UWP=8]="UWP",n[n.OTHER_WEB_CLIENT=9]="OTHER_WEB_CLIENT"})(Wn||(Wn={}));var bWe={Chrome:Wn.CHROME,Edge:Wn.EDGE,Firefox:Wn.FIREFOX,IE:Wn.IE,Opera:Wn.OPERA,Safari:Wn.SAFARI},MWe=([n,t])=>t==="Desktop"?n==="Windows"?Wn.UWP:Wn.ELECTRON:bWe[t]||Wn.OTHER_WEB_CLIENT,MH=n=>MWe(n).toString(),tge=(n,t,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,t,o,i,MH(e)].join(",");async function rge(n,t){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!le(n,"identity"))return{action:"no_identity_node"};t.logger.info({jid:o},"identity changed");let e=fA(o);if(e?.device&&e.device!==0)return t.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(t.meId&&(kt(o,t.meId)||t.meLid&&kt(o,t.meLid)))return t.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(t.debounceCache.get(o))return t.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};t.debounceCache.set(o,!0);let A=!K$(n.attrs.offline);if(!(await t.validateSession(o)).exists)return t.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(t.logger.debug({jid:o},"old session exists, will refresh session"),A)return t.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};t.onBeforeSessionRefresh?.(o);try{return await t.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return t.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function age(n,t,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return t&&(a.attrs.error=t.toString()),e.participant&&(a.attrs.participant=e.participant),e.recipient&&(a.attrs.recipient=e.recipient),e.type&&(a.attrs.type=e.type),i==="message"&&o&&(a.attrs.from=o),a}function _We(n){return n===null||n===""}function TWe(n){return n>2147483647||n<-2147483648?n&4294967295:n}function ige(n){let t=0;if(!_We(n))for(let o=0;oo.iteration===t)}addSenderMessageKey(t){this.senderKeyStateStructure.senderMessageKeys.push({iteration:t.getIteration(),seed:t.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(t){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===t);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new ud(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var nc=class n{constructor(t){if(this.MAX_STATES=5,this.senderKeyStates=[],t)for(let o of t)this.senderKeyStates.push(new Cd(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(t){return t===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===t)}addSenderKeyState(t,o,i,e){this.senderKeyStates.push(new Cd(t,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(t,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new Cd(t,o,i,e))}serialize(){return this.senderKeyStates.map(t=>t.getStructure())}static deserialize(t){let o=Buffer.from(t).toString("utf-8"),i=JSON.parse(o,jB.reviver);return new n(i)}};var sge=ze(Vc(),1);import*as tM from"crypto";function gge(){return tM.randomBytes(32)}function cge(){return tM.randomInt(2147483647)}function Ige(n){return n||(n=(0,sge.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var Bd=class{constructor(){this.UNSUPPORTED_VERSION=1,this.CURRENT_VERSION=3,this.WHISPER_TYPE=2,this.PREKEY_TYPE=3,this.SENDERKEY_TYPE=4,this.SENDERKEY_DISTRIBUTION_TYPE=5,this.ENCRYPTED_MESSAGE_OVERHEAD=53}};var fd=class extends Bd{constructor(t,o,i,e,a){if(super(),a)try{let A=a.slice(1),r=ne.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=r.id,this.iteration=r.iteration,this.chainKey=typeof r.chainKey=="string"?Buffer.from(r.chainKey,"base64"):r.chainKey,this.signatureKey=typeof r.signingKey=="string"?Buffer.from(r.signingKey,"base64"):r.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=t,this.iteration=o,this.chainKey=i,this.signatureKey=e;let r=ne.SenderKeyDistributionMessage.encode(ne.SenderKeyDistributionMessage.create({id:t,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),r])}}intsToByteHighAndLow(t,o){return((t<<4|o)&255)%256}serialize(){return this.serialized}getType(){return this.SENDERKEY_DISTRIBUTION_TYPE}getIteration(){return this.iteration}getChainKey(){return this.chainKey}getSignatureKey(){return this.signatureKey}getId(){return this.id}};var OE=class{constructor(t){this.senderKeyStore=t}async process(t,o){let i=await this.senderKeyStore.loadSenderKey(t);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(t,i)}async create(t){let o=await this.senderKeyStore.loadSenderKey(t);if(o.isEmpty()){let e=cge(),a=gge(),A=Ige();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(t,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new fd(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var aM=ze(Ll(),1);var rM=ze(Vc(),1);var bE=class extends Bd{constructor(t,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],r=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=ne.SenderKeyMessage.decode(r).toJSON();this.serialized=a,this.messageVersion=(A&255)>>4,this.keyId=g.id,this.iteration=g.iteration,this.ciphertext=typeof g.ciphertext=="string"?Buffer.from(g.ciphertext,"base64"):g.ciphertext,this.signature=s}else{let A=((this.CURRENT_VERSION<<4|this.CURRENT_VERSION)&255)%256,r=Buffer.from(i),s=ne.SenderKeyMessage.encode(ne.SenderKeyMessage.create({id:t,iteration:o,ciphertext:r})).finish(),g=this.getSignature(e,Buffer.concat([Buffer.from([A]),s]));this.serialized=Buffer.concat([Buffer.from([A]),s,Buffer.from(g)]),this.messageVersion=this.CURRENT_VERSION,this.keyId=t,this.iteration=o,this.ciphertext=r,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(t){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,rM.verifySignature)(t,o,i))throw new Error("Invalid signature!")}getSignature(t,o){return Buffer.from((0,rM.calculateSignature)(t,o))}serialize(){return this.serialized}getType(){return 4}};var ME=class{constructor(t,o){this.senderKeyStore=t,this.senderKeyName=o}async encrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for encryption");let i=o.getSenderKeyState();if(!i)throw new Error("No session to encrypt message");let e=i.getSenderChainKey().getIteration(),a=this.getSenderKey(i,e===0?0:e+1),A=await this.getCipherText(a.getIv(),a.getCipherKey(),t),r=new bE(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),r.serialize()}async decrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new bE(null,null,null,null,t),e=o.getSenderKeyState(i.getKeyId());if(!e)throw new Error("No session found to decrypt message");i.verifySignature(e.getSigningKeyPublic());let a=this.getSenderKey(e,i.getIteration()),A=await this.getPlainText(a.getIv(),a.getCipherKey(),i.getCipherText());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),A}getSenderKey(t,o){let i=t.getSenderChainKey();if(i.getIteration()>o){if(t.hasSenderMessageKey(o)){let e=t.removeSenderMessageKey(o);if(!e)throw new Error("No sender message key found for iteration");return e}throw new Error(`Received message with old counter: ${i.getIteration()}, ${o}`)}if(o-i.getIteration()>2e3)throw new Error("Over 2000 messages into the future!");for(;i.getIteration()0){let r=[...i];this.logger.trace(`Batch fetching ${r.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",r);for(let g of r){let c=s[g];c&&(e.set(g,c),this.mappingCache.set(`pn:${g}`,c),this.mappingCache.set(`lid:${c}`,g))}}let a={};for(let{pnUser:r,lidUser:s}of o){if(e.get(r)===s){this.logger.debug({pnUser:r,lidUser:s},"LID mapping already exists, skipping");continue}a[r]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[r,s]of Object.entries(a))A[r]=s,A[`${s}_reverse`]=r;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[r,s]of Object.entries(a))this.mappingCache.set(`pn:${r}`,s),this.mappingCache.set(`lid:${s}`,r)}async getLIDForPN(t){return(await this.getLIDsForPNs([t]))?.[0]?.lid||null}async getLIDsForPNs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightLIDLookups.get(i);if(e)return this.logger.trace(`Coalescing getLIDsForPNs request for ${o.length} PNs`),e;let a=this._getLIDsForPNsImpl(t);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(t){let o={},i={},e=[],a=(A,r,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=r.device!==void 0?r.device:0,I=`${g}${c?`:${c}`:""}@${r.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${I} (user mapping with device ${c})`),i[A]={lid:I,pn:A},!0};for(let A of t){if(!Tt(A)&&!wr(A))continue;let r=fA(A);if(!r)continue;let s=r.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,r,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:r})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],r=await this.keys.get("lid-mapping",A);for(let s of A){let g=r[s];g&&typeof g=="string"&&(this.mappingCache.set(`pn:${s}`,g),this.mappingCache.set(`lid:${g}`,s))}for(let{pn:s,pnUser:g,decoded:c}of e){let I=this.mappingCache.get(`pn:${g}`);if(I&&typeof I=="string"){if(!a(s,c,I)){this.logger.warn(`Invalid entry for ${s} (pair not resolved)`);continue}}else{this.logger.trace(`No LID mapping found for PN user ${g}; batch getting from USync`);let d=c.device||0,B=CA(s);wr(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(d):o[B]=[d]}}}if(Object.keys(o).length>0){let A=await this.pnToLIDFunc?.(Object.keys(o));if(A&&A.length>0){await this.storeLIDPNMappings(A);for(let r of A){let g=fA(r.pn)?.user;if(!g)continue;let c=fA(r.lid)?.user;if(c)for(let I of o[r.pn]){let d=`${c}${I?`:${I}`:""}@${I===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${r.pn} \u2192 ${d} (user mapping with device ${I})`);let B=`${g}${I?`:${I}`:""}@${I===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:d,pn:B}}}}else this.logger.warn("USync fetch yielded no results for pending PNs")}return Object.values(i).length>0?Object.values(i):null}async getPNForLID(t){return(await this.getPNsForLIDs([t]))?.[0]?.pn||null}async getPNsForLIDs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightPNLookups.get(i);if(e)return this.logger.trace(`Coalescing getPNsForLIDs request for ${o.length} LIDs`),e;let a=this._getPNsForLIDsImpl(t);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(t){let o={},i=[],e=(a,A,r)=>{if(!r||typeof r!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${r}:${s}@${A.domainType===zt.HOSTED_LID?"hosted":"s.whatsapp.net"}`;return this.logger.trace(`Found reverse mapping: ${a} \u2192 ${g}`),o[a]={lid:a,pn:g},!0};for(let a of t){if(!qA(a))continue;let A=fA(a);if(!A)continue;let r=A.user,s=this.mappingCache.get(`lid:${r}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:r,decoded:A})}if(i.length){let a=[...new Set(i.map(r=>`${r.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:r,lidUser:s,decoded:g}of i){let c=this.mappingCache.get(`lid:${s}`);(!c||typeof c!="string")&&(c=A[`${s}_reverse`],c&&typeof c=="string"&&(this.mappingCache.set(`lid:${s}`,c),this.mappingCache.set(`pn:${c}`,s))),c&&typeof c=="string"?e(r,g,c):this.logger.trace(`No reverse mapping found for LID user: ${s}`)}}return Object.values(o).length?Object.values(o):null}close(){this.mappingCache.clear()}};function NWe(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=dge.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function pge(n,t,o){let i=new iM(n.keys,t,o),e=RWe(n,i),a=n.keys,A=new Kg({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),r=async(g,c)=>{let I=oM(g,c),d=I.toString(),{[d]:B}=await n.keys.get("sender-key",[d]);B||await e.storeSenderKey(I,new nc);let f=await new OE(e).create(I);return{senderName:I,skdm:f}};return{decryptGroupMessage({group:g,authorJid:c,msg:I}){let d=oM(g,c),B=new ME(e,d);return a.transaction(async()=>B.decrypt(I),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let I=new OE(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let d=oM(g.groupId,c),B=new fd(null,null,null,null,g.axolotlSenderKeyDistributionMessage),f=d.toString(),{[f]:Q}=await n.keys.get("sender-key",[f]);return Q||await e.storeSenderKey(d,new nc),a.transaction(async()=>{let{[f]:y}=await n.keys.get("sender-key",[f]);y||await e.storeSenderKey(d,new nc),await I.process(d,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:I}){let d=Zn(g),B=new ag.SessionCipher(e,d);if(c==="pkmsg"){let Q=NWe(I);if(Q){let y=d.toString();await e.saveIdentity(y,Q)&&t.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function f(){let Q;switch(c){case"pkmsg":Q=await B.decryptPreKeyWhisperMessage(I);break;case"msg":Q=await B.decryptWhisperMessage(I);break}return Q}return a.transaction(async()=>await f(),g)},async encryptMessage({jid:g,data:c}){let I=Zn(g),d=new ag.SessionCipher(e,I);return a.transaction(async()=>{let{type:B,body:f}=await d.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(f,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:I}){return a.transaction(async()=>{let{senderName:d,skdm:B}=await r(g,c);return{ciphertext:await new ME(e,d).encrypt(I),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:I}=await r(g,c);return I.serialize()},g)},async hasSenderKey({group:g,meId:c}){let I=oM(g,c).toString(),{[I]:d}=await n.keys.get("sender-key",[I]);return!!d},async getSessionInfo(g){let c=Zn(g).toString(),I=await e.loadSession(c);if(!I)return null;let d=I.getOpenSession?.(),B=d?.indexInfo?.baseKey,f=d?.registrationId;return!B||typeof f!="number"?null:{baseKey:new Uint8Array(B),registrationId:f}},async injectE2ESession({jid:g,session:c}){t.trace({jid:g},"injecting E2EE session");let I=new ag.SessionBuilder(e,Zn(g));return a.transaction(async()=>{await I.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return Zn(g).toString()},lidMapping:i,async validateSession(g){try{let c=Zn(g),I=await e.loadSession(c.toString());return I?I.haveOpenSession()?{exists:!0}:{exists:!1,reason:"no open session"}:{exists:!1,reason:"no session"}}catch{return{exists:!1,reason:"validation error"}}},async deleteSession(g){if(!g.length)return;let c={};return g.forEach(I=>{let d=Zn(I);c[d.toString()]=null}),a.transaction(async()=>{await n.keys.set({session:c})},`delete-${g.length}-sessions`)},close(){A.clear(),i.close()},async migrateSession(g,c){if(!g||!qA(c)&&!Ea(c))return{migrated:0,skipped:0,total:0};if(!Tt(g)&&!wr(g))return{migrated:0,skipped:0,total:1};let{user:I}=fA(g);t.debug({fromJid:g},"bulk device migration - loading all user devices");let{[I]:d}=await a.get("device-list",[I]);if(!d)return{migrated:0,skipped:0,total:0};let{device:B}=fA(g),f=B?.toString()||"0";d.includes(f)||d.push(f);let y=d.filter(_=>{let R=`${I}.${_}`;return!A.has(R)}).map(_=>`${I}.${_}`),m=await a.get("session",y),T=[];for(let[_,R]of Object.entries(m))if(R){let H=_.split(".")[1];if(!H)continue;let F=parseInt(H),L=F===0?`${I}@s.whatsapp.net`:`${I}:${F}@s.whatsapp.net`;F===99&&(L=`${I}:99@hosted`),T.push(L)}return t.debug({fromJid:g,totalDevices:d.length,devicesWithSessions:T.length,devices:T},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let _=T.map(K=>{let G=I$(K,c),V=fA(K),U=fA(G);return{fromJid:K,toJid:G,pnUser:V.user,lidUser:U.user,deviceId:V.device||0,fromAddr:Zn(K),toAddr:Zn(G)}}),R=_.length,H=0,F=Array.from(new Set(_.map(K=>K.fromAddr.toString()))),L=await a.get("session",F),q={};for(let K of _){let G=K.fromAddr.toString(),V=K.toAddr.toString(),U=L[G];if(U){let N=ag.SessionRecord.deserialize(U);N.haveOpenSession()&&(q[V]=N.serialize(),q[G]=null,H++)}}if(Object.keys(q).length>0){await a.set({session:q}),t.debug({migratedSessions:H},"bulk session migration complete");for(let K of _)if(q[K.toAddr.toString()]){let G=`${K.pnUser}.${K.deviceId}`;A.set(G,!0)}}let z=R-H;return{migrated:H,skipped:z,total:R}},`migrate-${T.length}-sessions-${fA(c)?.user}`)}}}var Zn=n=>{let t=fA(n),{user:o,device:i,server:e,domainType:a}=t;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==zt.WHATSAPP?`${o}_${a}`:o,r=i||0;if(i===99&&t.server!=="hosted"&&t.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new ag.ProtocolAddress(A,r)},oM=(n,t)=>new Xf(n,Zn(t));function RWe({creds:n,keys:t},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[r,s]=a.split("_"),g=parseInt(s||"0");if(g===zt.LID||g===zt.HOSTED_LID)return e;let c=`${r}${A!=="0"?`:${A}`:""}@${g===zt.HOSTED?"hosted":"s.whatsapp.net"}`,I=await o.getLIDForPN(c);if(I)return Zn(I).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await t.get("session",[a]);if(A)return ag.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await t.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await t.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:r}=await t.get("identity-key",[A]),s=r?.length===a.length&&r.every((g,c)=>g===a[c]);return r&&!s?(await t.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):r?!1:(await t.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>t.set({"pre-key":{[e]:null}}),loadSignedPreKey:()=>{let e=n.signedPreKey;return{privKey:Buffer.from(e.keyPair.private),pubKey:Buffer.from(e.keyPair.public)}},loadSenderKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("sender-key",[a]);return A?nc.deserialize(A):new nc},storeSenderKey:async(e,a)=>{let A=e.toString(),r=JSON.stringify(a.serialize());await t.set({"sender-key":{[A]:Buffer.from(r,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from($o(e.public))}}}}var EIe=ze(hIe(),1),aQ=(0,EIe.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var sXe=[2,3e3,1043857760];var Hf="https://web.whatsapp.com",$ne="https://call.whatsapp.com/video/",ese="https://call.whatsapp.com/voice/",kE="CB:",uIe="TAG:";var dse=Buffer.from([6,0]),pse=Buffer.from([6,1]),eH=Buffer.from([6,5]),lFA=Buffer.from([6,6]),Yf=10080*60,CIe=1440*60,BIe=336*60*60,Bse="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",gXe=3,Jg=Buffer.from([5]),fIe=Buffer.from([87,65,6,gXe]),Ase=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,tH={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},iQ=[ne.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,ne.HistorySync.HistorySyncType.PUSH_NAME,ne.HistorySync.HistorySyncType.RECENT,ne.HistorySync.HistorySyncType.FULL,ne.HistorySync.HistorySyncType.ON_DEMAND,ne.HistorySync.HistorySyncType.NON_BLOCKING_DATA,ne.HistorySync.HistorySyncType.INITIAL_STATUS_V3],MI={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},QIe={version:sXe,browser:AM.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:aQ.child({class:"baileys"}),emitOwnEvents:!0,defaultQueryTimeoutMs:6e4,customUploadHosts:[],retryRequestDelayMs:250,maxMsgRetryCount:5,fireInitQueries:!0,auth:void 0,markOnlineOnConnect:!0,syncFullHistory:!0,patchMessageBeforeSending:n=>n,shouldSyncHistoryMessage:({syncType:n})=>n!==ne.HistorySync.HistorySyncType.FULL,shouldIgnoreJid:()=>!1,linkPreviewImageThumbnailWidth:192,transactionOpts:{maxCommitRetries:10,delayBetweenTriesMs:3e3},generateHighQualityLinkPreview:!1,enableAutoSessionRecreation:!0,enableRecentMessageCache:!0,options:{},appStateMacVerification:{patch:!1,snapshot:!1},countryCode:"US",getMessage:async()=>{},cachedGroupMetadata:async()=>{},makeSignalRepository:pge},YU={image:"/mms/image",video:"/mms/video",document:"/mms/document",audio:"/mms/audio",sticker:"/mms/image","thumbnail-link":"/mms/image","product-catalog-image":"/product/image","md-app-state":"","md-msg-hist":"/mms/md-app-state","biz-cover-photo":"/pps/biz-cover-photo"},Kne={audio:"Audio",document:"Document",gif:"Video",image:"Image",ppic:"",product:"Image",ptt:"Audio",sticker:"Image",video:"Video","thumbnail-document":"Document Thumbnail","thumbnail-image":"Image Thumbnail","thumbnail-video":"Video Thumbnail","thumbnail-link":"Link Thumbnail","md-msg-hist":"History","md-app-state":"App State","product-catalog-image":"","payment-bg-image":"Payment Background",ptv:"Video","biz-cover-photo":"Image"},tse=Object.keys(YU),yIe=12e4,oQ=5,mIe=812,SIe=3e4,yK={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var wIe=ze(jr(),1);import{createHash as cXe}from"crypto";import{createWriteStream as IXe,promises as lXe}from"fs";import{tmpdir as dXe}from"os";import{join as pXe}from"path";var DIe=n=>{let t=le(n,"product_catalog"),o=PA(t,"product").map(nQ),i=le(t,"paging");return{products:o,nextPageCursor:i?jA(i,"after"):void 0}},OIe=n=>{let t=le(n,"collections");return{collections:PA(t,"collection").map(i=>{let e=jA(i,"id"),a=jA(i,"name"),A=PA(i,"product").map(nQ);return{id:e,name:a,products:A,status:uXe(i)}})}},bIe=n=>{let t=le(n,"order"),o=PA(t,"product").map(a=>{let A=le(a,"image");return{id:jA(a,"id"),name:jA(a,"name"),imageUrl:jA(A,"url"),price:+jA(a,"price"),currency:jA(a,"currency"),quantity:+jA(a,"quantity")}}),i=le(t,"price");return{price:{total:+jA(i,"total"),currency:jA(i,"currency")},products:o}},mK=(n,t)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof t.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(t.name)}),typeof t.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(t.description)}),typeof t.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(t.retailerId)}),t.images.length&&i.push({tag:"media",attrs:{},content:t.images.map(a=>{if(!("url"in a))throw new wIe.Boom("Expected img for product to already be uploaded",{statusCode:400});return{tag:"image",attrs:{},content:[{tag:"url",attrs:{},content:Buffer.from(a.url.toString())}]}})}),typeof t.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(t.price.toString())}),typeof t.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(t.currency)}),"originCountryCode"in t&&(typeof t.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(t.originCountryCode)}]})),typeof t.isHidden<"u"&&(o.is_hidden=t.isHidden.toString()),{tag:"product",attrs:o,content:i}},nQ=n=>{let t=n.attrs.is_hidden==="true",o=jA(n,"id"),i=le(n,"media"),e=le(n,"status_info");return{id:o,imageUrls:EXe(i),reviewStatus:{whatsapp:jA(e,"status")},availability:"in stock",name:jA(n,"name"),retailerId:jA(n,"retailer_id"),url:jA(n,"url"),description:jA(n,"description"),price:+jA(n,"price"),currency:jA(n,"currency"),isHidden:t}};async function SK(n,t,o=3e4){return n={...n,images:n.images?await hXe(n.images,t,o):n.images},n}var hXe=async(n,t,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let I=e.url.toString();if(I.includes(".whatsapp.net"))return{url:I}}let{stream:a}=await Lf(e),A=cXe("sha256"),r=pXe(dXe(),"img"+zr()),s=IXe(r);for await(let I of a)A.update(I),s.write(I);let g=A.digest("base64"),{directPath:c}=await t(r,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await lXe.unlink(r).catch(I=>console.log("Error deleting temp file ",I)),{url:Uf(c)}})),EXe=n=>{let t=le(n,"image");return{requested:jA(t,"request_image_url"),original:jA(t,"original_image_url")}},uXe=n=>{let t=le(n,"status_info");return{status:jA(t,"status"),canAppeal:jA(t,"can_appeal")==="true"}};var gQ=ze(jr(),1);import{randomBytes as _K}from"crypto";var pn=null;try{pn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Gt(n,t,o){this.low=n|0,this.high=t|0,this.unsigned=!!o}Gt.prototype.__isLong__;Object.defineProperty(Gt.prototype,"__isLong__",{value:!0});function si(n){return(n&&n.__isLong__)===!0}function MIe(n){var t=Math.clz32(n&-n);return n?31-t:t}Gt.isLong=si;var _Ie={},TIe={};function wd(n,t){var o,i,e;return t?(n>>>=0,(e=0<=n&&n<256)&&(i=TIe[n],i)?i:(o=St(n,0,!0),e&&(TIe[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=_Ie[n],i)?i:(o=St(n,n<0?-1:0,!1),e&&(_Ie[n]=o),o))}Gt.fromInt=wd;function hn(n,t){if(isNaN(n))return t?sc:es;if(t){if(n<0)return sc;if(n>=vIe)return FIe}else{if(n<=-RIe)return Ao;if(n+1>=RIe)return GIe}return n<0?hn(-n,t).neg():St(n%PE|0,n/PE|0,t)}Gt.fromNumber=hn;function St(n,t,o){return new Gt(n,t,o)}Gt.fromBits=St;var bM=Math.pow;function DK(n,t,o){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(o=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?sc:es;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return DK(n.substring(1),t,o).neg();for(var e=hn(bM(o,8)),a=es,A=0;A>>0:this.low};He.toNumber=function(){return this.unsigned?(this.high>>>0)*PE+(this.low>>>0):this.high*PE+(this.low>>>0)};He.toString=function(t){if(t=t||10,t<2||36>>0,c=g.toString(t);if(A=s,A.isZero())return c+r;for(;c.length<6;)c="0"+c;r=""+c+r}};He.getHighBits=function(){return this.high};He.getHighBitsUnsigned=function(){return this.high>>>0};He.getLowBits=function(){return this.low};He.getLowBitsUnsigned=function(){return this.low>>>0};He.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ao)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,o=31;o>0&&(t&1<>21;return t?this.unsigned?!1:t===-1&&!(this.low===0&&this.high===-2097152):!0};He.isZero=function(){return this.high===0&&this.low===0};He.eqz=He.isZero;He.isNegative=function(){return!this.unsigned&&this.high<0};He.isPositive=function(){return this.unsigned||this.high>=0};He.isOdd=function(){return(this.low&1)===1};He.isEven=function(){return(this.low&1)===0};He.equals=function(t){return si(t)||(t=En(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};He.eq=He.equals;He.notEquals=function(t){return!this.eq(t)};He.neq=He.notEquals;He.ne=He.notEquals;He.lessThan=function(t){return this.comp(t)<0};He.lt=He.lessThan;He.lessThanOrEqual=function(t){return this.comp(t)<=0};He.lte=He.lessThanOrEqual;He.le=He.lessThanOrEqual;He.greaterThan=function(t){return this.comp(t)>0};He.gt=He.greaterThan;He.greaterThanOrEqual=function(t){return this.comp(t)>=0};He.gte=He.greaterThanOrEqual;He.ge=He.greaterThanOrEqual;He.compare=function(t){if(si(t)||(t=En(t)),this.eq(t))return 0;var o=this.isNegative(),i=t.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};He.comp=He.compare;He.negate=function(){return!this.unsigned&&this.eq(Ao)?Ao:this.not().add(vE)};He.neg=He.negate;He.add=function(t){si(t)||(t=En(t));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=t.high>>>16,r=t.high&65535,s=t.low>>>16,g=t.low&65535,c=0,I=0,d=0,B=0;return B+=a+g,d+=B>>>16,B&=65535,d+=e+s,I+=d>>>16,d&=65535,I+=i+r,c+=I>>>16,I&=65535,c+=o+A,c&=65535,St(d<<16|B,c<<16|I,this.unsigned)};He.subtract=function(t){return si(t)||(t=En(t)),this.add(t.neg())};He.sub=He.subtract;He.multiply=function(t){if(this.isZero())return this;if(si(t)||(t=En(t)),pn){var o=pn.mul(this.low,this.high,t.low,t.high);return St(o,pn.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?sc:es;if(this.eq(Ao))return t.isOdd()?Ao:es;if(t.eq(Ao))return this.isOdd()?Ao:es;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(kIe)&&t.lt(kIe))return hn(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,r=t.high>>>16,s=t.high&65535,g=t.low>>>16,c=t.low&65535,I=0,d=0,B=0,f=0;return f+=A*c,B+=f>>>16,f&=65535,B+=a*c,d+=B>>>16,B&=65535,B+=A*g,d+=B>>>16,B&=65535,d+=e*c,I+=d>>>16,d&=65535,d+=a*g,I+=d>>>16,d&=65535,d+=A*s,I+=d>>>16,d&=65535,I+=i*c+e*g+a*s+A*r,I&=65535,St(B<<16|f,I<<16|d,this.unsigned)};He.mul=He.multiply;He.divide=function(t){if(si(t)||(t=En(t)),t.isZero())throw Error("division by zero");if(pn){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var o=(this.unsigned?pn.div_u:pn.div_s)(this.low,this.high,t.low,t.high);return St(o,pn.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?sc:es;var i,e,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return sc;if(t.gt(this.shru(1)))return PIe;a=sc}else{if(this.eq(Ao)){if(t.eq(vE)||t.eq(wK))return Ao;if(t.eq(Ao))return vE;var A=this.shr(1);return i=A.div(t).shl(1),i.eq(es)?t.isNegative()?vE:wK:(e=this.sub(t.mul(i)),a=i.add(e.div(t)),a)}else if(t.eq(Ao))return this.unsigned?sc:es;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=es}for(e=this;e.gte(t);){i=Math.max(1,Math.floor(e.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(i)/Math.LN2),s=r<=48?1:bM(2,r-48),g=hn(i),c=g.mul(t);c.isNegative()||c.gt(e);)i-=s,g=hn(i,this.unsigned),c=g.mul(t);g.isZero()&&(g=vE),a=a.add(g),e=e.sub(c)}return a};He.div=He.divide;He.modulo=function(t){if(si(t)||(t=En(t)),pn){var o=(this.unsigned?pn.rem_u:pn.rem_s)(this.low,this.high,t.low,t.high);return St(o,pn.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};He.mod=He.modulo;He.rem=He.modulo;He.not=function(){return St(~this.low,~this.high,this.unsigned)};He.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};He.clz=He.countLeadingZeros;He.countTrailingZeros=function(){return this.low?MIe(this.low):MIe(this.high)+32};He.ctz=He.countTrailingZeros;He.and=function(t){return si(t)||(t=En(t)),St(this.low&t.low,this.high&t.high,this.unsigned)};He.or=function(t){return si(t)||(t=En(t)),St(this.low|t.low,this.high|t.high,this.unsigned)};He.xor=function(t){return si(t)||(t=En(t)),St(this.low^t.low,this.high^t.high,this.unsigned)};He.shiftLeft=function(t){return si(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?St(this.low<>>32-t,this.unsigned):St(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):St(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};He.shr=He.shiftRight;He.shiftRightUnsigned=function(t){return si(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?St(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?St(this.high,0,this.unsigned):St(this.high>>>t-32,0,this.unsigned)};He.shru=He.shiftRightUnsigned;He.shr_u=He.shiftRightUnsigned;He.rotateLeft=function(t){var o;return si(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?St(this.high,this.low,this.unsigned):t<32?(o=32-t,St(this.low<>>o,this.high<>>o,this.unsigned)):(t-=32,o=32-t,St(this.high<>>o,this.low<>>o,this.unsigned))};He.rotl=He.rotateLeft;He.rotateRight=function(t){var o;return si(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?St(this.high,this.low,this.unsigned):t<32?(o=32-t,St(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,o=32-t,St(this.low<>>t,this.high<>>t,this.unsigned))};He.rotr=He.rotateRight;He.toSigned=function(){return this.unsigned?St(this.low,this.high,!1):this};He.toUnsigned=function(){return this.unsigned?this:St(this.low,this.high,!0)};He.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};He.toBytesLE=function(){var t=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};He.toBytesBE=function(){var t=this.high,o=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};Gt.fromBytes=function(t,o,i){return i?Gt.fromBytesLE(t,o):Gt.fromBytesBE(t,o)};Gt.fromBytesLE=function(t,o){return new Gt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,o)};Gt.fromBytesBE=function(t,o){return new Gt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],o)};typeof BigInt=="function"&&(Gt.fromBigInt=function(t,o){var i=Number(BigInt.asIntN(32,t)),e=Number(BigInt.asIntN(32,t>>BigInt(32)));return St(i,e,o)},Gt.fromValue=function(t,o){return typeof t=="bigint"?Gt.fromBigInt(t,o):En(t,o)},He.toBigInt=function(){var t=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new ic;return{mutex(t){return n.runExclusive(t)}}},LIe=()=>{let n=new Map;return{async mutex(t,o){let i=n.get(t);i||(i={mutex:new ic,refCount:0},n.set(t,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(t)===i&&n.delete(t)}}}};function UIe(n,t,o=10){let i=[],e=!1;return{enqueue:(A,r)=>{if(i.push({type:A,node:r}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&t.isWsOpen();){let{type:c,node:I}=i.shift(),d=n.get(c);if(!d){t.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await d(I).catch(B=>t.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await t.yieldToEventLoop())}e=!1})().catch(g=>t.onUnexpectedError(g,"processing offline nodes"))}}}var LM=ze(jr(),1);var NI=ze(jr(),1);var MM=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(t){let o=[],i;if(t.tag==="devices"){Vi(t);let e=le(t,"device-list"),a=le(t,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:r}of e.content){let s=+r.id,g=+r["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(r.is_hosted&&r.is_hosted==="true")})}a?.tag==="key-index-list"&&(i={timestamp:+a.attrs.ts,signedKeyIndex:a?.content,expectedTimestamp:a.attrs.expected_ts?+a.attrs.expected_ts:void 0})}return{deviceList:o,keyIndex:i}}};var ng=class{withId(t){return this.id=t,this}withLid(t){return this.lid=t,this}withPhone(t){return this.phone=t,this}withUsername(t){return this.username=t,this}withUsernameKey(t){return this.usernameKey=t,this}withType(t){return this.type=t,this}withPersonaId(t){return this.personaId=t,this}};var _M=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(t){return t.phone?{tag:"contact",attrs:{},content:t.phone}:t.username?{tag:"contact",attrs:{username:t.username,...t.usernameKey?{pin:t.usernameKey}:{},...t.lid?{lid:t.lid}:{}}}:t.type?{tag:"contact",attrs:{type:t.type}}:{tag:"contact",attrs:{}}}parser(t){return t.tag==="contact"?(Vi(t),t?.attrs?.type==="in"):!1}};var TM=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="status"){Vi(t);let o=t?.content?.toString()??null,i=new Date(+(t?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):t.attrs?.code&&+t.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var NM=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="disappearing_mode"){Vi(t);let o=+t?.attrs.duration,i=new Date(+(t?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var RM=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(t){return null}parser(t){return t.tag==="username"?(Vi(t),typeof t.content=="string"?t.content:null):null}};var kM=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(t){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:t.personaId}}]}}parser(t){let o=le(t,"bot"),i=le(o,"profile"),e=le(i,"commands"),a=le(i,"prompts"),A=[],r=[];for(let s of PA(e,"command"))A.push({name:jA(s,"name"),description:jA(s,"description")});for(let s of PA(a,"prompt"))r.push(`${jA(s,"emoji")} ${jA(s,"text")}`);return{isDefault:!!le(i,"default"),jid:t.attrs.jid,name:jA(i,"name"),attributes:jA(i,"attributes"),description:jA(i,"description"),category:jA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:jA(e,"description"),commands:A,prompts:r}}};var vM=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(t){return t.lid?{tag:"lid",attrs:{jid:t.lid}}:null}parser(t){return t.tag==="lid"?t.attrs.val:null}};var sg=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(t){return this.mode=t,this}withContext(t){return this.context=t,this}withUser(t){return this.users.push(t),this}parseUSyncQueryResult(t){if(t?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=le(t,"usync"),a=e?le(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,r)=>{let s=r?.attrs.jid;if(s){let g=Array.isArray(r?.content)?Object.fromEntries(r.content.map(c=>{let I=c.tag,d=o[I];return d?[I,d(c)]:[I,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new MM),this}withContactProtocol(){return this.protocols.push(new _M),this}withStatusProtocol(){return this.protocols.push(new TM),this}withDisappearingModeProtocol(){return this.protocols.push(new NM),this}withBotProfileProtocol(){return this.protocols.push(new kM),this}withLIDProtocol(){return this.protocols.push(new vM),this}withUsernameProtocol(){return this.protocols.push(new RM),this}};var $r=ze(jr(),1);import{randomBytes as bK}from"crypto";import{URL as QXe}from"url";import{promisify as yXe}from"util";var PM=class{constructor(t={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,t)}};import{EventEmitter as BXe}from"events";var GM=class extends BXe{constructor(t,o){super(),this.url=t,this.config=o,this.setMaxListeners(0)}};var FM=class extends GM{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===Yo.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===Yo.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===Yo.CLOSING}get isConnecting(){return this.socket?.readyState===Yo.CONNECTING}connect(){if(this.socket)return;this.socket=new Yo(this.url,{origin:Hf,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let t=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of t)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let t=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await t,this.socket=null}send(t,o){return this.socket?.send(t,o),!!this.socket}};var OK=ze(jr(),1);var fXe=(n,t,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:OA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:t},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),sQ=async(n,t,o,i,e)=>{let a=await fXe(n,t,i,e),A=le(a,"result");if(A?.content){let s=JSON.parse(A.content.toString());if(s.errors&&s.errors.length>0){let c=s.errors.map(B=>B.message||"Unknown error").join(", "),I=s.errors[0],d=I.extensions?.error_code||400;throw new OK.Boom(`GraphQL server error: ${c}`,{statusCode:d,data:I})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let r=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new OK.Boom(`Failed to ${r}, unexpected response structure.`,{statusCode:400,data:a})};var HIe=n=>{let{waWebSocketUrl:t,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:r,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:I}=n,d=new PM,B=0,f=z$(),Q=()=>`${f}${oe++}`;r&&i.warn({},"\u26A0\uFE0F The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version."),a[1].toLocaleLowerCase().includes("android")&&i.warn("\u26A0\uFE0F Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk."),iQ.map(de=>n.shouldSyncHistoryMessage({syncType:de})).filter(de=>de===!1).length===iQ.length&&i.warn("\u26A0\uFE0F DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS");let m=typeof t=="string"?new QXe(t):t;if(n.mobile||m.protocol==="tcp:")throw new $r.Boom("Mobile API is not supported anymore",{statusCode:tr.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let T=Dr.generateKeyPair(),_=Cse({keyPair:T,NOISE_HEADER:fIe,logger:i,routingInfo:A?.creds?.routingInfo}),R=new FM(m,n);R.connect();let H=yXe(R.send),F=async de=>{if(!R.isOpen)throw new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed});let Qe=_.encodeFrame(de);await Th(o,async(Me,oA)=>{try{await H.call(R,Qe),Me()}catch(dA){oA(dA)}})},L=de=>{i.level==="trace"&&i.trace({xml:xn(de),msg:"xml send"});let Qe=l$(de);return F(Qe)},q=async(de,Qe=s)=>{let Me,oA;try{return await Th(Qe,(FA,Yt)=>(Me=ct=>{FA(ct)},oA=ct=>{Yt(ct||new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed}))},R.on(`TAG:${de}`,Me),R.on("close",oA),R.on("error",oA),()=>Yt(new $r.Boom("Query Cancelled"))))}catch(dA){if(dA instanceof $r.Boom&&dA.output?.statusCode===tr.timedOut){i?.warn?.({msgId:de},"timed out waiting for message");return}throw dA}finally{Me&&R.off(`TAG:${de}`,Me),oA&&(R.off("close",oA),R.off("error",oA))}},z=async(de,Qe)=>{de.attrs.id||(de.attrs.id=Q());let Me=de.attrs.id,oA=await Th(Qe,async(dA,FA)=>{let Yt=q(Me,Qe).catch(FA);L(de).then(async()=>dA(await Yt)).catch(FA)});return oA&&"tag"in oA&&Vi(oA),oA},K=async()=>{let de=await z({tag:"iq",attrs:{to:OA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!le(de,"digest"))throw await Xe(),new Error("encrypt/get digest returned no digest node")},G=async()=>{let de=(J.signedPreKey.keyId||0)+1,Qe=await PD(J.signedIdentityKey,de);await z({tag:"iq",attrs:{to:OA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[jf(Qe)]}]}),k.emit("creds.update",{signedPreKey:Qe})},V=async de=>{if(de.protocols.length===0)throw new $r.Boom("USyncQuery must have at least one protocol");let Me=de.users.map(ct=>({tag:"user",attrs:{jid:ct.phone?void 0:ct.id},content:de.protocols.map(br=>br.getUserElement(ct)).filter(br=>br!==null)})),oA={tag:"list",attrs:{},content:Me},dA={tag:"query",attrs:{},content:de.protocols.map(ct=>ct.getQueryElement())},FA={tag:"iq",attrs:{to:OA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:de.context,mode:de.mode,sid:Q(),last:"true",index:"0"},content:[dA,oA]}]},Yt=await z(FA);return de.parseUSyncQueryResult(Yt)},U=async(...de)=>{let Qe=new sg,Me=!1;for(let dA of de)if(qA(dA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{Me||(Me=!0,Qe=Qe.withContactProtocol());let FA=`+${dA.replace("+","").split("@")[0]?.split(":")[0]}`;Qe.withUser(new ng().withPhone(FA))}if(Qe.users.length===0)return[];let oA=await V(Qe);if(oA)return oA.list.filter(dA=>!!dA.contact).map(({contact:dA,id:FA})=>({jid:FA,exists:dA}))},N=async de=>{let Qe=new sg().withLIDProtocol().withContext("background");for(let oA of de)if(qA(oA)){i?.warn("LID user found in LID fetch call");continue}else Qe.withUser(new ng().withId(oA));if(Qe.users.length===0)return[];let Me=await V(Qe);return Me?Me.list.filter(oA=>!!oA.lid).map(({lid:oA,id:dA})=>({pn:dA,lid:oA})):[]},k=$se(i),{creds:J}=A,X=Yse(A.keys,i,g),ae=I({creds:J,keys:X},i,N),De,oe=1,Se,Be,Re=!1,Ne=[],Je=(de,Qe)=>{i.error({err:de},`unexpected error in '${Qe}'`)},ve=async de=>{if(!R.isOpen)throw new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed});let Qe,Me,oA=Th(o,(dA,FA)=>{Qe=dA,Me=MK(FA),R.on("frame",Qe),R.on("close",Me),R.on("error",Me)}).finally(()=>{R.off("frame",Qe),R.off("close",Me),R.off("error",Me)});return de&&F(de).catch(Me),oA},aA=async()=>{let de={clientHello:{ephemeral:T.public}};de=ne.HandshakeMessage.fromObject(de),i.info({browser:a,helloMsg:de},"connected to WA");let Qe=ne.HandshakeMessage.encode(de).finish(),Me=await ve(Qe),oA=ne.HandshakeMessage.decode(Me);i.trace({handshake:oA},"handshake recv from WA");let dA=_.processHandshake(oA,J.noiseKey),FA;J.me?(FA=cse(J.me.id,n),i.info({node:FA},"logging in...")):(FA=Ise(J,n),i.info({node:FA},"not logged in, attempting registration..."));let Yt=_.encrypt(ne.ClientPayload.encode(FA).finish());await F(ne.HandshakeMessage.encode({clientFinish:{static:dA,payload:Yt}}).finish()),await _.finishInit(),Ze()},fe=async()=>{let de=await z({tag:"iq",attrs:{id:Q(),xmlns:"encrypt",type:"get",to:OA},content:[{tag:"count",attrs:{}}]});return+le(de,"count").attrs.value},Ie=null,Xe=async(de=oQ)=>{if(Ie){i.debug("Pre-key upload already in progress, waiting for completion"),await Ie;return}let Qe=async Me=>{i.info({count:de,retryCount:Me},"uploading pre-keys");let oA=await X.transaction(async()=>{i.debug({requestedCount:de},"generating pre-keys with requested count");let{update:dA,node:FA}=await nse({creds:J,keys:X},de);return k.emit("creds.update",dA),FA},J?.me?.id||"upload-pre-keys");try{await z(oA),i.info({count:de},"uploaded pre-keys successfully")}catch(dA){if(i.error({uploadError:dA.toString(),count:de},"Failed to upload pre-keys to server"),Me<3){let FA=Math.min(1e3*Math.pow(2,Me),1e4);return i.info(`Retrying pre-key upload in ${FA}ms`),await new Promise(Yt=>setTimeout(Yt,FA)),Qe(Me+1)}throw dA}};Ie=Promise.race([Qe(0),new Promise((Me,oA)=>setTimeout(()=>oA(new $r.Boom("Pre-key upload timeout",{statusCode:408})),SIe))]);try{await Ie}finally{Ie=null}},je=async()=>{let de=J.nextPreKeyId-1;return de<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await X.get("pre-key",[de.toString()]))[de.toString()],currentPreKeyId:de}},be=async()=>{try{let de=0,Qe=await fe();Qe===0?de=mIe:de=oQ;let{exists:Me,currentPreKeyId:oA}=await je();i.info(`${Qe} pre-keys found on server`),i.info(`Current prekey ID: ${oA}, exists in storage: ${Me}`);let dA=Qe<=de,FA=!Me&&oA>0;if(dA||FA){let ct=[];dA&&ct.push(`server count low (${Qe})`),FA&&ct.push(`current prekey ${oA} missing from storage`),i.info(`Uploading PreKeys due to: ${ct.join(", ")}`),await Xe(de)}else i.info(`PreKey validation passed - Server: ${Qe}, Current prekey ${oA} exists`)}catch(de){i.error({error:de},"Failed to check/upload pre-keys during initialization")}},EA=async de=>{await _.decodeFrame(de,Qe=>{De=new Date;let Me=!1;if(Me=R.emit("frame",Qe),!(Qe instanceof Uint8Array)){let oA=Qe.attrs.id;i.level==="trace"&&i.trace({xml:xn(Qe),msg:"recv xml"}),Me=R.emit(`${uIe}${oA}`,Qe)||Me;let dA=Qe.tag,FA=Qe.attrs||{},Yt=Array.isArray(Qe.content)?Qe.content[0]?.tag:"";for(let ct of Object.keys(FA))Me=R.emit(`${kE}${dA},${ct}:${FA[ct]},${Yt}`,Qe)||Me,Me=R.emit(`${kE}${dA},${ct}:${FA[ct]}`,Qe)||Me,Me=R.emit(`${kE}${dA},${ct}`,Qe)||Me;Me=R.emit(`${kE}${dA},,${Yt}`,Qe)||Me,Me=R.emit(`${kE}${dA}`,Qe)||Me,!Me&&i.level==="debug"&&i.debug({unhandled:!0,msgId:oA,fromMe:!1,frame:Qe},"communication recv")}})},hA=async de=>{if(Re){i.trace({trace:de?.stack},"connection already closed");return}if(Re=!0,i.info({trace:de?.stack},de?"connection errored":"connection closed"),clearInterval(Se),clearTimeout(Be),R.removeAllListeners("close"),R.removeAllListeners("open"),R.removeAllListeners("message"),ae.close?.(),!R.isClosed&&!R.isClosing)try{await R.close()}catch{}for(let Qe of Ne)try{await Qe(de)}catch(Me){i.error({err:Me},"error in socket end handler")}k.emit("connection.update",{connection:"close",lastDisconnect:{error:de,date:new Date}}),k.removeAllListeners("connection.update"),k.destroy()},iA=async()=>{if(R.isOpen)return;if(R.isClosed||R.isClosing)throw new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed});let de,Qe;await new Promise((Me,oA)=>{de=()=>Me(void 0),Qe=MK(oA),R.on("open",de),R.on("close",Qe),R.on("error",Qe)}).finally(()=>{R.off("open",de),R.off("close",Qe),R.off("error",Qe)})},Ze=()=>Se=setInterval(()=>{De||(De=new Date),Date.now()-De.getTime()>e+5e3?hA(new $r.Boom("Connection was lost",{statusCode:tr.connectionLost})):R.isOpen?z({tag:"iq",attrs:{id:Q(),to:OA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(Qe=>{i.error({trace:Qe.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),bA=de=>z({tag:"iq",attrs:{to:OA,xmlns:"passive",type:"set"},content:[{tag:de,attrs:{}}]}),Ce=async de=>{let Qe=A.creds.me?.id;Qe&&await L({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:Qe,reason:"user_initiated"}}]}),hA(new $r.Boom(de||"Intentional Logout",{statusCode:tr.loggedOut}))},ke=async(de,Qe)=>{let Me=Qe??$$(bK(5));if(Qe&&Qe?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=Me,A.creds.me={id:Sr(de,"s.whatsapp.net"),name:"~"},k.emit("creds.update",A.creds),await L({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:A.creds.me.id,stage:"companion_hello",should_show_push_notification:"true"},content:[{tag:"link_code_pairing_wrapped_companion_ephemeral_pub",attrs:{},content:await Ue()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:MH(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function Ue(){let de=bK(32),Qe=bK(16),Me=await GD(A.creds.pairingCode,de),oA=P$(A.creds.pairingEphemeralKeyPair.public,Me,Qe);return Buffer.concat([de,Qe,oA])}let MA=de=>z({tag:"iq",attrs:{to:OA,id:Q(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:de}]});R.on("message",EA),R.on("open",async()=>{try{await aA()}catch(de){i.error({err:de},"error in validating connection"),hA(de)}}),R.on("error",MK(hA)),R.on("close",()=>void hA(new $r.Boom("Connection Terminated",{statusCode:tr.connectionClosed}))),R.on("CB:xmlstreamend",()=>void hA(new $r.Boom("Connection Terminated by Server",{statusCode:tr.connectionClosed}))),R.on("CB:iq,type:set,pair-device",async de=>{let Qe={tag:"iq",attrs:{to:OA,type:"result",id:de.attrs.id}};await L(Qe);let Me=le(de,"pair-device"),oA=PA(Me,"ref"),dA=Buffer.from(J.noiseKey.public).toString("base64"),FA=Buffer.from(J.signedIdentityKey.public).toString("base64"),Yt=J.advSecretKey,ct=c||6e4,br=()=>{if(!R.isOpen)return;let or=oA.shift();if(!or){hA(new $r.Boom("QR refs attempts ended",{statusCode:tr.timedOut}));return}let mo=or.content.toString("utf-8"),to=tge(mo,dA,FA,Yt,a);k.emit("connection.update",{qr:to}),Be=setTimeout(br,ct),ct=c||2e4};br()}),R.on("CB:iq,,pair-success",async de=>{i.debug("pair success recv");try{_A(de);let{reply:Qe,creds:Me}=lse(de,J);i.info({me:Me.me,platform:Me.platform},"pairing configured successfully, expect to restart the connection..."),k.emit("creds.update",Me),k.emit("connection.update",{isNewLogin:!0,qr:void 0}),await L(Qe),wA()}catch(Qe){i.info({trace:Qe.stack},"error in pairing"),hA(Qe)}}),R.on("CB:success",async de=>{try{_A(de),await be(),await bA("active");try{await K()}catch(Qe){i.warn({e:Qe},"failed to run digest after login")}}catch(Qe){i.warn({err:Qe},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(Be),k.emit("creds.update",{me:{...A.creds.me,lid:de.attrs.lid}}),k.emit("connection.update",{connection:"open"}),wA(),de.attrs.lid&&A.creds.me?.id){let Qe=de.attrs.lid;process.nextTick(async()=>{try{let Me=A.creds.me.id;await ae.lidMapping.storeLIDPNMappings([{lid:Qe,pn:Me}]);let{user:oA,device:dA}=fA(Me);await A.keys.set({"device-list":{[oA]:[dA?.toString()||"0"]}}),await ae.migrateSession(Me,Qe),i.info({myPN:Me,myLID:Qe},"Own LID session created successfully")}catch(Me){i.error({error:Me,lid:Qe},"Failed to create own LID session")}})}}),R.on("CB:stream:error",de=>{let[Qe]=vs(de);i.error({reasonNode:Qe,fullErrorNode:de},"stream errored out");let{reason:Me,statusCode:oA}=W$(de);hA(new $r.Boom(`Stream Errored (${Me})`,{statusCode:oA,data:Qe||de}))}),R.on("CB:failure",de=>{let Qe=+(de.attrs.reason||500);hA(new $r.Boom("Connection Failure",{statusCode:Qe,data:de.attrs}))}),R.on("CB:ib,,downgrade_webclient",()=>{hA(new $r.Boom("Multi-device beta not joined",{statusCode:tr.multideviceMismatch}))}),R.on("CB:ib,,offline_preview",async de=>{i.info("offline preview received",JSON.stringify(de)),await L({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),R.on("CB:ib,,edge_routing",de=>{let Qe=le(de,"edge_routing"),Me=le(Qe,"routing_info");Me?.content&&(A.creds.routingInfo=Buffer.from(Me?.content),k.emit("creds.update",A.creds))});let Ke=!1;process.nextTick(()=>{J.me?.id&&(k.buffer(),Ke=!0),k.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),R.on("CB:ib,,offline",de=>{let Me=+(le(de,"offline")?.attrs.count||0);i.info(`handled ${Me} offline messages/notifications`),Ke&&(k.flush(),i.trace("flushed events for initial buffer")),k.emit("connection.update",{receivedPendingNotifications:!0})}),k.on("creds.update",de=>{let Qe=de.me?.name;J.me?.name!==Qe&&(i.debug({name:Qe},"updated pushName"),L({tag:"presence",attrs:{name:Qe}}).catch(Me=>{i.warn({trace:Me.stack},"error in sending presence update on name change")})),Object.assign(J,de)});let _A=({attrs:de})=>{let Qe=de?.t;if(!Qe)return;let Me=Number(Qe);if(Number.isNaN(Me)||Me<=0)return;let oA=Date.now();B=Me*1e3-oA,i.debug({offset:B},"calculated server time offset")},ot=()=>{let de=3*yK.Day;return((Date.now()+B+de)%yK.Week).toString()},wA=async()=>{if(!R.isOpen)return;let de={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:ot()}}]};try{await L(de)}catch(Qe){i.debug({error:Qe},"failed to send unified_session telemetry")}},ht=de=>{Ne.push(de)},Br=async()=>{let de=await sQ({},ha.REACHOUT_TIMELOCK,Ra.xwa2_fetch_account_reachout_timelock,z,Q),Qe={isActive:!!de?.is_active,timeEnforcementEnds:de?.time_enforcement_ends&&de?.time_enforcement_ends!=="0"?new Date(parseInt(de.time_enforcement_ends,10)*1e3):void 0,enforcementType:de?.enforcement_type??AI.DEFAULT};return k.emit("connection.update",{reachoutTimeLock:Qe}),Qe},UA=async()=>sQ({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},ha.MESSAGE_CAPPING_INFO,Ra.xwa2_message_capping_info,z,Q);return{type:"md",ws:R,ev:k,authState:{creds:J,keys:X},signalRepository:ae,get user(){return A.creds.me},generateMessageTag:Q,query:z,waitForMessage:q,waitForSocketOpen:iA,sendRawMessage:F,sendNode:L,logout:Ce,end:hA,registerSocketEndHandler:ht,onUnexpectedError:Je,uploadPreKeys:Xe,uploadPreKeysToServerIfRequired:be,digestKeyBundle:K,rotateSignedPreKey:G,requestPairingCode:ke,updateServerTimeOffset:_A,sendUnifiedSession:wA,wamBuffer:d,waitForConnectionUpdate:q$(k),sendWAMBuffer:MA,executeUSyncQuery:V,onWhatsApp:U,fetchAccountReachoutTimelock:Br,fetchNewChatMessageCap:UA}};function MK(n){return t=>{n(new $r.Boom(`WebSocket Error (${t?.message})`,{statusCode:X$(t),data:t}))}}var mXe=(n,t)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return t?.length&&(o.content=t),[o]},KIe=n=>{let{logger:t,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:r}=n,s=HIe(n),{ev:g,ws:c,authState:I,generateMessageTag:d,sendNode:B,query:f,signalRepository:Q,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:T}=s,_=Q.lidMapping.getLIDForPN.bind(Q.lidMapping),R,H={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},F=pa.Connecting,L=gc(),q=gc(),z=gc(),K=gc(),G,V={initialBootstrapComplete:!1,recentSyncComplete:!1},U,N=new Set,k=n.placeholderResendCache||new ac({stdTTL:MI.MSG_RETRY,useClones:!1}),J=async W=>{let{[W]:$}=await I.keys.get("app-state-sync-key",[W]);return $},X=async(W=!1)=>{if(!R||W){let{content:$}=await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"get"},content:[{tag:"privacy",attrs:{}}]});R=QL($?.[0],"category")}return R},ae=async(W,$)=>{await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:W,value:$}}]}]})},De=async W=>{await ae("messages",W)},oe=async W=>{await ae("calladd",W)},Se=async W=>{await ae("last",W)},Be=async W=>{await ae("online",W)},Re=async W=>{await ae("profile",W)},Ne=async W=>{await ae("status",W)},Je=async W=>{await ae("readreceipts",W)},ve=async W=>{await ae("groupadd",W)},aA=async W=>{await f({tag:"iq",attrs:{xmlns:"disappearing_mode",to:OA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:W.toString()}}]})},fe=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"bot",to:OA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),$=le(W,"bot"),re=[];for(let se of PA($,"section"))if(se.attrs.type==="all")for(let we of PA(se,"bot"))re.push({jid:we.attrs.jid,personaId:we.attrs.persona_id});return re},Ie=async(...W)=>{let $=new sg().withStatusProtocol();for(let se of W)$.withUser(new ng().withId(se));let re=await s.executeUSyncQuery($);if(re)return re.list},Xe=async(...W)=>{let $=new sg().withDisappearingModeProtocol();for(let se of W)$.withUser(new ng().withId(se));let re=await s.executeUSyncQuery($);if(re)return re.list},je=async(W,$,re)=>{let se;if(!W)throw new NI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");CA(W)!==CA(I.creds.me.id)?se=CA(W):se=void 0;let{img:we}=await Ub($,re);await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...se?{target:se}:{}},content:[{tag:"picture",attrs:{type:"image"},content:we}]})},be=async W=>{let $;if(!W)throw new NI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");CA(W)!==CA(I.creds.me.id)?$=CA(W):$=void 0,await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...$?{target:$}:{}}})},EA=async W=>{await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(W,"utf-8")}]})},hA=async W=>{await UA({pushNameSetting:W},"")},iA=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"get"}}),$=le(W,"list");return PA($,"item").map(re=>re.attrs.jid)},Ze=async(W,$)=>{let re=CA(W),se,we;if(qA(re)||Ea(re)){if(se=re,$==="block"){let he=await Q.lidMapping.getPNForLID(re);if(!he)throw new NI.Boom(`Unable to resolve PN JID for LID: ${W}`,{statusCode:400});we=CA(he)}}else if(Tt(re)||wr(re)){let he=await Q.lidMapping.getLIDForPN(re);if(!he)throw new NI.Boom(`Unable to resolve LID for PN JID: ${W}`,{statusCode:400});se=he,$==="block"&&(we=CA(re))}else throw new NI.Boom(`Invalid jid: ${W}`,{statusCode:400});let Ee={action:$,jid:se};if($==="block"){if(!we)throw new NI.Boom(`pn_jid required for block: ${W}`,{statusCode:400});Ee.pn_jid=we}await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"set"},content:[{tag:"item",attrs:Ee}]})},bA=async W=>{let $=await f({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:W}}]}]}),re=le($,"business_profile"),se=le(re,"profile");if(se){let we=le(se,"address"),Ee=le(se,"description"),he=le(se,"website"),ye=le(se,"email"),qe=le(le(se,"categories"),"category"),IA=le(se,"business_hours"),yA=IA?PA(IA,"business_hours_config"):void 0,$A=he?.content?.toString();return{wid:se.attrs?.jid,address:we?.content?.toString(),description:Ee?.content?.toString()||"",website:$A?[$A]:[],email:ye?.content?.toString(),category:qe?.content?.toString(),business_hours:{timezone:IA?.attrs?.timezone,business_config:yA?.map(({attrs:vA})=>vA)}}}},Ce=async(W,$)=>{t.info({fromTimestamp:$},"clean dirty bits "+W),await B({tag:"iq",attrs:{to:OA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:d()},content:[{tag:"clean",attrs:{type:W,...$?{timestamp:$.toString()}:null}}]})},ke=W=>({onMutation($){vse($,g,I.creds.me,W?{accountSettings:I.creds.accountSettings}:void 0,t)}}),Ue=g.createBufferedFunction(async(W,$)=>{let re=new Map,se=async ye=>{if(re.has(ye))return re.get(ye)??void 0;let qe=await J(ye);return re.set(ye,qe??null),qe},we={},Ee={};await I.keys.transaction(async()=>{let ye=new Set(W),qe={},IA=new Set;for(;ye.size;){let yA={},$A=[];for(let At of ye){let tA=(await I.keys.get("app-state-sync-version",[At]))[At];tA?(tA=aH(tA),typeof we[At]>"u"&&(we[At]=tA.version)):tA=Jb(),yA[At]=tA;let tt=IA.has(At);tt&&IA.delete(At),t.info(`resyncing ${At} from v${tA.version}${tt?" (forcing snapshot)":""}`),$A.push({tag:"collection",attrs:{name:At,version:tA.version.toString(),return_snapshot:(tt||!tA.version).toString()}})}let vA=await f({tag:"iq",attrs:{to:OA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:$A}]}),YA=await Tse(vA,n?.options);for(let At in YA){let Ge=At,{patches:tA,hasMorePatches:tt,snapshot:ea}=YA[Ge];try{if(ea){let{state:nr,mutationMap:So}=await Rse(Ge,ea,se,we[Ge],e.snapshot,t);yA[Ge]=nr,Object.assign(Ee,So),t.info(`restored state of ${Ge} from snapshot to v${nr.version} with mutations`),await I.keys.set({"app-state-sync-version":{[Ge]:nr}})}if(tA.length){let{state:nr,mutationMap:So}=await oH(Ge,tA,yA[Ge],se,n.options,we[Ge],t,e.patch);await I.keys.set({"app-state-sync-version":{[Ge]:nr}}),t.info(`synced ${Ge} to v${nr.version}`),we[Ge]=nr.version,Object.assign(Ee,So)}tt?t.info(`${Ge} has more patches...`):ye.delete(Ge)}catch(nr){qe[Ge]=(qe[Ge]||0)+1;let So={name:Ge,attempt:qe[Ge],version:yA[Ge].version,statusCode:nr.output?.statusCode,errorType:nr.name,error:nr.stack};zf(nr)&&qe[Ge]>=iH?(t.warn(So,`${Ge} blocked on missing key from v${yA[Ge].version}, parking after ${qe[Ge]} attempts`),N.add(Ge),ye.delete(Ge)):zf(nr)?(t.info(So,`${Ge} blocked on missing key from v${yA[Ge].version}, retrying with snapshot`),IA.add(Ge)):bse(nr,qe[Ge])?(t.warn(So,`failed to sync ${Ge} from v${yA[Ge].version}, giving up`),ye.delete(Ge)):(t.info(So,`failed to sync ${Ge} from v${yA[Ge].version}, forcing snapshot retry`),IA.add(Ge))}}}},I?.creds?.me?.id||"resync-app-state");let{onMutation:he}=ke($);for(let ye in Ee)he(Ee[ye])}),MA=async(W,$="preview",re)=>{let se=CA(W),we=Tt(se)||qA(se),Ee=I.creds.me,he=Ee&&(se===CA(Ee.id)||Ee.lid&&se===CA(Ee.lid)),ye;H.profilePicPrivacyToken&&we&&!he&&(ye=await mH({authState:I,jid:se,getLIDForPN:_})),W=CA(W);let qe=await f({tag:"iq",attrs:{target:W,to:OA,type:"get",xmlns:"w:profile:picture"},content:mXe($,ye)},re);return le(qe,"picture")?.attrs?.url},Ke=async(W,$,re)=>{let se=await f({tag:"call",attrs:{id:d(),to:"@call"},content:[{tag:"link_create",attrs:{media:W},content:$?[{tag:"event",attrs:{start_time:String($.startTime)}}]:void 0}]},re);return le(se,"link_create")?.attrs?.token},_A=async(W,$)=>{let re=I.creds.me,se=W==="available";if(se||W==="unavailable"){if(!re.name){t.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:se}),se&&m(),await B({tag:"presence",attrs:{name:re.name.replace(/@/g,""),type:W}})}else{let{server:we}=fA($);await B({tag:"chatstate",attrs:{from:we==="lid"?re.lid:re.id,to:$},content:[{tag:W==="recording"?"composing":W,attrs:W==="recording"?{media:"audio"}:{}}]})}},ot=async W=>{let $=CA(W),se=Tt($)||qA($)?await mH({authState:I,jid:$,getLIDForPN:_}):void 0;return B({tag:"presence",attrs:{to:W,id:d(),type:"subscribe"},content:se})},wA=({tag:W,attrs:$,content:re})=>{let se,we=$.from,Ee=$.participant||$.from;if(!(a(we)&&we!==OA)){if(W==="presence")se={lastKnownPresence:$.type==="unavailable"?"unavailable":"available",lastSeen:$.last&&$.last!=="deny"?+$.last:void 0,groupOnlineCount:$.count?+$.count:void 0};else if(Array.isArray(re)){let[he]=re,ye=he.tag;ye==="paused"&&(ye="available"),he.attrs?.media==="audio"&&(ye="recording"),se={lastKnownPresence:ye}}else t.error({tag:W,attrs:$,content:re},"recv invalid presence node");se&&g.emit("presence.update",{id:we,presences:{[Ee]:se}})}},ht=async W=>{let $=W.type,re=I.creds.myAppStateKeyId;if(!re)throw new NI.Boom("App state key not present!",{statusCode:400});let se,we;if(await z.mutex(async()=>{await I.keys.transaction(async()=>{t.debug({patch:W},"applying app patch"),await Ue([$],!1);let{[$]:Ee}=await I.keys.get("app-state-sync-version",[$]);se=Ee?aH(Ee):Jb(),we=await Mse(W,re,se,J);let{patch:he,state:ye}=we,qe={tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:$,version:(ye.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:ne.SyncdPatch.encode(he).finish()}]}]}]};await f(qe),await I.keys.set({"app-state-sync-version":{[$]:ye}})},I?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:Ee}=ke(!1),{mutationMap:he}=await oH($,[{...we.patch,version:{version:we.state.version}}],se,J,n.options,void 0,t);for(let ye in he)Ee(he[ye])}},Br=async()=>{let W=await f({tag:"iq",attrs:{to:OA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...I?.creds?.lastPropHash?{hash:I.creds.lastPropHash}:{}}}]}),$=le(W,"props"),re={};$&&($.attrs?.hash&&(I.creds.lastPropHash=$?.attrs?.hash,g.emit("creds.update",I.creds)),re=QL($,"prop"));let se=re[10518]??re.privacy_token_sending_on_all_1_on_1_messages;se!==void 0&&(H.privacyTokenOn1to1=se==="true"||se==="1");let we=re[9666]??re.profile_scraping_privacy_token_in_photo_iq;we!==void 0&&(H.profilePicPrivacyToken=we==="true"||we==="1");let Ee=re[14303]??re.lid_trusted_token_issue_to_lid;return Ee!==void 0&&(H.lidTrustedTokenIssueToLid=Ee==="true"||Ee==="1"),t.debug({serverProps:H},"fetched props"),re},UA=(W,$)=>{let re=kse(W,$);return ht(re)},de=W=>UA({disableLinkPreviews:{isPreviewsDisabled:W}},""),Qe=(W,$,re)=>UA({star:{messages:$,star:re}},W),Me=(W,$)=>UA({contact:$},W),oA=W=>UA({contact:null},W),dA=(W,$)=>UA({addLabel:{...$}},W),FA=(W,$)=>UA({addChatLabel:{labelId:$}},W),Yt=(W,$)=>UA({removeChatLabel:{labelId:$}},W),ct=(W,$,re)=>UA({addMessageLabel:{messageId:$,labelId:re}},W),br=(W,$,re)=>UA({removeMessageLabel:{messageId:$,labelId:re}},W),or=W=>UA({quickReply:W},""),mo=W=>UA({quickReply:{timestamp:W,deleted:!0}},""),to=async()=>{await Promise.all([Br(),iA(),X()])},Ae=g.createBufferedFunction(async(W,$)=>{if(g.emit("messages.upsert",{messages:[W],type:$}),W.pushName){let Ee=W.key.fromMe?I.creds.me.id:W.key.participant||W.key.remoteJid;Ee=CA(Ee),W.key.fromMe||g.emit("contacts.update",[{id:Ee,notify:W.pushName,verifiedName:W.verifiedBizName}]),W.key.fromMe&&W.pushName&&I.creds.me?.name!==W.pushName&&g.emit("creds.update",{me:{...I.creds.me,name:W.pushName}})}let re=jb(W.message),se=re?A(re)&&iQ.includes(re.syncType):!1;if(re&&se){let Ee=re.syncType;Ee===ne.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!V.initialBootstrapComplete&&(V.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===ne.HistorySync.HistorySyncType.RECENT&&re.progress===100&&!V.recentSyncComplete&&(V.recentSyncComplete=!0,clearTimeout(U),U=void 0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===ne.HistorySync.HistorySyncType.RECENT&&!V.recentSyncComplete&&(clearTimeout(U),U=setTimeout(()=>{V.recentSyncComplete||(V.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:ne.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),U=void 0},yIe))}re&&F===pa.AwaitingInitialSync&&(G&&(clearTimeout(G),G=void 0),se?(F=pa.Syncing,t.info("Transitioned to Syncing state")):(F=pa.Online,t.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let we=async()=>{if(F===pa.Syncing){N.clear(),t.info("Doing app state sync"),await Ue(t$,!0),F=pa.Online,t.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let Ee=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:Ee})}};await Promise.all([(async()=>{se&&await we()})(),Xse(W,{signalRepository:Q,shouldProcessHistoryMsg:se,placeholderResendCache:k,ev:g,creds:I.creds,keyStore:I.keys,logger:t,options:n.options,getMessage:r})]),W.message?.protocolMessage?.appStateSyncKeyShare&&F===pa.Syncing&&(t.info("App state sync key arrived, triggering app state sync"),await we())});return c.on("CB:presence",wA),c.on("CB:chatstate",wA),c.on("CB:ib,,dirty",async W=>{let{attrs:$}=le(W,"dirty");switch($.type){case"account_sync":if($.timestamp){let{lastAccountSyncTimestamp:se}=I.creds;se&&await Ce("account_sync",se),se=+$.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:se})}break;case"groups":break;default:t.info({node:W},"received unknown sync");break}}),g.on("connection.update",({connection:W,receivedPendingNotifications:$})=>{if(W==="close"&&(N.clear(),clearTimeout(U),U=void 0),W==="open"&&(i&&to().catch(se=>y(se,"init queries")),_A(o?"available":"unavailable").catch(se=>y(se,"presence update requests"))),!$||F!==pa.Connecting)return;if(V.initialBootstrapComplete=!1,V.recentSyncComplete=!1,clearTimeout(U),U=void 0,F=pa.AwaitingInitialSync,t.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(ne.Message.HistorySyncNotification.create({syncType:ne.HistorySync.HistorySyncType.RECENT}))){t.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),F=pa.Online,setTimeout(()=>g.flush(),0);return}if(I.creds.accountSyncCounter>0){t.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),F=pa.Online,setTimeout(()=>g.flush(),0);return}t.info("First connection, awaiting history sync notification with a 20s timeout."),G&&clearTimeout(G),G=setTimeout(()=>{if(F===pa.AwaitingInitialSync){t.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),F=pa.Online,g.flush();let se=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:se})}},2e4)}),g.on("creds.update",({myAppStateKeyId:W})=>{if(!W||N.size===0)return;if(F===pa.Syncing){N.clear();return}let $=[...N];N.clear(),t.info({collections:$},"app state sync key arrived, re-syncing blocked collections"),Ue($,!1).catch(re=>y(re,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:W,pn:$})=>{try{await Q.lidMapping.storeLIDPNMappings([{lid:W,pn:$}])}catch(re){t.warn({lid:W,pn:$,error:re},"Failed to store LID-PN mapping")}}),T(()=>{G&&(clearTimeout(G),G=void 0),!n.placeholderResendCache&&k.close&&k.close(),F=pa.Connecting,R=void 0}),{...s,serverProps:H,createCallLink:Ke,getBotListV2:fe,messageMutex:L,receiptMutex:q,appStatePatchMutex:z,notificationMutex:K,fetchPrivacySettings:X,upsertMessage:Ae,appPatch:ht,sendPresenceUpdate:_A,presenceSubscribe:ot,profilePictureUrl:MA,fetchBlocklist:iA,fetchStatus:Ie,fetchDisappearingDuration:Xe,updateProfilePicture:je,removeProfilePicture:be,updateProfileStatus:EA,updateProfileName:hA,updateBlockStatus:Ze,updateDisableLinkPreviewsPrivacy:de,updateCallPrivacy:oe,updateMessagesPrivacy:De,updateLastSeenPrivacy:Se,updateOnlinePrivacy:Be,updateProfilePicturePrivacy:Re,updateStatusPrivacy:Ne,updateReadReceiptsPrivacy:Je,updateGroupsAddPrivacy:ve,updateDefaultDisappearingMode:aA,getBusinessProfile:bA,resyncAppState:Ue,chatModify:UA,cleanDirtyBits:Ce,addOrEditContact:Me,removeContact:oA,placeholderResendCache:k,addLabel:dA,addChatLabel:FA,removeChatLabel:Yt,addMessageLabel:ct,removeMessageLabel:br,star:Qe,addOrEditQuickReply:or,removeQuickReply:mo}};var xIe=n=>{let t=KIe(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(g,c,I)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:I}),r=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return GE(c)},s=async()=>{let g=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),c={},I=le(g,"groups");if(I){let d=PA(I,"group");for(let B of d){let f=GE({tag:"result",attrs:{},content:[B]});c[f.id]=f}}return t.ev.emit("groups.update",Object.values(c)),c};return t.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=le(g,"dirty");c.type==="groups"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,groupMetadata:r,groupCreate:async(g,c)=>{let I=zr(),d=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:I},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return GE(d)},groupLeave:async g=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"group",attrs:{id:g}}]}])},groupUpdateSubject:async(g,c)=>{await A(g,"set",[{tag:"subject",attrs:{},content:Buffer.from(c,"utf-8")}])},groupRequestParticipantsList:async g=>{let c=await A(g,"get",[{tag:"membership_approval_requests",attrs:{}}]),I=le(c,"membership_approval_requests");return PA(I,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:I,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=le(d,"membership_requests_action"),f=le(B,I);return PA(f,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:I,attrs:{},content:c.map(Q=>({tag:"participant",attrs:{jid:Q}}))}]),B=le(d,I);return PA(B,"participant").map(Q=>({status:Q.attrs.error||"200",jid:Q.attrs.jid,content:Q}))},groupUpdateDescription:async(g,c)=>{let d=(await r(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:zr()}:{delete:"true"},...d?{prev:d}:{}},content:c?[{tag:"body",attrs:{},content:Buffer.from(c,"utf-8")}]:void 0}])},groupInviteCode:async g=>{let c=await A(g,"get",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return le(c,"group")?.attrs.jid},groupRevokeInviteV4:async(g,c)=>!!await A(g,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:c}}]}]),groupAcceptInviteV4:i.createBufferedFunction(async(g,c)=>{g=typeof g=="string"?{remoteJid:g}:g;let I=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=ne.Message.GroupInviteMessage.fromObject(c),c.inviteExpiration=0,c.inviteCode="",i.emit("messages.update",[{key:g,update:{message:{groupInviteMessage:c}}}])),await a({key:{remoteJid:c.groupJid,id:zr(t.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:va()},"notify"),I.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return GE(c)},groupToggleEphemeral:async(g,c)=>{let I=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[I])},groupSettingUpdate:async(g,c)=>{await A(g,"set",[{tag:c,attrs:{}}])},groupMemberAddMode:async(g,c)=>{await A(g,"set",[{tag:"member_add_mode",attrs:{},content:c}])},groupJoinApprovalMode:async(g,c)=>{await A(g,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"group_join",attrs:{state:c}}]}])},groupFetchAllParticipating:s}},GE=n=>{let t=le(n,"group");if(!t){let B=le(n,"error");if(B){let f=B.attrs.code?+B.attrs.code:500,Q=B.attrs.text||"group metadata query failed";throw new LM.Boom(Q,{statusCode:f,data:B})}throw new LM.Boom("Invalid group metadata response: missing node",{data:n})}if(!t.attrs.id)throw new LM.Boom("Invalid group metadata response: missing group id",{data:t});let o=le(t,"description"),i,e,a,A,r,s;o&&(i=jA(o,"body"),a=o.attrs.participant?CA(o.attrs.participant):void 0,A=o.attrs.participant_pn?CA(o.attrs.participant_pn):void 0,r=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=t.attrs.id.includes("@")?t.attrs.id:Sr(t.attrs.id,"g.us"),c=le(t,"ephemeral")?.attrs.expiration,I=jA(t,"member_add_mode")==="all_member_add";return{id:g,notify:t.attrs.notify,addressingMode:t.attrs.addressing_mode==="lid"?kB.LID:kB.PN,subject:t.attrs.subject,subjectOwner:t.attrs.s_o,subjectOwnerPn:t.attrs.s_o_pn,subjectOwnerUsername:t.attrs.s_o_username,subjectTime:+t.attrs.s_t,size:t.attrs.size?+t.attrs.size:PA(t,"participant").length,creation:+t.attrs.creation,owner:t.attrs.creator?CA(t.attrs.creator):void 0,ownerPn:t.attrs.creator_pn?CA(t.attrs.creator_pn):void 0,ownerUsername:t.attrs.creator_username||void 0,owner_country_code:t.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:r,descTime:s,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_group"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:I,participants:PA(t,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:qA(B.jid)&&Tt(B.phone_number)?B.phone_number:void 0,lid:Tt(B.jid)&&qA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var FE=ze(jr(),1);var SXe=n=>{let{id:t,thread_metadata:o,viewer_metadata:i}=n;return{id:t,owner:void 0,name:o.name.text,creation_time:parseInt(o.creation_time,10),description:o.description.text,invite:o.invite,subscribers:parseInt(o.subscribers_count,10),verification:o.verification,picture:{id:o.picture.id,directPath:o.picture.direct_path},mute_state:i.mute}},wXe=n=>typeof n!="object"||n===null?null:"id"in n&&typeof n.id=="string"?n:"result"in n&&typeof n.result=="object"&&n.result!==null&&"id"in n.result?n.result:null,YIe=n=>{let t=xIe(n),{query:o,generateMessageTag:i}=t,e=(A,r,s)=>sQ(A,r,s,o,i),a=async(A,r)=>{let s={newsletter_id:A,updates:{...r,settings:null}};return e(s,ha.UPDATE_METADATA,"xwa2_newsletter_update")};return{...t,newsletterCreate:async(A,r)=>{let g=await e({input:{name:A,description:r??null}},ha.CREATE,Ra.xwa2_newsletter_create);return SXe(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},ha.SUBSCRIBERS,Ra.xwa2_newsletter_subscribers),newsletterMetadata:async(A,r)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:r,type:A.toUpperCase()}},g=await e(s,ha.METADATA,Ra.xwa2_newsletter_metadata);return wXe(g)},newsletterFollow:A=>e({newsletter_id:A},ha.FOLLOW,Ra.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},ha.UNFOLLOW,Ra.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},ha.MUTE,Ra.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},ha.UNMUTE,Ra.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,r)=>await a(A,{name:r}),newsletterUpdateDescription:async(A,r)=>await a(A,{description:r}),newsletterUpdatePicture:async(A,r)=>{let{img:s}=await Ub(r);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,r,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:r,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,r,s,g)=>{let c={count:r.toString()};return typeof s=="number"&&(c.since=s.toString()),g&&(c.after=g.toString()),await o({tag:"iq",attrs:{id:i(),type:"get",xmlns:"newsletter",to:A},content:[{tag:"message_updates",attrs:c}]})},subscribeNewsletterUpdates:async A=>{let r=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=le(r,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},ha.ADMIN_COUNT,Ra.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,r)=>{await e({newsletter_id:A,user_id:r},ha.CHANGE_OWNER,Ra.xwa2_newsletter_change_owner)},newsletterDemote:async(A,r)=>{await e({newsletter_id:A,user_id:r},ha.DEMOTE,Ra.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},ha.DELETE,Ra.xwa2_newsletter_delete_v2)}}};var jIe=n=>{let{logger:t,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:r,maxMsgRetryCount:s}=n,g=YIe(n),{ev:c,authState:I,messageMutex:d,signalRepository:B,upsertMessage:f,query:Q,fetchPrivacySettings:y,sendNode:m,groupMetadata:T,groupToggleEphemeral:_,registerSocketEndHandler:R}=g,H=B.lidMapping.getLIDForPN.bind(B.lidMapping),F=new Set,L=n.userDevicesCache||new ac({stdTTL:MI.USER_DEVICES,useClones:!1}),q=gc(),z=r?new eM(t,s):null,K=LIe(),G,V=KU,U=async(fe=!1)=>{let Ie=await G;return(!Ie||fe||new Date().getTime()-Ie.fetchDate.getTime()>Ie.ttl*1e3)&&(G=(async()=>{let Xe=await Q({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:OA},content:[{tag:"media_conn",attrs:{}}]}),je=le(Xe,"media_conn"),be={hosts:PA(je,"host").map(({attrs:EA})=>({hostname:EA.hostname,maxContentLengthBytes:+EA.maxContentLengthBytes})),auth:je.attrs.auth,ttl:+je.attrs.ttl,fetchDate:new Date};return t.debug("fetched media conn"),be.hosts[0]&&(V=be.hosts[0].hostname),be})()),G},N=async(fe,Ie,Xe,je)=>{if(!Xe||Xe.length===0)throw new FE.Boom("missing ids in receipt");let be={tag:"receipt",attrs:{id:Xe[0]}};(je==="read"||je==="read-self")&&(be.attrs.t=va().toString()),je==="sender"&&(Tt(fe)||qA(fe))?(be.attrs.recipient=fe,be.attrs.to=Ie):(be.attrs.to=fe,Ie&&(be.attrs.participant=Ie)),je&&(be.attrs.type=je);let hA=Xe.slice(1);hA.length&&(be.content=[{tag:"list",attrs:{},content:hA.map(iA=>({tag:"item",attrs:{id:iA}}))}]),t.debug({attrs:be.attrs,messageIds:Xe},"sending receipt for messages"),await m(be)},k=async(fe,Ie)=>{let Xe=Zne(fe);for(let{jid:je,participant:be,messageIds:EA}of Xe)await N(je,be,EA,Ie)},J=async fe=>{let Xe=(await y()).readreceipts==="all"?"read":"read-self";await k(fe,Xe)},X=async(fe,Ie,Xe)=>{let je=[];Ie||t.debug("not using cache for devices");let be=[],EA=fe.map(Ce=>{let ke=fA(Ce),Ue=ke?.user,MA=ke?.device;return typeof MA=="number"&&MA>=0&&Ue?(je.push({user:Ue,device:MA,jid:Ce}),null):(Ce=CA(Ce),{jid:Ce,user:Ue})}).filter(Ce=>Ce!==null),hA;if(Ie&&L.mget){let Ce=EA.map(ke=>ke?.user).filter(Boolean);hA=await L.mget(Ce)}for(let{jid:Ce,user:ke}of EA)if(Ie){let Ue=hA?.[ke]||(L.mget?void 0:await L.get(ke));if(Ue){let MA=Ue.map(Ke=>({...Ke,jid:Sr(Ke.user,Ke.server,Ke.device)}));je.push(...MA),t.trace({user:ke},"using cache for devices")}else be.push(Ce)}else be.push(Ce);if(!be.length)return je;let iA=new Set;for(let Ce of be)if(qA(Ce)||Ea(Ce)){let ke=fA(Ce)?.user;ke&&iA.add(ke)}let Ze=new sg().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Ce of be)Ze.withUser(new ng().withId(Ce));let bA=await g.executeUSyncQuery(Ze);if(bA){let Ce=bA.list.filter(Ke=>!!Ke.lid);if(Ce.length>0){t.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Ce.map(Ke=>({lid:Ke.lid,pn:Ke.id})));try{let Ke=Ce.map(_A=>_A.lid);Ke.length&&await De(Ke,!0)}catch(Ke){t.warn({e:Ke,count:Ce.length},"failed to assert sessions for newly mapped LIDs")}}let ke=ose(bA?.list,I.creds.me.id,I.creds.me.lid,Xe),Ue={};for(let Ke of ke)Ue[Ke.user]=Ue[Ke.user]||[],Ue[Ke.user]?.push(Ke);for(let[Ke,_A]of Object.entries(Ue)){let ot=iA.has(Ke);for(let wA of _A){let ht=ot?Sr(Ke,wA.server,wA.device):Sr(wA.user,wA.server,wA.device);je.push({...wA,jid:ht}),t.debug({user:wA.user,device:wA.device,finalJid:ht,usedLid:ot},"Processed device with LID priority")}}await q.mutex(async()=>{if(L.mset)await L.mset(Object.entries(Ue).map(([Ke,_A])=>({key:Ke,value:_A})));else for(let Ke in Ue)Ue[Ke]&&await L.set(Ke,Ue[Ke])});let MA={};for(let[Ke,_A]of Object.entries(Ue))_A&&_A.length>0&&(MA[Ke]=_A.map(ot=>ot.device?.toString()||"0"));if(Object.keys(MA).length>0)try{await I.keys.set({"device-list":MA}),t.debug({userCount:Object.keys(MA).length},"stored user device lists for bulk migration")}catch(Ke){t.warn({error:Ke},"failed to store user device lists")}}return je},ae=(fe,Ie)=>Be(fe,{protocolMessage:{type:ne.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:Ie?.slice(0,30),labelTimestamp:va()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),De=async(fe,Ie)=>{let Xe=!1,je=[...new Set(fe)],be=[];t.debug({jids:fe},"assertSessions call with jids");for(let EA of je)!Ie&&(await B.validateSession(EA)).exists||be.push(EA);if(be.length){let EA=[...be.filter(iA=>!!qA(iA)||!!Ea(iA)),...(await B.lidMapping.getLIDsForPNs(be.filter(iA=>!!Tt(iA)||!!wr(iA)))||[]).map(iA=>iA.lid)];t.debug({jidsRequiringFetch:be,wireJids:EA},"fetching sessions");let hA=await Q({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:OA},content:[{tag:"key",attrs:{},content:EA.map(iA=>{let Ze={jid:iA};return Ie&&(Ze.reason="identity"),{tag:"user",attrs:Ze}})}]});await ise(hA,B),Xe=!0}return Xe},oe=async fe=>{if(!I.creds.me?.id)throw new FE.Boom("Not authenticated");let Ie={protocolMessage:{peerDataOperationRequestMessage:fe,type:ne.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},Xe=CA(I.creds.me.id);return await Be(Xe,Ie,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},Se=async(fe,Ie,Xe,je)=>{if(!fe.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let be=await a(Ie,fe),EA=Array.isArray(be)?be:fe.map(Ue=>({recipientJid:Ue,message:be})),hA=!1,iA=I.creds.me.id,Ze=I.creds.me?.lid,bA=Ze?fA(Ze)?.user:null,Ce=EA.map(async({recipientJid:Ue,message:MA})=>{try{if(!Ue)return null;let Ke=MA;if(je){let{user:ht}=fA(Ue),{user:Br}=fA(iA),UA=bA;(ht===Br||UA&&ht===UA)&&!(Ue===iA||Ze&&Ue===Ze)&&(Ke=je,t.debug({jid:Ue,targetUser:ht},"Using DSM for own device"))}let _A=_h(Ke),ot=Ue;return await K.mutex(ot,async()=>{let{type:ht,ciphertext:Br}=await B.encryptMessage({jid:Ue,data:_A});return ht==="pkmsg"&&(hA=!0),{tag:"to",attrs:{jid:Ue},content:[{tag:"enc",attrs:{v:"2",type:ht,...Xe||{}},content:Br}]}})}catch(Ke){return t.error({jid:Ue,err:Ke},"Failed to encrypt for recipient"),null}}),ke=(await Promise.all(Ce)).filter(Ue=>Ue!==null);if(fe.length>0&&ke.length===0)throw new FE.Boom("All encryptions failed",{statusCode:500});return{nodes:ke,shouldIncludeDeviceIdentity:hA}},Be=async(fe,Ie,{messageId:Xe,participant:je,additionalAttributes:be,additionalNodes:EA,useUserDevicesCache:hA,useCachedGroupMetadata:iA,statusJidList:Ze})=>{let bA=jse(I.creds),Ce=I.creds.me?.lid,ke=!!je?.jid,Ue=ke,MA="status@broadcast",{user:Ke,server:_A}=fA(fe),ot=_A==="g.us",wA=fe===MA,ht=_A==="lid",Br=_A==="newsletter",UA=ot||wA,de=fe;Xe=Xe||zr(bA),hA=hA!==!1,iA=iA!==!1&&!wA;let Qe=[],Me=wA?MA:de,oA=[],dA=[],FA,Yt={deviceSentMessage:{destinationJid:Me,message:Ie},messageContextInfo:Ie.messageContextInfo},ct={};if(je){!ot&&!wA&&(be={...be,device_fanout:"false"});let{user:br,device:or}=fA(je.jid);dA.push({user:br,device:or,jid:je.jid})}return await I.keys.transaction(async()=>{let br=Ne(Ie);if(br&&(ct.mediatype=br),Br){let Ee=a?await a(Ie,[]):Ie,he=eee(Ee);oA.push({tag:"plaintext",attrs:{},content:he});let ye={tag:"message",attrs:{to:fe,id:Xe,type:Re(Ie),...be||{}},content:oA};t.debug({msgId:Xe},`sending newsletter message to ${fe}`),await m(ye);return}if((ya(Ie)?.pinInChatMessage||ya(Ie)?.reactionMessage)&&(ct["decrypt-fail"]="hide"),UA&&!ke){let[Ee,he]=await Promise.all([(async()=>{let tA=iA&&A?await A(fe):void 0;return tA&&Array.isArray(tA?.participants)?t.trace({jid:fe,participants:tA.participants.length},"using cached group metadata"):wA||(tA=await T(fe)),tA})(),(async()=>!je&&!wA?(await I.keys.get("sender-key-memory",[fe]))[fe]||{}:{})()]),ye=Ee?Ee.participants.map(tA=>tA.id):[];Ee?.ephemeralDuration&&Ee.ephemeralDuration>0&&(be={...be,expiration:Ee.ephemeralDuration.toString()}),wA&&Ze&&ye.push(...Ze);let qe=await X(ye,!!hA,!1);dA.push(...qe),ot&&(be={...be,addressing_mode:Ee?.addressingMode||"lid"});let IA=await a(Ie);if(Array.isArray(IA))throw new FE.Boom("Per-jid patching is not supported in groups");let yA=_h(IA);FA=IA;let vA=(be?.addressing_mode||Ee?.addressingMode||"lid")==="lid"&&Ce?Ce:bA,{ciphertext:YA,senderKeyDistributionMessage:At}=await B.encryptGroupMessage({group:Me,data:yA,meId:vA}),Ge=[];for(let tA of dA){let tt=tA.jid;(!!!he[tt]||je)&&!Ea(tt)&&!wr(tt)&&tA.device!==99&&(Ge.push(tt),he[tt]=!0)}if(Ge.length){t.debug({senderKeyJids:Ge},"sending new sender key");let tA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:At,groupId:Me}};await De(Ge);let ea=await Se(Ge,tA,ct);Ue=Ue||ea.shouldIncludeDeviceIdentity,Qe.push(...ea.nodes)}oA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...ct},content:YA}),await I.keys.set({"sender-key-memory":{[fe]:he}})}else{let Ee=bA;ht&&Ce?(Ee=Ce,t.debug({to:fe,ownId:Ee},"Using LID identity for @lid conversation")):t.debug({to:fe,ownId:Ee},"Using PN identity for @s.whatsapp.net conversation");let{user:he}=fA(Ee);if(!je){let tA=await a(Ie,[fe]);FA=Array.isArray(tA)?tA.find(tt=>tt.recipientJid===fe)||tA[0]:tA}if(!ke){let tA=ht?"lid":"s.whatsapp.net";if(dA.push({user:Ke,device:0,jid:Sr(Ke,tA,0)}),Ke!==he){let tt=ht?"lid":"s.whatsapp.net",ea=ht&&Ce?fA(Ce).user:fA(bA).user;dA.push({user:ea,device:0,jid:Sr(ea,tt,0)})}if(be?.category!=="peer"){dA.length=0;let tt=ht&&Ce?Sr(fA(Ce)?.user,"lid",void 0):Sr(fA(bA)?.user,"s.whatsapp.net",void 0),ea=await X([tt,fe],!0,!1);dA.push(...ea),t.debug({deviceCount:dA.length,devices:dA.map(nr=>`${nr.user}:${nr.device}@${fA(nr.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let ye=[],qe=[],IA=[],{user:yA}=fA(bA),{user:$A}=Ce?fA(Ce):{user:null};for(let{user:tA,jid:tt}of dA){if(tt===bA||Ce&&tt===Ce){t.debug({jid:tt,meId:bA,meLid:Ce},"Skipping exact sender device (whatsmeow pattern)");continue}tA===yA||tA===$A?qe.push(tt):IA.push(tt),ye.push(tt)}await De(ye);let[{nodes:vA,shouldIncludeDeviceIdentity:YA},{nodes:At,shouldIncludeDeviceIdentity:Ge}]=await Promise.all([Se(qe,Yt||Ie,ct),Se(IA,Ie,ct,Yt)]);Qe.push(...vA),Qe.push(...At),(qe.length>0||IA.length>0)&&(ct.phash=Y$([...qe,...IA])),Ue=Ue||YA||Ge}if(ke){let Ee=qA(je.jid),he=kt(je.jid,Ee?Ce:bA),ye=Ie;if(UA){let $A;if(Ce&&await B.hasSenderKey({group:Me,meId:Ce})?$A=Ce:await B.hasSenderKey({group:Me,meId:bA})&&($A=bA),$A)try{let vA=await B.getSenderKeyDistributionMessage({group:Me,meId:$A});ye={...Ie,senderKeyDistributionMessage:{groupId:Me,axolotlSenderKeyDistributionMessage:vA}}}catch(vA){t.warn({err:vA,jid:Me},"failed to build SKDM for retry, sending without it")}}let qe=he?_h({deviceSentMessage:{destinationJid:Me,message:ye}}):_h(ye),{type:IA,ciphertext:yA}=await B.encryptMessage({data:qe,jid:je.jid});oA.push({tag:"enc",attrs:{v:"2",type:IA,count:je.count.toString()},content:yA})}if(Qe.length)if(be?.category==="peer"){let Ee=Qe[0]?.content?.[0];Ee&&oA.push(Ee)}else oA.push({tag:"participants",attrs:{},content:Qe});let or={tag:"message",attrs:{id:Xe,to:Me,type:Re(Ie),...be||{}},content:oA};if(je?Jr(Me)?(or.attrs.to=Me,or.attrs.participant=je.jid):kt(je.jid,bA)?(or.attrs.to=je.jid,or.attrs.recipient=Me):or.attrs.to=je.jid:or.attrs.to=Me,Ue&&(or.content.push({tag:"device-identity",attrs:{},content:Jf(I.creds.account,!0)}),t.debug({jid:fe},"adding device identity")),!Br&&!ke&&FA?.messageContextInfo?.messageSecret&&xb(FA))try{let Ee=_h(FA),he={id:Xe,fromMe:!0,remoteJid:Me,participant:je?.jid},ye=await Jne(Ee,FA,he);ye&&(or.content.push(ye),t.trace({jid:fe},"added reporting token to message"))}catch(Ee){t.warn({jid:fe,trace:Ee?.stack},"failed to attach reporting token")}let mo=be?.category==="peer",to=!ot&&!ke&&!wA&&!Br&&!mo,Ae=to?await rg(Me,H):Me,$=(to?await I.keys.get("tctoken",[Ae]):{})[Ae],re=$?.token;if(re?.length&&Ed($?.timestamp)){t.debug({jid:Me,timestamp:$?.timestamp},"tctoken expired, clearing"),re=void 0;let Ee=$?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:$.senderTimestamp}:null;try{await I.keys.set({tctoken:{[Ae]:Ee}})}catch(he){t.debug({jid:Me,err:he?.message},"failed to persist tctoken expiry cleanup")}}re?.length&&g.serverProps.privacyTokenOn1to1&&or.content.push({tag:"tctoken",attrs:{},content:re}),EA&&EA.length>0&&or.content.push(...EA),t.debug({msgId:Xe},`sending message to ${Qe.length} devices`),await m(or);let se=!!ya(Ie)?.protocolMessage,we=Me===s$||c$(Me)||mh(Me);if(to&&!se&&!we&&Wse($?.senderTimestamp)&&!F.has(Ae)){F.add(Ae);let Ee=va(),he=B.lidMapping.getPNForLID.bind(B.lidMapping);Zf(Me,g.serverProps.lidTrustedTokenIssueToLid,H,he).then(ye=>Je([ye],Ee)).then(async ye=>{await wE({result:ye,fallbackJid:Ae,keys:I.keys,getLIDForPN:H});let IA=(await I.keys.get("tctoken",[Ae]))[Ae],yA=await SE(I.keys,[Ae]);await I.keys.set({tctoken:{[Ae]:{token:Buffer.alloc(0),...IA,senderTimestamp:Ee},...yA}})}).catch(ye=>{t.debug({jid:Me,err:ye?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{F.delete(Ae)})}z&&!je&&z.addRecentMessage(Me,Xe,Ie)},bA),Xe},Re=fe=>{let Ie=ya(fe);return Ie?Ie.reactionMessage||Ie.encReactionMessage?"reaction":Ie.pollCreationMessage||Ie.pollCreationMessageV2||Ie.pollCreationMessageV3||Ie.pollUpdateMessage?"poll":Ie.eventMessage?"event":Ne(Ie)!==""?"media":"text":"text"},Ne=fe=>fe.imageMessage?"image":fe.videoMessage?fe.videoMessage.gifPlayback?"gif":"video":fe.audioMessage?fe.audioMessage.ptt?"ptt":"audio":fe.contactMessage?"vcard":fe.documentMessage?"document":fe.contactsArrayMessage?"contact_array":fe.liveLocationMessage?"livelocation":fe.stickerMessage?"sticker":fe.listMessage?"list":fe.listResponseMessage?"list_response":fe.buttonsResponseMessage?"buttons_response":fe.orderMessage?"order":fe.productMessage?"product":fe.interactiveResponseMessage?"native_flow_response":fe.groupInviteMessage?"url":"",Je=async(fe,Ie)=>{let Xe=(Ie??va()).toString();return await Q({tag:"iq",attrs:{to:OA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:fe.map(be=>({tag:"token",attrs:{jid:CA(be),t:Xe,type:"trusted_contact"}}))}]})},ve=Gne(n,U),aA=_L(c,"messages.media-update");return R(()=>{!n.userDevicesCache&&L.close&&L.close(),G=void 0,z&&z.clear()}),{...g,userDevicesCache:L,devicesMutex:q,issuePrivacyTokens:Je,assertSessions:De,relayMessage:Be,sendReceipt:N,sendReceipts:k,readMessages:J,refreshMediaConn:U,getMediaHost:()=>V,waUploadToServer:ve,fetchPrivacySettings:y,sendPeerDataOperationMessage:oe,createParticipantNodes:Se,getUSyncDevices:X,messageRetryManager:z,updateMemberLabel:ae,updateMediaMessage:async fe=>{let Ie=Xne(fe.message),Xe=Ie.mediaKey,je=I.creds.me.id,be=Lne(fe.key,Xe,je),EA;if(await Promise.all([m(be),aA(async hA=>{let iA=hA.find(Ze=>Ze.key.id===fe.key.id);if(iA){if(iA.error)EA=iA.error;else try{let Ze=Hne(iA.media,Xe,iA.key.id);if(Ze.result!==ne.MediaRetryNotification.ResultType.SUCCESS){let bA=ne.MediaRetryNotification.ResultType[Ze.result];throw new FE.Boom(`Media re-upload failed by device (${bA})`,{data:Ze,statusCode:xU(Ze.result)||404})}Ie.directPath=Ze.directPath,Ie.url=Uf(Ie.directPath,V),t.debug({directPath:Ze.directPath,key:iA.key},"media update successful")}catch(Ze){EA=Ze}return!0}})]),EA)throw EA;return c.emit("messages.update",[{key:fe.key,update:{message:fe.message}}]),fe},sendMessage:async(fe,Ie,Xe={})=>{let je=I.creds.me.id;if(typeof Ie=="object"&&"disappearingMessagesInChat"in Ie&&typeof Ie.disappearingMessagesInChat<"u"&&Jr(fe)){let{disappearingMessagesInChat:be}=Ie;await _(fe,typeof be=="boolean"?be?Yf:0:be)}else{let be=await Vne(fe,Ie,{logger:t,userJid:je,getUrlInfo:Ue=>Vse(Ue,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:t,uploadImage:i?ve:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:ve,mediaCache:n.mediaCache,options:n.options,messageId:zr(g.user?.id),...Xe}),EA="event"in Ie&&!!Ie.event,hA="delete"in Ie&&!!Ie.delete,iA="edit"in Ie&&!!Ie.edit,Ze="pin"in Ie&&!!Ie.pin,bA="poll"in Ie&&!!Ie.poll,Ce={},ke=[];return hA?Jr(Ie.delete?.remoteJid)&&!Ie.delete?.fromMe?Ce.edit="8":Ce.edit="7":iA?Ce.edit="1":Ze?Ce.edit="2":bA?ke.push({tag:"meta",attrs:{polltype:"creation"}}):EA&&ke.push({tag:"meta",attrs:{event_type:"creation"}}),await Be(fe,be.message,{messageId:be.key.id,useCachedGroupMetadata:Xe.useCachedGroupMetadata,additionalAttributes:Ce,statusJidList:Xe.statusJidList,additionalNodes:ke}),n.emitOwnEvents&&process.nextTick(async()=>{await d.mutex(()=>f(be,"append"))}),be}}}};var DXe=new Set(Object.values(AI));function OXe(n){return typeof n=="string"&&DXe.has(n)}var JIe=n=>{let{logger:t,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,r=jIe(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:I,ws:d,messageMutex:B,notificationMutex:f,receiptMutex:Q,signalRepository:y,query:m,upsertMessage:T,resyncAppState:_,onUnexpectedError:R,assertSessions:H,sendNode:F,relayMessage:L,sendReceipt:q,uploadPreKeys:z,sendPeerDataOperationMessage:K,messageRetryManager:G,registerSocketEndHandler:V,issuePrivacyTokens:U,fetchAccountReachoutTimelock:N,placeholderResendCache:k}=r,J=y.lidMapping.getLIDForPN.bind(y.lidMapping),X=gc(),ae=n.msgRetryCounterCache||new ac({stdTTL:MI.MSG_RETRY,useClones:!1}),De=n.callOfferCache||new ac({stdTTL:MI.CALL_OFFER,useClones:!1}),oe=new ac({stdTTL:5,useClones:!1}),Se=!1,Be=async(Ae,W,$)=>{if(!I.creds.me?.id)throw new gQ.Boom("Not authenticated");let re={historySyncOnDemandRequest:{chatJid:W.remoteJid,oldestMsgFromMe:W.fromMe,oldestMsgId:W.id,oldestMsgTimestampMs:$,onDemandMsgCount:Ae},peerDataOperationRequestType:ne.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return K(re)},Re=async(Ae,W)=>{if(!I.creds.me?.id)throw new gQ.Boom("Not authenticated");if(await k.get(Ae?.id)){t.debug({messageKey:Ae},"already requested resend");return}else await k.set(Ae?.id,W||!0);if(await JB(2e3),!await k.get(Ae?.id))return t.debug({messageKey:Ae},"message received while resend requested"),"RESOLVED";let $={placeholderMessageResendRequest:[{messageKey:Ae}],peerDataOperationRequestType:ne.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await k.get(Ae?.id)&&(t.debug({messageKey:Ae},"PDO message without response after 8 seconds. Phone possibly offline"),await k.del(Ae?.id))},8e3),K($)},Ne=async Ae=>{let W=le(Ae,"update");if(W){let $=W.attrs?.op_name;if(!$){t.warn({node:xn(Ae)},"mex notification missing op_name, fallback to legacy"),await aA(Ae);return}let re;try{re=JSON.parse(W.content.toString())}catch(we){t.error({err:we,opName:$},"failed to parse mex notification JSON");return}if(re.errors?.length){t.warn({errors:re.errors,opName:$},"mex notification has GQL errors");return}let se=re.data;if(!se){t.warn({opName:$},"mex notification has null data");return}switch(t.debug({opName:$},"processing mex notification"),$){case"NotificationUserReachoutTimelockUpdate":Je(se);break;case"MessageCappingInfoNotification":ve(se);break;case"NotificationNewsletterUpdate":case"NotificationLinkedProfilesUpdates":case"NotificationNewsletterAdminPromote":case"NotificationNewsletterAdminDemote":case"NotificationNewsletterUserSettingChange":case"NotificationNewsletterJoin":case"NotificationNewsletterLeave":case"NotificationNewsletterStateChange":case"NotificationNewsletterAdminMetadataUpdate":case"NotificationNewsletterOwnerUpdate":case"NotificationNewsletterAdminInviteRevoke":case"NotificationNewsletterWamoSubStatusChange":case"NotificationNewsletterBlockUser":case"NotificationNewsletterPaidPartnership":case"NotificationNewsletterMilestone":case"NewsletterResponseStateUpdate":await aA(Ae);break;default:t.debug({opName:$},"unhandled mex notification");break}return}await aA(Ae)},Je=Ae=>{let W=Ae.xwa2_notify_account_reachout_timelock;if(!W){t.warn("reachout timelock notification missing payload");return}if(!W.is_active){t.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:AI.DEFAULT}});return}let $=W.time_enforcement_ends?new Date(parseInt(W.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),re=OXe(W.enforcement_type)?W.enforcement_type:AI.DEFAULT;t.info({enforcementType:re,timeEnforcementEnds:$},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:$,enforcementType:re}})},ve=Ae=>{let W=Ae.xwa2_notify_new_chat_messages_capping_info_update;if(!W){t.warn("message capping notification missing payload");return}t.info({payload:W},"received message capping update"),c.emit("message-capping.update",W)},aA=async Ae=>{let W=le(Ae,"mex"),$=W?.content?null:le(Ae,"update")||vs(Ae)[0],re=W?.content?W:$;if(!re?.content){t.warn({node:xn(Ae)},"invalid mex newsletter notification");return}let se;try{let he=re.content;if(Array.isArray(he)){t.warn({payloadNode:re},"invalid mex newsletter notification payload format");return}let ye=typeof he=="string"?Buffer.from(he,"binary"):Buffer.from(he);se=JSON.parse(ye.toString())}catch(he){t.error({err:he,node:xn(Ae)},"failed to parse mex newsletter notification");return}let we=se?.operation??re?.attrs?.op_name,Ee=se?.updates;if(!Ee){let he=se?.data?.xwa2_notify_linked_profiles;he&&(Ee=[he])}if(!Ee||!we){t.warn({data:se},"invalid mex newsletter notification content");return}switch(t.info({operation:we,updates:Ee},"got mex newsletter notification"),we){case"NotificationNewsletterUpdate":for(let he of Ee)he.jid&&he.settings&&Object.keys(he.settings).length>0&&c.emit("newsletter-settings.update",{id:he.jid,update:he.settings});break;case"NotificationNewsletterAdminPromote":for(let he of Ee)he.jid&&he.user&&c.emit("newsletter-participants.update",{id:he.jid,author:Ae.attrs.from,user:he.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let he of Ee){let ye=he?.jid,qe=Array.isArray(he?.added_profiles)?he.added_profiles:[],IA=[];for(let yA of qe){let $A=typeof yA=="string"?yA:yA?.pn??yA?.jid??null;if(ye&&$A){let vA={lid:ye,pn:$A};c.emit("lid-mapping.update",vA),IA.push(vA)}}await y.lidMapping.storeLIDPNMappings(IA)}break;default:t.info({operation:we,data:se},"unhandled mex newsletter notification");break}},fe=async Ae=>{let W=Ae.attrs.from,$=vs(Ae),re=Ae.attrs.participant;for(let se of $)switch(t.debug({from:W,child:se},"got newsletter notification"),se.tag){case"reaction":{let we={id:W,server_id:se.attrs.message_id,reaction:{code:jA(se,"reaction"),count:1}};c.emit("newsletter.reaction",we);break}case"view":{let we={id:W,server_id:se.attrs.message_id,count:parseInt(se.content?.toString()||"0",10)};c.emit("newsletter.view",we);break}case"participant":{let we={id:W,author:re,user:se.attrs.jid,action:se.attrs.action,new_role:se.attrs.role};c.emit("newsletter-participants.update",we);break}case"update":{let we=le(se,"settings");if(we){let Ee={},he=le(we,"name");he?.content&&(Ee.name=he.content.toString());let ye=le(we,"description");ye?.content&&(Ee.description=ye.content.toString()),c.emit("newsletter-settings.update",{id:W,update:Ee})}break}case"message":{let we=le(se,"plaintext");if(we?.content)try{let Ee=typeof we.content=="string"?Buffer.from(we.content,"binary"):Buffer.from(we.content),he=ne.Message.decode(Ee).toJSON(),ye=ne.WebMessageInfo.fromObject({key:{remoteJid:W,id:se.attrs.message_id||se.attrs.server_id,fromMe:!1},message:he,messageTimestamp:+se.attrs.t}).toJSON();await T(ye,"append"),t.debug("Processed plaintext newsletter message")}catch(Ee){t.error({error:Ee},"Failed to decode plaintext newsletter message")}break}default:t.warn({node:Ae,child:se},"Unknown newsletter notification child");break}},Ie=async(Ae,W)=>{let $=age(Ae,W,I.creds.me.id);t.debug({recv:{tag:Ae.tag,attrs:Ae.attrs},sent:$.attrs},"sent ack"),await F($)},Xe=async(Ae,W)=>{let $={tag:"call",attrs:{from:I.creds.me.id,to:W},content:[{tag:"reject",attrs:{"call-id":Ae,"call-creator":W,count:"0"},content:void 0}]};await m($)},je=async(Ae,W=!1)=>{let{fullMessage:$}=NL(Ae,I.creds.me.id,I.creds.me.lid||""),{key:re}=$,se=re.id;if(G){if(G.hasExceededMaxRetries(se)){t.debug({msgId:se},"reached retry limit with new retry manager, clearing"),G.markRetryFailed(se);return}let YA=G.incrementRetryCount(se),At=`${se}:${re?.participant}`;await ae.set(At,YA)}else{let YA=`${se}:${re?.participant}`,At=await ae.get(YA)||0;if(At>=i){t.debug({retryCount:At,msgId:se},"reached retry limit, clearing"),await ae.del(YA);return}At+=1,await ae.set(YA,At)}let we=`${se}:${re?.participant}`,Ee=await ae.get(we)||1,{account:he,signedPreKey:ye,signedIdentityKey:qe}=I.creds,IA=Ae.attrs.from,yA=!1,$A="";if(A&&G&&Ee>1)try{let YA=y.jidToSignalProtocolAddress(IA),At=await y.validateSession(IA),Ge=G.shouldRecreateSession(IA,At.exists);yA=Ge.recreate,$A=Ge.reason,yA&&(t.debug({fromJid:IA,retryCount:Ee,reason:$A},"recreating session for retry"),await I.keys.set({session:{[YA]:null}}),W=!0)}catch(YA){t.warn({error:YA,fromJid:IA},"failed to check session recreation")}if(Ee<=2)if(G)G.schedulePhoneRequest(se,async()=>{try{let YA=await Re(re);t.debug(`sendRetryRequest: requested placeholder resend (${YA}) for message ${se} (scheduled)`)}catch(YA){t.warn({error:YA,msgId:se},"failed to send scheduled phone request")}});else{let YA=await Re(re);t.debug(`sendRetryRequest: requested placeholder resend for message ${YA}`)}let vA=Jf(he,!0);await I.keys.transaction(async()=>{let YA={tag:"receipt",attrs:{id:se,type:"retry",to:Ae.attrs.from},content:[{tag:"retry",attrs:{count:Ee.toString(),id:Ae.attrs.id,t:Ae.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:qg(I.creds.registrationId)}]};if(Ae.attrs.recipient&&(YA.attrs.recipient=Ae.attrs.recipient),Ae.attrs.participant&&(YA.attrs.participant=Ae.attrs.participant),Ee>1||W||yA){let{update:At,preKeys:Ge}=await $U(I,1),[tA]=Object.keys(Ge),tt=Ge[+tA];YA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Jg)},{tag:"identity",attrs:{},content:qe.public},XU(tt,+tA),jf(ye),{tag:"device-identity",attrs:{},content:vA}]}),c.emit("creds.update",At)}await F(YA),t.info({msgAttrs:Ae.attrs,retryCount:Ee},"sent retry receipt")},I?.creds?.me?.id||"sendRetryRequest")},be=new Set,EA=Ae=>{(async()=>{let W=CA(Ae),$=await rg(W,J),se=(await I.keys.get("tctoken",[$]))?.[$]?.senderTimestamp;if(se==null||Ed(se))return;t.debug({jid:W,senderTimestamp:se},"identity changed, re-issuing tctoken");let we=y.lidMapping.getPNForLID.bind(y.lidMapping),Ee=await Zf(W,r.serverProps.lidTrustedTokenIssueToLid,J,we),he=await U([Ee],se);await wE({result:he,fallbackJid:$,keys:I.keys,getLIDForPN:J,onNewJidStored:_A})})().catch(W=>{t.debug({jid:Ae,err:W?.message},"failed to re-issue tctoken after identity change")})},hA=async Ae=>{if(Ae.attrs.from===OA){let $=Ae.attrs.id;if($&&be.has($))return;let se=+le(Ae,"count").attrs.value,we=se{let re=Ae.attrs.participant,se=Ae.attrs.participant_pn,we=Ae.attrs.participant_username,Ee=le(W,"participant")?.attrs?.jid||re,he=le(W,"participant")?.attrs?.phone_number||se;switch(W?.tag){case"create":let ye=GE(W);$.messageStubType=RA.GROUP_CREATE,$.messageStubParameters=[ye.subject],$.key={participant:ye.owner,participantAlt:ye.ownerPn},c.emit("chats.upsert",[{id:ye.id,name:ye.subject,conversationTimestamp:ye.creation}]),c.emit("groups.upsert",[{...ye,author:re,authorPn:se,authorUsername:we}]);break;case"ephemeral":case"not_ephemeral":$.message={protocolMessage:{type:ne.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(W.attrs.expiration||0)}};break;case"modify":let qe=PA(W,"participant").map(Ge=>Ge.attrs.jid);$.messageStubParameters=qe||[],$.messageStubType=RA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let IA=`GROUP_PARTICIPANT_${W.tag.toUpperCase()}`;$.messageStubType=RA[IA];let yA=PA(W,"participant").map(({attrs:Ge})=>({id:Ge.jid,phoneNumber:qA(Ge.jid)&&Tt(Ge.phone_number)?Ge.phone_number:void 0,lid:Tt(Ge.jid)&&qA(Ge.lid)?Ge.lid:void 0,username:Ge.participant_username||Ge.username||void 0,admin:Ge.type||null}));yA.length===1&&(kt(yA[0].id,re)||kt(yA[0].id,se))&&W.tag==="remove"&&($.messageStubType=RA.GROUP_PARTICIPANT_LEAVE),$.messageStubParameters=yA.map(Ge=>JSON.stringify(Ge));break;case"subject":$.messageStubType=RA.GROUP_CHANGE_SUBJECT,$.messageStubParameters=[W.attrs.subject];break;case"description":let $A=le(W,"body")?.content?.toString();$.messageStubType=RA.GROUP_CHANGE_DESCRIPTION,$.messageStubParameters=$A?[$A]:void 0;break;case"announcement":case"not_announcement":$.messageStubType=RA.GROUP_CHANGE_ANNOUNCE,$.messageStubParameters=[W.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":$.messageStubType=RA.GROUP_CHANGE_RESTRICT,$.messageStubParameters=[W.tag==="locked"?"on":"off"];break;case"invite":$.messageStubType=RA.GROUP_CHANGE_INVITE_LINK,$.messageStubParameters=[W.attrs.code];break;case"member_add_mode":let vA=W.content;vA&&($.messageStubType=RA.GROUP_MEMBER_ADD_MODE,$.messageStubParameters=[vA.toString()]);break;case"membership_approval_mode":let YA=le(W,"group_join");YA&&($.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,$.messageStubParameters=[YA.attrs.state]);break;case"created_membership_requests":$.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,$.messageStubParameters=[JSON.stringify({lid:Ee,pn:he}),"created",W.attrs.request_method];break;case"revoked_membership_requests":let At=kt(Ee,re);$.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,$.messageStubParameters=[JSON.stringify({lid:Ee,pn:he}),At?"revoked":"rejected"];break}},Ze=async Ae=>{let[W]=vs(Ae),$=CA(Ae.attrs.from);if(!W){t.debug({from:$},"devices notification missing child, skipping");return}let re=W.tag,se=W.attrs.device_hash,we=PA(W,"device");if(kt($,I.creds.me.id)||kt($,I.creds.me.lid)){let he=we.map(ye=>ye.attrs.jid);t.info({deviceJids:he},"got my own devices")}if(!we.length){t.debug({from:$,tag:re},"no devices in notification, skipping");return}let Ee=[];for(let he of we){let ye=he.attrs.jid;if(!ye)continue;let qe=fA(ye);if(!qe){t.debug({jid:ye},"failed to decode device jid, skipping");continue}Ee.push({jid:ye,user:qe.user,server:qe.server,device:qe.device})}Ee.length&&await g.mutex(async()=>{let he=new Map;for(let ye of Ee){let qe=he.get(ye.user)||[];qe.push(ye),he.set(ye.user,qe)}for(let[ye,qe]of he){if(re==="update"){t.debug({user:ye},`${ye}'s device list updated, dropping cached devices`),await s?.del(ye);continue}re==="remove"&&await y.deleteSession(qe.map(vA=>vA.jid));let IA=await s?.get(ye)||[];if(!IA.length){t.debug({user:ye,tag:re},"device list not cached, deferring to USync refresh");continue}let yA=new Set(qe.map(vA=>vA.device)),$A;switch(re){case"add":t.info({deviceHash:se,count:qe.length},"devices added"),$A=[...IA.filter(vA=>!yA.has(vA.device)),...qe.map(vA=>({user:vA.user,server:vA.server,device:vA.device}))];break;case"remove":t.info({deviceHash:se,count:qe.length},"devices removed"),$A=IA.filter(vA=>!yA.has(vA.device));break;default:t.debug({tag:re},"Unknown device list change tag");continue}$A.length===0?await s?.del(ye):await s?.set(ye,$A)}})},bA=async Ae=>{let W={},[$]=vs(Ae),re=Ae.attrs.type,se=CA(Ae.attrs.from);switch(re){case"newsletter":await fe(Ae);break;case"mex":await Ne(Ae);break;case"w:gp2":iA(Ae,$,W);break;case"mediaretry":let we=Une(Ae);c.emit("messages.media-update",[we]);break;case"encrypt":await hA(Ae);break;case"devices":try{await Ze(Ae)}catch(wo){t.error({error:wo,node:Ae},"failed to handle devices notification")}break;case"server_sync":let Ee=le(Ae,"collection");if(Ee){let wo=Ee.attrs.name;await _([wo],!1)}break;case"picture":let he=le(Ae,"set"),ye=le(Ae,"delete");if(c.emit("contacts.update",[{id:CA(Ae?.attrs?.from)||(he||ye)?.attrs?.hash||"",imgUrl:he?"changed":"removed"}]),Jr(se)){let wo=he||ye;W.messageStubType=RA.GROUP_CHANGE_ICON,he&&(W.messageStubParameters=[he.attrs.id]),W.participant=wo?.attrs.author,W.key={...W.key||{},participant:he?.attrs.author}}break;case"account_sync":if($.tag==="disappearing_mode"){let wo=+$.attrs.duration,Md=+$.attrs.t;t.info({newDuration:wo},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...I.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:wo,ephemeralSettingTimestamp:Md}}})}else if($.tag==="blocklist"){let wo=PA($,"item");for(let{attrs:Md}of wo){let WM=[Md.jid],ZM=Md.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:WM,type:ZM})}}break;case"link_code_companion_reg":let qe=le(Ae,"link_code_companion_reg"),IA=ht(ka(qe,"link_code_pairing_ref")),yA=ht(ka(qe,"primary_identity_pub")),$A=ht(ka(qe,"link_code_pairing_wrapped_primary_ephemeral_pub")),vA=await wA($A),YA=Dr.sharedKey(I.creds.pairingEphemeralKeyPair.private,vA),At=_K(32),Ge=_K(32),tA=Jn(YA,32,{salt:Ge,info:"link_code_pairing_key_bundle_encryption_key"}),tt=Buffer.concat([Buffer.from(I.creds.signedIdentityKey.public),yA,At]),ea=_K(12),nr=xl(tt,tA,ea,Buffer.alloc(0)),So=Buffer.concat([Ge,ea,nr]),zM=Dr.sharedKey(I.creds.signedIdentityKey.private,yA),VM=Buffer.concat([YA,zM,At]);I.creds.advSecretKey=Buffer.from(Jn(VM,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:OA,type:"set",id:r.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:I.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:So},{tag:"companion_identity_public",attrs:{},content:I.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:IA}]}]}),I.creds.registered=!0,c.emit("creds.update",I.creds);break;case"privacy_token":await ot(Ae);break}if(Object.keys(W).length)return W},Ce=new Set,ke=(async()=>{try{let Ae=await Xb(I.keys);for(let W of Ae)Ce.add(W);t.debug({count:Ce.size},"loaded tctoken index")}catch(Ae){t.warn({err:Ae?.message},"failed to load tctoken index")}})(),Ue;async function MA(){Ue&&(clearTimeout(Ue),Ue=void 0);let Ae=await SE(I.keys,Ce);return I.keys.set({tctoken:Ae})}function Ke(){Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{Ue=void 0,MA().catch(Ae=>{t.warn({err:Ae?.message},"failed to save tctoken index")})},5e3)}function _A(Ae){Ae&&Ae!==_I&&!Ce.has(Ae)&&(Ce.add(Ae),Ke())}let ot=async Ae=>{if(!le(Ae,"tokens"))return;let $=CA(Ae.attrs.from),se=(Ae.attrs.sender_lid&&qA(CA(Ae.attrs.sender_lid))?CA(Ae.attrs.sender_lid):void 0)??await rg($,J);t.debug({from:$,storageJid:se},"processing privacy token notification"),await wE({result:Ae,fallbackJid:se,keys:I.keys,getLIDForPN:J,onNewJidStored:_A})};async function wA(Ae){let W=ht(Ae),$=W.slice(0,32),re=await GD(I.creds.pairingCode,$),se=W.slice(32,48),we=W.slice(48,80);return G$(we,re,se)}function ht(Ae){if(Ae===void 0)throw new gQ.Boom("Invalid buffer",{statusCode:400});return Ae instanceof Buffer?Ae:Buffer.from(Ae)}let Br=async(Ae,W)=>{let $=`${Ae}:${W}`;return(await ae.get($)||0){let $=`${Ae}:${W}`,re=(await ae.get($)||0)+1;await ae.set($,re)},de=async(Ae,W,$,re)=>{let se=Ae.remoteJid,we=Ae.participant||se,Ee=+$.attrs.count||1,he=W[0],ye=[];for(let Ge of W){let tA;if(G){let tt=G.getRecentMessage(se,Ge);tt&&(tA=tt.message,t.debug({jid:se,id:Ge},"found message in retry cache"),G.markRetrySuccess(Ge))}tA||(tA=await e({...Ae,id:Ge}),tA&&(t.debug({jid:se,id:Ge},"found message via getMessage"),G&&G.markRetrySuccess(Ge))),ye.push(tA)}let qe=!fA(we)?.device,IA=y.jidToSignalProtocolAddress(we),yA=!1,$A=ase(re);if($A)try{await y.injectE2ESession({jid:we,session:$A}),yA=!0,t.debug({participant:we,retryCount:Ee},"injected session from retry receipt key bundle")}catch(Ge){t.warn({error:Ge,participant:we},"failed to inject session from retry receipt")}if(!yA){let Ge=rI(re,"registration",4);if(typeof Ge=="number"&&Number.isInteger(Ge)){let tA=await y.getSessionInfo(we);tA&&tA.registrationId!==0&&tA.registrationId!==Ge&&(t.info({participant:we,stored:tA.registrationId,received:Ge},"reg id mismatch on retry without bundle, deleting session"),await I.keys.set({session:{[IA]:null}}))}}let vA=2;if(he&&G){let Ge=await y.getSessionInfo(we);Ge&&(Ee===vA?G.saveBaseKey(IA,he,Ge.baseKey):Ee>vA&&(G.hasSameBaseKey(IA,he,Ge.baseKey)&&(t.warn({participant:we,retryCount:Ee},"base key collision on retry, forcing fresh session"),await I.keys.set({session:{[IA]:null}})),G.deleteBaseKey(IA,he)))}let YA=!1,At="";if(A&&G&&Ee>1&&!yA)try{let Ge=await y.validateSession(we),tA=G.shouldRecreateSession(we,Ge.exists);YA=tA.recreate,At=tA.reason,YA&&(t.debug({participant:we,retryCount:Ee,reason:At},"recreating session for outgoing retry"),await I.keys.set({session:{[IA]:null}}))}catch(Ge){t.warn({error:Ge,participant:we},"failed to check session recreation for outgoing retry")}yA||await H([we],!0),Jr(se)&&await I.keys.set({"sender-key-memory":{[se]:null}}),t.debug({participant:we,sendToAll:qe,shouldRecreateSession:YA,recreateReason:At,injectedFromBundle:yA},"prepared session for retry resend");for(let[Ge,tA]of ye.entries())if(W[Ge])if(tA&&await Br(W[Ge],we)){await UA(W[Ge],we);let tt={messageId:W[Ge]};qe?tt.useUserDevicesCache=!1:tt.participant={jid:we,count:+$.attrs.count},await L(Ae.remoteJid,tA,tt)}else t.debug({jid:Ae.remoteJid,id:W[Ge]},"recv retry request, but message not available")},Qe=async Ae=>{let{attrs:W,content:$}=Ae,re=W.from.includes("lid"),se=kt(W.participant||W.from,re?I.creds.me?.lid:I.creds.me?.id),we=!se||Jr(W.from)?W.from:W.recipient,Ee=!W.recipient||(W.type==="retry"||W.type==="sender")&&se,he={remoteJid:we,id:"",fromMe:Ee,participant:W.participant},ye=[W.id];if(Array.isArray($)){let qe=PA($[0],"item");ye.push(...qe.map(IA=>IA.attrs.id))}try{await Promise.all([Q.mutex(async()=>{let qe=V$(W.type);if(typeof qe<"u"&&(qe>=ne.WebMessageInfo.Status.SERVER_ACK||!se))if(Jr(we)||Yg(we)){if(W.participant){let IA=qe===ne.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",ye.map(yA=>({key:{...he,id:yA},receipt:{userJid:CA(W.participant),[IA]:+W.t}})))}}else c.emit("messages.update",ye.map(IA=>({key:{...he,id:IA},update:{status:qe,messageTimestamp:qr(+(W.t??0))}})));if(W.type==="retry"){he.participant=he.participant||W.from;let IA=le(Ae,"retry");if(ye[0]&&he.participant&&await Br(ye[0],he.participant))if(he.fromMe)try{await UA(ye[0],he.participant),t.debug({attrs:W,key:he},"recv retry request"),await de(he,ye,IA,Ae)}catch(yA){t.error({key:he,ids:ye,trace:yA instanceof Error?yA.stack:"Unknown error"},"error in sending message again")}else t.info({attrs:W,key:he},"recv retry for not fromMe message");else t.info({attrs:W,key:he},"will not send message again, as sent too many times")}})])}finally{await Ie(Ae).catch(qe=>t.error({ackErr:qe},"failed to ack receipt"))}},Me=async Ae=>{let W=Ae.attrs.from;try{await Promise.all([f.mutex(async()=>{let $=await bA(Ae);if($){let re=kt(Ae.attrs.participant||W,I.creds.me.id),{senderAlt:se,addressingMode:we}=HD(Ae);$.key={remoteJid:W,fromMe:re,participant:Ae.attrs.participant,participantAlt:se,participantUsername:Ae.attrs.participant_username,addressingMode:we,id:Ae.attrs.id,...$.key||{}},$.participant??($.participant=Ae.attrs.participant),$.messageTimestamp=+Ae.attrs.t;let Ee=ne.WebMessageInfo.fromObject($);await T(Ee,"append")}})])}finally{await Ie(Ae).catch($=>t.error({ackErr:$},"failed to ack notification"))}},oA=async Ae=>{if(le(Ae,"enc")?.attrs.type==="msmsg"){t.debug({key:Ae.attrs.key},"ignored msmsg"),await Ie(Ae,Jl.MissingMessageSecret);return}let $=!1;try{let{fullMessage:re,category:se,author:we,decrypt:Ee}=ree(Ae,I.creds.me.id,I.creds.me.lid||"",y,t),he=re.key.participantAlt||re.key.remoteJidAlt;if(he){let ye=fA(he)?.server,qe=re.key.participant||re.key.remoteJid;ye==="lid"?await y.lidMapping.getPNForLID(he)||(await y.lidMapping.storeLIDPNMappings([{lid:he,pn:qe}]),await y.migrateSession(qe,he)):(await y.lidMapping.storeLIDPNMappings([{lid:qe,pn:he}]),await y.migrateSession(he,qe))}await B.mutex(async()=>{if(await Ee(),re.key?.remoteJid&&re.key?.id&&re.message&&G&&G.addRecentMessage(re.key.remoteJid,re.key.id,re.message),re.messageStubType===ne.WebMessageInfo.StubType.CIPHERTEXT&&re.category!=="peer"){if(re?.messageStubParameters?.[0]===Aee)return $=!0,Ie(Ae,Jl.ParsingError);if(re.messageStubParameters?.[0]===UD){let qe=le(Ae,"unavailable")?.attrs?.type;if(qe==="bot_unavailable_fanout"||qe==="hosted_unavailable_fanout"||qe==="view_once_unavailable_fanout")return t.debug({msgId:re.key.id,unavailableType:qe},"skipping placeholder resend for excluded unavailable type"),$=!0,Ie(Ae);let IA=va()-qr(re.messageTimestamp);if(IA>BIe)return t.debug({msgId:re.key.id,messageAge:IA},"skipping placeholder resend for old message"),$=!0,Ie(Ae);let yA={remoteJid:re.key.remoteJid,fromMe:re.key.fromMe,id:re.key.id,participant:re.key.participant},$A={key:re.key,messageTimestamp:re.messageTimestamp,pushName:re.pushName,participant:re.participant,verifiedBizName:re.verifiedBizName};Re(yA,$A).then(vA=>{vA&&vA!=="RESOLVED"&&(t.debug({msgId:re.key.id,requestId:vA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:re.key,update:{messageStubParameters:[UD,vA]}}]))}).catch(vA=>{t.warn({err:vA,msgId:re.key.id},"failed to request placeholder resend for unavailable message")}),$=!0,await Ie(Ae)}else{if(Yg(re.key.remoteJid)){let ye=va()-qr(re.messageTimestamp);if(ye>CIe)return t.debug({msgId:re.key.id,messageAge:ye,remoteJid:re.key.remoteJid},"skipping retry for expired status message"),$=!0,Ie(Ae)}t.debug("[handleMessage] Attempting retry request for failed decryption"),await X.mutex(async()=>{try{if(!d.isOpen){t.debug({node:Ae},"Connection closed, skipping retry");return}let ye=le(Ae,"enc");await je(Ae,!ye),o&&await JB(o)}catch(ye){t.error({err:ye},"Failed to send retry")}$=!0,await Ie(Ae,Jl.UnhandledError)})}}else if(G&&re.key.id&&G.cancelPendingPhoneRequest(re.key.id),tI(re.key.remoteJid))$=!0,await Ie(Ae),t.debug({key:re.key},"processed newsletter message without receipts");else{let qe,IA=re.key.participant;if(se==="peer"?qe="peer_msg":re.key.fromMe?(qe="sender",(qA(re.key.remoteJid)||qA(re.key.remoteJidAlt))&&(IA=we)):Se||(qe="inactive"),$=!0,await q(re.key.remoteJid,IA,[re.key.id],qe),jb(re.message)){let $A=CA(re.key.remoteJid);await q($A,void 0,[re.key.id],"hist_sync")}}Zse(re,I.creds.me.id,I.creds.me.lid),await T(re,Ae.attrs.offline?"append":"notify")})}catch(re){t.error({error:re,node:xn(Ae)},"error in handling message"),$||await Ie(Ae,Jl.UnhandledError).catch(se=>t.error({ackErr:se},"failed to ack message after error"))}},dA=async Ae=>{try{let{attrs:W}=Ae,[$]=vs(Ae);if(!$)throw new gQ.Boom("Missing call info in call node");let re=Z$($),se=$.attrs["call-id"],we=$.attrs.from||$.attrs["call-creator"],Ee={chatId:W.from,from:we,callerPn:$.attrs.caller_pn,id:se,date:new Date(+W.t*1e3),offline:!!W.offline,status:re};if(re==="relaylatency"){let ye=$.attrs.latency||$.attrs.latency_ms||$.attrs["latency-ms"],qe=ye?Number(ye):void 0;Number.isFinite(qe)&&(Ee.latencyMs=qe)}re==="offer"&&(Ee.isVideo=!!le($,"video"),Ee.isGroup=$.attrs.type==="group"||!!$.attrs["group-jid"],Ee.groupJid=$.attrs["group-jid"],await De.set(Ee.id,Ee));let he=await De.get(Ee.id);he&&(Ee.isVideo=he.isVideo,Ee.isGroup=he.isGroup,Ee.callerPn=Ee.callerPn||he.callerPn),(re==="reject"||re==="accept"||re==="timeout"||re==="terminate")&&await De.del(Ee.id),c.emit("call",[Ee])}catch(W){t.error({error:W,node:xn(Ae)},"error in handling call")}finally{await Ie(Ae).catch(W=>t.error({ackErr:W},"failed to ack call"))}},FA=async({attrs:Ae})=>{let W={remoteJid:Ae.from,fromMe:!0,id:Ae.id};if(Ae.error){let $=Ae.error===String(Jl.SenderReachoutTimelocked);if(Ae.error===TL.MessageAccountRestriction){t.warn({msgId:Ae.id,from:Ae.from},"error 463: account restricted or missing tctoken for contact");let re=Ae.from;re&&!mo.has(re)&&(mo.add(re),(async()=>{try{let se=y.lidMapping.getPNForLID.bind(y.lidMapping),we=await rg(re,J),Ee=await Zf(re,r.serverProps.lidTrustedTokenIssueToLid,J,se),he=await U([Ee],va());await wE({result:he,fallbackJid:we,keys:I.keys,getLIDForPN:J,onNewJidStored:_A}),t.debug({from:re},"completed 463 token recovery issuance")}catch(se){t.debug({from:re,err:se?.message},"failed 463 token recovery issuance")}finally{mo.delete(re)}})())}else Ae.error===TL.SmaxInvalid?t.warn({msgId:Ae.id,from:Ae.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):$?(await N().catch(re=>t.warn({err:re},"failed to fetch reachout timelock")),t.warn({attrs:Ae},"received error in ack")):t.warn({attrs:Ae},"received error in ack");c.emit("messages.update",[{key:W,update:{status:yh.ERROR,messageStubParameters:$?[Ae.error,tee]:[Ae.error]}}])}},Yt=async(Ae,W,$)=>{c.buffer(),await re(),c.flush();function re(){return $(Ae,!1).catch(se=>R(se,W))}},ct=UIe(new Map([["message",oA],["call",dA],["receipt",Qe],["notification",Me]]),{isWsOpen:()=>d.isOpen,onUnexpectedError:R,yieldToEventLoop:()=>new Promise(Ae=>setImmediate(Ae))}),br=async(Ae,W,$,re)=>{let se=W.attrs.from,we=se;if(Ae==="receipt"&&se){let he=W.attrs,ye=he.from.includes("lid");we=!kt(he.participant||he.from,ye?I.creds.me?.lid:I.creds.me?.id)||Jr(he.from)?he.from:he.recipient}if(we&&we!==OA&&a(we)){await Ie(W,Ae==="message"?Jl.UnhandledError:void 0);return}!!W.attrs.offline?ct.enqueue(Ae,W):await Yt(W,$,re)};d.on("CB:message",async Ae=>{await br("message",Ae,"processing message",oA)}),d.on("CB:call",async Ae=>{await br("call",Ae,"handling call",dA)}),d.on("CB:receipt",async Ae=>{await br("receipt",Ae,"handling receipt",Qe)}),d.on("CB:notification",async Ae=>{await br("notification",Ae,"handling notification",Me)}),d.on("CB:ack,class:message",Ae=>{FA(Ae).catch(W=>R(W,"handling bad ack"))}),c.on("call",async([Ae])=>{if(Ae&&(Ae.status==="timeout"||Ae.status==="offer"&&Ae.isGroup)){let W={key:{remoteJid:Ae.chatId,id:Ae.id,fromMe:!1},messageTimestamp:va(Ae.date)};Ae.status==="timeout"?Ae.isGroup?W.messageStubType=Ae.isVideo?RA.CALL_MISSED_GROUP_VIDEO:RA.CALL_MISSED_GROUP_VOICE:W.messageStubType=Ae.isVideo?RA.CALL_MISSED_VIDEO:RA.CALL_MISSED_VOICE:W.message={call:{callKey:Buffer.from(Ae.id)}};let $=ne.WebMessageInfo.fromObject(W);await T($,Ae.offline?"append":"notify")}});let or=0,mo=new Set;c.on("connection.update",({isOnline:Ae,connection:W})=>{if(typeof Ae<"u"&&(Se=Ae,t.trace(`sendActiveReceipts set to "${Se}"`)),W==="close"&&Ue){clearTimeout(Ue),Ue=void 0;try{Promise.resolve(MA()).catch(()=>{})}catch{}}if(Ae){let $=Date.now(),re=1440*60*1e3;$-or>=re&&(or=$,to())}}),V(()=>{!n.msgRetryCounterCache&&ae.close&&ae.close(),!n.callOfferCache&&De.close&&De.close(),oe.close(),Se=!1});async function to(){try{await ke;let Ae=await Xb(I.keys),W=new Set(Ce);for(let he of Ae)W.add(he);if(!W.size)return;let $=[...W],re=await I.keys.get("tctoken",$),se={},we=new Set,Ee=0;for(let he of $){let ye=re[he];if(!ye){Ee++;continue}let qe=!!ye.token?.length,IA=qe&&Ed(ye.timestamp),yA=ye.senderTimestamp!==void 0,$A=yA&&Ed(ye.senderTimestamp),vA=qe&&!IA,YA=yA&&!$A;!vA&&!YA?(se[he]=null,Ee++):IA&&YA?(se[he]={token:Buffer.alloc(0),senderTimestamp:ye.senderTimestamp},we.add(he),Ee++):we.add(he)}if(Ee===0)return;await I.keys.set({tctoken:{...se,[_I]:{token:Buffer.from(JSON.stringify([...we]))}}}),Ce.clear();for(let he of we)Ce.add(he);t.debug({mutated:Ee,remaining:we.size},"pruned expired tctokens")}catch(Ae){t.warn({err:Ae?.message},"failed to prune expired tctokens")}}return{...r,sendMessageAck:Ie,sendRetryRequest:je,rejectCall:Xe,fetchMessageHistory:Be,requestPlaceholderResend:Re,messageRetryManager:G}};var qIe=n=>{let t=JIe(n),{authState:o,query:i,waUploadToServer:e}=t,a=async f=>{let Q=[],y=["address","email","description"];return Q.push(...y.filter(T=>f[T]!==void 0&&f[T]!==null).map(T=>({tag:T,attrs:{},content:f[T]}))),f.websites!==void 0&&Q.push(...f.websites.map(T=>({tag:"website",attrs:{},content:T}))),f.hours!==void 0&&Q.push({tag:"business_hours",attrs:{timezone:f.hours.timezone},content:f.hours.days.map(T=>{let _={tag:"business_hours_config",attrs:{day_of_week:T.day,mode:T.mode}};return T.mode==="specific_hours"?{..._,attrs:{..._.attrs,open_time:T.openTimeInMinutes,close_time:T.closeTimeInMinutes}}:_})}),await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:Q}]})},A=async f=>{let{fileSha256:Q,filePath:y}=await Lb(f,"biz-cover-photo"),m=Q.toString("base64"),{meta_hmac:T,fbid:_,ts:R}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(_),op:"update",token:T,ts:String(R)}}]}]}),_},r=async f=>await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:f}}]}]}),s=async({jid:f,limit:Q,cursor:y})=>{f=f||o.creds.me?.id,f=CA(f);let m=[{tag:"limit",attrs:{},content:Buffer.from((Q||10).toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}];y&&m.push({tag:"after",attrs:{},content:y});let T=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:f,allow_shop_source:"true"},content:m}]});return DIe(T)},g=async(f,Q=51)=>{f=f||o.creds.me?.id,f=CA(f);let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:f},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return OIe(y)},c=async(f,Q)=>{let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:f},content:[{tag:"image_dimensions",attrs:{},content:[{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]},{tag:"token",attrs:{},content:Buffer.from(Q)}]}]});return bIe(y)},I=async(f,Q)=>{Q=await SK(Q,e);let y=mK(f,Q),m=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_edit",attrs:{v:"1"},content:[y,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),T=le(m,"product_catalog_edit"),_=le(T,"product");return nQ(_)},d=async f=>{f.isHidden=!!f.isHidden,f=await SK(f,e);let Q=mK(void 0,f),y=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[Q,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=le(y,"product_catalog_add"),T=le(m,"product");return nQ(T)},B=async f=>{let Q=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:f.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(le(Q,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...t,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:d,productDelete:B,productUpdate:I,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:r}};var zIe=n=>{let t=qIe(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(I,d,B)=>e({tag:"iq",attrs:{type:d,xmlns:"w:g2",to:I},content:B}),r=async I=>{let d=await A(I,"get",[{tag:"query",attrs:{request:"interactive"}}]);return TK(d)},s=async()=>{let I=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),d={},B=le(I,"communities");if(B){let f=PA(B,"community");for(let Q of f){let y=TK({tag:"result",attrs:{},content:[Q]});d[y.id]=y}}return t.ev.emit("groups.update",Object.values(d)),d};async function g(I){aQ.info({node:I},"parseGroupResult");let d=le(I,"group");if(d)try{aQ.info({groupNode:d},"groupNode");let B=await t.groupMetadata(`${d.attrs.id}@g.us`);return B||c.empty()}catch(B){return console.error("Error parsing group metadata:",B),c.empty()}return c.empty()}let c={empty:()=>null,of:I=>I!==null?{value:I}:null};return t.ws.on("CB:ib,,dirty",async I=>{let{attrs:d}=le(I,"dirty");d.type==="communities"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,communityMetadata:r,communityCreate:async(I,d)=>{let B=ML().substring(0,12),f=await A("@g.us","set",[{tag:"create",attrs:{subject:I},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(d||"","utf-8")}]},{tag:"parent",attrs:{default_membership_approval_mode:"request_required"}},{tag:"allow_non_admin_sub_group_creation",attrs:{}},{tag:"create_general_chat",attrs:{}}]}]);return await g(f)},communityCreateGroup:async(I,d,B)=>{let f=zr(),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:I,key:f},content:[...d.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(Q)},communityLeave:async I=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:I}}]}])},communityUpdateSubject:async(I,d)=>{await A(I,"set",[{tag:"subject",attrs:{},content:Buffer.from(d,"utf-8")}])},communityLinkGroup:async(I,d)=>{await A(d,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}]}])},communityUnlinkGroup:async(I,d)=>{await A(d,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}])},communityFetchLinkedGroups:async I=>{let d=I,B=!1,f=await t.groupMetadata(I);f.linkedParent?d=f.linkedParent:B=!0;let Q=await A(d,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=le(Q,"sub_groups");if(m){let T=PA(m,"group");for(let _ of T)y.push({id:_.attrs.id?Sr(_.attrs.id,"g.us"):void 0,subject:_.attrs.subject||"",creation:_.attrs.creation?Number(_.attrs.creation):void 0,owner:_.attrs.creator?CA(_.attrs.creator):void 0,size:_.attrs.size?Number(_.attrs.size):void 0})}return{communityJid:d,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async I=>{let d=await A(I,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=le(d,"membership_approval_requests");return PA(B,"membership_approval_request").map(Q=>Q.attrs)},communityRequestParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:d.map(T=>({tag:"participant",attrs:{jid:T}}))}]}]),Q=le(f,"membership_requests_action"),y=le(Q,B);return PA(y,"participant").map(T=>({status:T.attrs.error||"200",jid:T.attrs.jid}))},communityParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:d.map(m=>({tag:"participant",attrs:{jid:m}}))}]),Q=le(f,B);return PA(Q,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(I,d)=>{let f=(await r(I)).descId??null;await A(I,"set",[{tag:"description",attrs:{...d?{id:ML()}:{delete:"true"},...f?{prev:f}:{}},content:d?[{tag:"body",attrs:{},content:Buffer.from(d,"utf-8")}]:void 0}])},communityInviteCode:async I=>{let d=await A(I,"get",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityRevokeInvite:async I=>{let d=await A(I,"set",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityAcceptInvite:async I=>{let d=await A("@g.us","set",[{tag:"invite",attrs:{code:I}}]);return le(d,"community")?.attrs.jid},communityRevokeInviteV4:async(I,d)=>!!await A(I,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:d}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(I,d)=>{I=typeof I=="string"?{remoteJid:I}:I;let B=await A(d.groupJid,"set",[{tag:"accept",attrs:{code:d.inviteCode,expiration:d.inviteExpiration.toString(),admin:I.remoteJid}}]);return I.id&&(d=ne.Message.GroupInviteMessage.fromObject(d),d.inviteExpiration=0,d.inviteCode="",i.emit("messages.update",[{key:I,update:{message:{groupInviteMessage:d}}}])),await a({key:{remoteJid:d.groupJid,id:zr(t.user?.id),fromMe:!1,participant:I.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:I.remoteJid,messageTimestamp:va()},"notify"),B.attrs.from}),communityGetInviteInfo:async I=>{let d=await A("@g.us","get",[{tag:"invite",attrs:{code:I}}]);return TK(d)},communityToggleEphemeral:async(I,d)=>{let B=d?{tag:"ephemeral",attrs:{expiration:d.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(I,"set",[B])},communitySettingUpdate:async(I,d)=>{await A(I,"set",[{tag:d,attrs:{}}])},communityMemberAddMode:async(I,d)=>{await A(I,"set",[{tag:"member_add_mode",attrs:{},content:d}])},communityJoinApprovalMode:async(I,d)=>{await A(I,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:d}}]}])},communityFetchAllParticipating:s}},TK=n=>{let t=le(n,"community"),o=le(t,"description"),i,e;o&&(i=jA(o,"body"),e=o.attrs.id);let a=t.attrs.id?.includes("@")?t.attrs.id:Sr(t.attrs.id||"","g.us"),A=le(t,"ephemeral")?.attrs.expiration,r=jA(t,"member_add_mode")==="all_member_add";return{id:a,subject:t.attrs.subject||"",subjectOwner:t.attrs.s_o,subjectTime:Number(t.attrs.s_t||0),size:PA(t,"participant").length,creation:Number(t.attrs.creation||0),owner:t.attrs.creator?CA(t.attrs.creator):void 0,desc:i,descId:e,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_community"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:r,participants:PA(t,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:jA(t,"addressing_mode")}};var bXe=n=>{let t={...QIe,...n};return zIe(t)},VIe=bXe;var WIe=VIe;var MXe=Object.freeze({key:"whatsapp",label:"WhatsApp",get connectionLabel(){return w(" Web \u5173\u8054\u8BBE\u5907")},reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),UM=class extends ps{constructor(t){super({...t,descriptor:MXe})}};import{chmod as ZIe,mkdir as _Xe,readdir as TXe}from"node:fs/promises";var NXe=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),RXe=6e4;function XIe(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function kXe(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function vXe(n){let t=n;if(typeof t=="string"){if(!/^\d+$/.test(t))return null;t=Number(t)}else typeof t=="bigint"?t=Number(t):t&&typeof t=="object"&&(t=Number(t.valueOf()));return Number.isFinite(t)&&t>=0?t*1e3:null}async function NK(n){await _Xe(n,{recursive:!0,mode:448}),await ZIe(n,448);let t=await TXe(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(t.filter(o=>o.isFile()).map(o=>ZIe(`${n}/${o.name}`,384).catch(()=>{})))}function PXe(n,t){let o=n.user??t.creds.me,i=CA(o?.id);if(!/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i??""))throw new Error("WhatsApp did not return a valid linked account");return{accountJid:i,name:typeof o?.name=="string"&&o.name.trim()?o.name.trim().slice(0,100):w("WhatsApp\u673A\u5668\u4EBA")}}async function HM({authDir:n,onQr:t,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=WIe,loadAuthState:r=zse}={}){if(!n||typeof t!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await NK(n);let s=Date.now(),{state:g,saveCreds:c}=await r(n),I=g.keys.set.bind(g.keys);g.keys.set=async z=>{await I(z),await NK(n)};let d=!1,B=!1,f,Q,y=Promise.resolve(),m=null,T=0,_=null,R=new Promise((z,K)=>{f=z,Q=K}),H=z=>{B||(B=!0,Q(z))},F=async()=>{d||(d=!0,T+=1,H(XIe()),await _?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},L=async()=>{d||(d=!0,T+=1,H(XIe()),await _?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let z=++T,K=!1,G=A({auth:g,browser:AM.macOS("DeepSeek Harness"),logger:NXe,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=G;let V=()=>{!K||!g.creds.me||B||y.then(()=>{d||B||z!==T||!K||!g.creds.me||(B=!0,f(PXe(G,g)))}).catch(U=>H(U))};G.ev.on("creds.update",()=>{d||z!==T||(y=y.then(async()=>{await c(),await NK(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),V())}),G.ev.on("connection.update",U=>{if(!(d||z!==T)&&(typeof U.qr=="string"&&U.qr&&t(U.qr),U.connection==="open"&&(K=!0,V()),U.connection==="close")){let N=kXe(U.lastDisconnect?.error);if(N===tr.restartRequired){_??=y.then(async()=>{d||z!==T||(await G.end(void 0).catch(()=>{}),!(d||z!==T)&&q())}).catch(X=>H(X)).finally(()=>{_=null});return}let k=N===tr.loggedOut,J=Object.assign(new Error(k?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:k?"logged-out":"connection-closed"});B?i?.({error:J,loggedOut:k}):H(J)}}),G.ev.on("messages.upsert",({messages:U,type:N})=>{if(!(d||z!==T||N!=="notify"&&N!=="append"||typeof o!="function"))for(let k of Array.isArray(U)?U:[]){if(N==="append"){let J=vXe(k?.messageTimestamp);if(J===null||J{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await F():e.addEventListener("abort",()=>void F(),{once:!0})),Object.freeze({get socket(){return m},ready:R,close:F,logout:L})}var kK=new Set(["image/jpeg","image/png","image/webp","image/gif"]),FXe=5*1024*1024,RK=15e3,vK=12e4,LXe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],UXe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]),HXe=new Set(["s.whatsapp.net","c.us","lid","hosted","hosted.lid"]);function ele(n){if(typeof n!="string")return null;let t=n.trim();if(/^\+?\d+$/.test(t))return`${t.replace(/^\+/,"")}@s.whatsapp.net`;let o=fA(t);return!o||!/^\d+$/.test(o.user)||!HXe.has(o.server)?null:t}function FK(n,t){let o=ele(n),i=ele(t);if(!o||!i)return!1;try{return kt(o,i)===!0}catch{return!1}}function KXe(n){let t=n;for(let o=0;o<5&&t&&typeof t=="object";o+=1){let i=LXe.find(e=>t[e]?.message);if(!i)return!1;if(UXe.has(i))return!0;t=t[i].message}return!1}function xXe(n){return n?.extendedTextMessage?.contextInfo??n?.imageMessage?.contextInfo??n?.videoMessage?.contextInfo??n?.documentMessage?.contextInfo??null}function tle(n){return n?.conversation??n?.extendedTextMessage?.text??n?.imageMessage?.caption??n?.videoMessage?.caption??n?.documentMessage?.caption??""}function cQ(n,t,o){if(!t||typeof t!="object")return null;let i=typeof t.fileName=="string"&&t.fileName?t.fileName:typeof o=="string"&&o?o:void 0;return{kind:n,...i?{name:i}:{}}}function YXe(n){let t=[];if(n?.imageMessage&&t.push(cQ("image",n.imageMessage)),n?.documentMessage){let o=typeof n.documentMessage.mimetype=="string"?n.documentMessage.mimetype.toLowerCase():"";t.push(cQ(o.startsWith("image/")?"image":"file",n.documentMessage))}if(n?.audioMessage&&t.push(cQ("audio",n.audioMessage)),n?.videoMessage&&t.push(cQ("video",n.videoMessage)),n?.stickerMessage){let o=typeof n.stickerMessage.mimetype=="string"?n.stickerMessage.mimetype.toLowerCase():"";t.push(cQ(o.startsWith("video/")||n.stickerMessage.isAnimated===!0?"video":"image",n.stickerMessage))}return t.filter(Boolean)}function jXe(n){if(!n?.quotedMessage||typeof n.quotedMessage!="object")return;let t=ya(n.quotedMessage),o=typeof n.stanzaId=="string"&&n.stanzaId?n.stanzaId:void 0,i=typeof n.participant=="string"&&n.participant?n.participant:void 0;return{...o?{messageId:o}:{},...i?{authorId:i}:{},content:tle(t),attachments:YXe(t)}}function rle(n){if(Number.isSafeInteger(n)&&n>=0)return n;let t;try{t=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(t)&&t>=0?t:void 0}async function JXe(n,t,{signal:o,maxBytes:i=FXe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(RK),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>t(n,"stream",{options:{signal:a}})),r=await new Promise((I,d)=>{let B=!1,f=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",Q),y(m),!0),Q=()=>f(d,a.reason);a.addEventListener("abort",Q,{once:!0}),A.then(y=>{f(I,y)||y?.destroy?.()},y=>f(d,y)),a.aborted&&Q()}).catch(I=>{throw o?.aborted?o.reason??I:e.aborted?new ft("image-download-failed",`WhatsApp image download timed out after ${RK} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}),s=[],g=0,c=()=>r?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let I of r){a.throwIfAborted();let d=Buffer.from(I);if(g+=d.length,g>i)throw r.destroy?.(),new ft("image-too-large",`WhatsApp image exceeded ${i} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));s.push(d)}}catch(I){throw o?.aborted?o.reason??I:e.aborted?new ft("image-download-failed",`WhatsApp image stream timed out after ${RK} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function qXe(n,t,o,{viewOnce:i=!1}={}){let e,a;if(!i&&t?.imageMessage&&t.imageMessage.viewOnce!==!0)e=t.imageMessage;else if(t?.documentMessage){let r=typeof t.documentMessage.mimetype=="string"?t.documentMessage.mimetype.toLowerCase():"";if(!kK.has(r))return null;e=t.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return kK.has(A)?{name:a,mediaType:A,size:rle(e.fileLength),load:r=>JXe(n,o,r)}:null}function zXe(n,t,o){let i=t?.documentMessage;if(!i)return null;let e=typeof i.mimetype=="string"&&i.mimetype?i.mimetype.toLowerCase():void 0;return kK.has(e)?null:{name:typeof i.fileName=="string"&&i.fileName?i.fileName:"whatsapp-file",...e?{mediaType:e}:{},size:rle(i.fileLength),async load({signal:a}={}){a?.throwIfAborted();let A=await o(n,"stream",{options:{signal:a}});return a?.throwIfAborted(),{stream:A}}}}function VXe({socket:n,logger:t=console,download:o=WU}={}){if(typeof o!="function")throw new TypeError("WhatsApp media downloader is required");return typeof n?.updateMediaMessage!="function"?o:(i,e,a)=>o(i,e,a,{logger:t,reuploadRequest:A=>n.updateMediaMessage(A)})}function WXe(n,t,{download:o=WU}={}){let i=typeof n?.key?.remoteJid=="string"?n.key.remoteJid:"",e=typeof n?.key?.remoteJidAlt=="string"?n.key.remoteJidAlt:"",a=typeof n?.key?.id=="string"?n.key.id:"";if(!i||!a||i==="status@broadcast"||i.endsWith("@newsletter"))return null;let A=i.endsWith("@g.us"),r=n.key.fromMe===!0,s=r&&!A&&[i,e].some(_=>_&&kt(_,t));if(r&&!s&&!A)return null;let g=r?t:A?n.key.participant:i,c=A&&!r?n.key.participantAlt:e;if(typeof g!="string"||!g)return null;let I=KXe(n.message),d=ya(n.message),B=xXe(d),f=Array.isArray(B?.mentionedJid)&&B.mentionedJid.some(_=>kt(_,t)),Q=typeof B?.participant=="string"&&kt(B.participant,t),y=qXe(n,d,o,{viewOnce:I}),m=zXe(n,d,o),T=jXe(B);return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,contextSource:()=>({senderName:n.pushName}),senderAlternateId:typeof c=="string"?c:"",senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:tle(d),plainText:typeof d?.conversation=="string"||typeof d?.extendedTextMessage?.text=="string",images:y?[y]:[],files:m?[m]:[],...T?{replyTo:T}:{},addressed:!A||r||f||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s},reactionTarget:{jid:i,key:n.key}}}var PK=class{#e=new Map;has(t){return this.#t(),this.#e.has(t)}remember(t){this.#A(t)}reserve(t){this.#A(t)}#A(t){if(!(typeof t!="string"||!t))for(this.#t(),this.#e.set(t,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#t(){let t=Date.now();for(let[o,i]of this.#e)i>t||this.#e.delete(o)}};function ale(n){return n?.reason??new DOMException("The operation was aborted.","AbortError")}function Ale(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,ale(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function ZXe(n){if(n?.code==="artifact-delivery-uncertain")return n;let t=new Error("WhatsApp could not confirm artifact delivery.");return t.code="artifact-delivery-uncertain",t.cause=n,t}function XXe(n){if(n?.code?.startsWith?.("artifact-"))return n;let t=n?.output?.statusCode??n?.data?.statusCode??n?.statusCode,o;if(t===401||t===403?o="artifact-permission-required":t===413?o="artifact-too-large":t===429?o="artifact-rate-limited":[400,404,405,406,410,415,422].includes(t)&&(o="artifact-provider-rejected"),!o)return ZXe(n);let i=new Error("WhatsApp rejected artifact delivery.");return i.code=o,i.cause=n,i}var GK=class{#e;#A;#t;#r;#l=new Map;constructor(t,o,{signal:i,mediaUploadTimeoutMs:e=vK}={}){this.#e=t,this.#A=o,this.#t=i,this.#r=e}async sendText(t,o){await this.#a(t.jid);let i=[];for(let[e,a]of hs(o,4e3).entries()){let A=$Ie(10).toString("hex").toUpperCase(),r={...e===0&&t.quoted?{quoted:t.quoted}:{},messageId:A};typeof this.#A.reserve=="function"?this.#A.reserve(A):this.#A.remember(A);let s=await this.#e.sendMessage(t.jid,{text:a},r);this.#A.remember(s?.key?.id),typeof s?.key?.id=="string"&&s.key.id&&i.push(s.key.id)}return{providerMessageIds:i}}async sendFile(t,o){return this.#i(t,o,{document:o.bytes,mimetype:o.mediaType??"application/octet-stream",fileName:o.fileName},"file")}async sendImage(t,o){return this.#i(t,o,{image:o.bytes,mimetype:o.mediaType??"image/jpeg"},"image")}async addReaction(t,o,{signal:i}={}){if(typeof o!="string"||!o.trim())throw new TypeError("A WhatsApp reaction emoji is required");let e=o.trim();return await this.#o(t,e,i),e}removeReaction(t,o,{signal:i}={}){return this.#o(t,"",i)}async#o(t,o,i){if(typeof t?.jid!="string"||!t.jid||!t.key?.id)throw new TypeError("A WhatsApp reaction target is required");let e=i??this.#t;e?.throwIfAborted();let a=$Ie(10).toString("hex").toUpperCase();typeof this.#A.reserve=="function"?this.#A.reserve(a):this.#A.remember(a);let A=this.#e.sendMessage(t.jid,{react:{text:o,key:t.key}},{messageId:a}),r=await Ale(A,e);return this.#A.remember(r?.key?.id),r}async#i(t,o,i,e){this.#t?.throwIfAborted(),await this.#a(t.jid),this.#t?.throwIfAborted();let a=typeof o.deliveryKey=="string"&&o.deliveryKey?o.deliveryKey:o.artifactId,A=e==="image"?`${a}:image`:a,r=typeof A=="string"&&A?GXe("sha256").update(A).digest("hex").slice(0,20).toUpperCase():void 0,s={...t.quoted?{quoted:t.quoted}:{},...r?{messageId:r}:{},mediaUploadTimeoutMs:this.#r};this.#A.remember(r);let g;try{let c=this.#e.sendMessage(t.jid,i,s);mn(o,c);let I=AbortSignal.timeout(this.#r),d=this.#t?AbortSignal.any([this.#t,I]):I;g=await Ale(c,d)}catch(c){throw this.#t?.aborted?ale(this.#t):XXe(c)}return this.#t?.throwIfAborted(),this.#A.remember(g?.key?.id),g}async sendTyping(t){!t.selfChat&&t.quoted?.key&&await this.#e.readMessages([t.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",t.jid),await this.#a(t.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",t.jid).catch(()=>{this.#a(t.jid)})},2e4);o.unref?.(),this.#l.set(t.jid,o)}async close(){let t=[...this.#l.keys()];await Promise.allSettled(t.map(o=>this.#a(o)))}async#a(t,o=!0){let i=this.#l.get(t);i&&clearInterval(i),this.#l.delete(t),o&&await this.#e.sendPresenceUpdate("paused",t).catch(()=>{})}};function $Xe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...so()}}var IQ=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c=$Xe();#g=null;#I=null;#p=null;#E=null;#u=null;constructor({config:t,authDir:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,logger:r=console,replyTimeoutMs:s=6e5,connectTimeoutMs:g=3e4,mediaUploadTimeoutMs:c=vK,createSession:I=HM}){if(!t||!o||!i||!e||typeof I!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");if(this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,!Number.isSafeInteger(c)||c<=0)throw new TypeError("mediaUploadTimeoutMs must be a positive safe integer");this.#s=Math.min(c,vK),this.#d=I}get status(){return structuredClone(this.#c)}async start(){return this.#c.ready&&this.#I?this.status:this.#u?this.#u:(this.#u=this.#C().finally(()=>{this.#u=null}),this.#u)}async#C(){await this.stop(),this.#c.startedAt=new Date().toISOString(),this.#c.connectionState="connecting",this.#c.lastError=null,await this.#t.ensureRunning(),this.#c.harnessReachable=!0;let t=new AbortController;this.#g=t;let o=new PK,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#d({authDir:this.#A,signal:t.signal,logger:this.#i,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async(c,I)=>{let d=WXe(c,this.#e.accountJid,{download:VXe({socket:I?.socket,logger:this.#i})});!d||o.has(d.providerMessageId)||!this.#E||(this.#c.lastCheckedAt=Date.now(),await this.#E.accept(d))},onDisconnect:({error:c})=>{t.signal.aborted||(this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=c?.message??"WhatsApp Web connection closed")}});this.#I=a;let A,r=await Promise.race([a.ready,e,new Promise((c,I)=>{A=setTimeout(()=>I(new Error("WhatsApp Web did not connect in time")),this.#n)})]).finally(()=>clearTimeout(A));if(!kt(r.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new GK(a.socket,o,{signal:t.signal,mediaUploadTimeoutMs:this.#s});this.#p=s,this.#E=new UM({bot:s,harness:this.#t,state:this.#r,contextEnhancement:this.#l,accessPolicy:this.#o?{botId:this.#o.botId,getSettings:(...c)=>this.#o.getSettings(...c),...typeof this.#o.isPrivileged=="function"?{isPrivileged:(...c)=>this.#o.isPrivileged(...c)}:{},equals:FK}:void 0,status:this.#c,logger:this.#i,replyTimeoutMs:this.#a,signal:t.signal});let g=Date.now();return this.#c.ready=!0,this.#c.connectionState="connected",this.#c.lastCheckedAt=g,this.#c.lastConnectedAt=g,this.status}catch(a){throw this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#I?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(t){if(!this.#c.ready||!this.#p){let o=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw o.code="test-target-unavailable",o}if(typeof t!="string"||!t.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#p.sendText({jid:this.#e.accountJid,selfChat:!0},t),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.jid=="string"?t.route.jid.trim():"",a=t?.kind==="user"&&/^[^@\s]+@(s\.whatsapp\.net|lid)$/.test(e),A=t?.kind==="group"&&/^[^@\s]+@g\.us$/.test(e);if(!a&&!A){let r=new TypeError("Invalid WhatsApp proactive delivery target");throw r.code="invalid-target",r}if(!this.#c.ready||!this.#p){let r=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return i?.throwIfAborted(),this.#p.sendText({jid:e},o)}async stop(){let t=this.#I,o=this.#p,i=this.#E;return this.#g?.abort(),this.#g=null,this.#I=null,this.#p=null,this.#E=null,await o?.close().catch(()=>{}),await t?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#c.ready=!1,this.#c.connectionState="idle",this.status}};var r7e=/^[a-f0-9-]{36}$/;function a7e(n){let t=cc(n.dshHome??process.env.DSH_HOME??LE(t7e(),".dsh")),o=cc(n.dataDir??LE(t,"integrations","dsh-whatsapp")),i=cc(n.authDir??LE(o,"auth")),e=a=>{if(!r7e.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return cc(i,a)};return{config:cc(n.configPath??LE(o,"config.json")),bots:cc(n.botsDir??LE(o,"bots")),workspaces:cc(n.workspacesPath??LE(o,"workspaces.json")),authPath:e}}async function LK(n,t={},o={}){let i=na(n,t),e=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,a=()=>xa(n),A=o.ConfigStore??AD,r=o.StateStore??aD,s=o.HarnessClient??rD,g=o.Controller??DB,c=o.Runtime??IQ,I=o.createSession??HM,d=o.createConnectionSupervisor??ep,B=a7e(t),f=await new A(B.config).load(),Q=cc(t.workspace??process.cwd()),y=o.WorkspaceStore??oa,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),T=f.list();await m.reconcile(T.map(k=>k.botId)),await Promise.all(T.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("whatsapp",k)})));let _=typeof f.remove=="function"?Ya(f,{workspaces:m}):f,R=new Map,H=k=>cc(B.bots,k,"state.json"),F=async k=>{let J=R.get(k);return J||(J=await new r(H(k)).load(),R.set(k,J)),J},L=za(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:z,fileIngressExecutor:K}=Va(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),G=new s({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...L?{commandExecutor:L}:{},...q?{controlExecutor:q}:{},...z?{sessionMaintenanceExecutor:z}:{},...K?{fileIngressExecutor:K}:{}}),V=new g({configStore:_,authPath:B.authPath,createSession:I,logger:e,createRuntime:async({botId:k,config:J,authDir:X})=>{let ae=await F(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("whatsapp",J)});let De=ja(G,{botId:k,workspaces:m,state:ae,agentPresetCatalog:a});return new c({config:J,authDir:X,harness:De.harness,state:De.state,contextEnhancement:{botId:k,getSettings:()=>m.contextEnhancementFor(k)},accessPolicy:Wa(m,k,{channel:"whatsapp",config:J,equals:FK}),replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??3e4,createSession:I,logger:{error:(...oe)=>e.error?.(`[${k}]`,...oe),warn:(...oe)=>e.warn?.(`[${k}]`,...oe),info:(...oe)=>e.info?.(`[${k}]`,...oe),debug:(...oe)=>e.debug?.(`[${k}]`,...oe)}})},deleteAuth:k=>e7e(B.authPath(k),{recursive:!0,force:!0}),deleteState:async({botId:k})=>{let J=R.get(k);if(R.delete(k),J&&typeof J.remove=="function")await J.remove();else try{await A7e(H(k))}catch(X){if(X?.code!=="ENOENT")throw X}}}),U=Ja(V,{workspaces:m,stateFor:F,agentPresetCatalog:a}),N=d({channel:"whatsapp",controller:U,harness:G,logger:e,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:U,deliveryAdapter:qa({channel:"whatsapp",workspaces:m,coreController:V,stateFor:F}),ready:N.ready,async close(){await N.close(),await U.close(),G.stopManagedProcess()}}}import i7e from"qrcode";var ile="/whatsapp",_r=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setAccessPolicy:Xa,setWorkspace:Gi,setAgentPreset:Fi,setContextEnhancement:Pi}),ole=Object.freeze(Object.values(_r)),o7e=new Set(["qrValue","accountJid","authDirectory"]);function KK(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function KM(n,t){return KK(n)&&Object.keys(n).every(o=>t.includes(o))}function UK(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function n7e(n,t){return KK(t)?[_r.status,_r.beginProvisioning].includes(n)?KM(t,[])?null:`${n} does not accept fields.`:[_r.pollProvisioning,_r.cancelProvisioning].includes(n)?KM(t,["attemptId"])&&UK(t.attemptId)?null:`${n} requires an attemptId.`:n===_r.reconnectBot?KM(t,["botId","sendTest"])&&UK(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.":n===_r.deleteBot?KM(t,["botId","confirm"])&&UK(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===_r.setAccessPolicy?$a(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u8BBF\u95EE\u8BBE\u7F6E\u3002":n===_r.setWorkspace?ei(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===_r.setAgentPreset?ti(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===_r.setContextEnhancement?Za(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown WhatsApp endpoint.":"Payload must be an object."}function UE(n){if(Array.isArray(n))return n.map(UE);if(!KK(n))return n;let t={};for(let[o,i]of Object.entries(n))o7e.has(o)||(t[o]=UE(i));return t}async function s7e(n){return i7e.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function HK(n,t){return!n||typeof n.qrValue!="string"?UE(n):UE({...n,qrCodeDataUrl:await t(n.qrValue)})}async function Dd(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await HK(o.provisioning,t)),UE(o)}function nle(n,{encodeQr:t=s7e}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete WhatsApp controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!ole.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let r=n7e(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===_r.status)s=await Dd(await n.status(),i);else if(e===_r.beginProvisioning)s=await HK(await n.startProvisioning(),i);else if(e===_r.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await HK(g,i)}else if(e===_r.cancelProvisioning)s=UE(await n.cancelProvisioning(a.attemptId));else if(e===_r.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(s=await Dd(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(d=>d?.botId===a.botId&&d.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let d=new Error("Connection test is unavailable");throw d.code="test-target-unavailable",d}await n.sendConnectionTest(a.botId)}catch(d){c=d}s={...s,testMessage:gr(c)}}}else if(e===_r.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Dd(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===_r.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>Dd(g,i))}else if(e===_r.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Dd(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else if(e===_r.setAccessPolicy){if(typeof n.updateAccessPolicy!="function")throw new Error("Access policy update is unavailable");s=await n.updateAccessPolicy(a.botId,a.policy,g=>Dd(g,i))}else s=await Dd(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ai(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"whatsapp-operation-failed",message:"WhatsApp \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function xM(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(ile,nle(t,o),{authority:yr(i)})}async function sle(n,t={}){if(t?.controller)return xM(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await LK(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=xM(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close WhatsApp Web connections"),e}var g7e="/dsh-im-delivery",c7e="DSH-IM \u4E3B\u52A8\u6295\u9012\u6D4B\u8BD5\u6210\u529F\u3002",wi=Object.freeze({send:"message.send",listTargets:"target.list",listSuggestions:"target.suggestion.list",createTarget:"target.create",updateTarget:"target.update",deleteTarget:"target.delete",testTarget:"target.test"}),I7e=new Set(Object.values(wi)),l7e=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function dQ(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function RI(n,t){return dQ(n)&&Object.keys(n).length===t.length&&Object.keys(n).every(o=>t.includes(o))}function Od(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function lQ(n){return typeof n=="string"&&/^[A-Za-z0-9._:@-]{1,128}$/.test(n)}function gle(n,{targetId:t}){let o=t?["targetId","name","kind","route"]:["name","kind","route"];return!dQ(n)||Object.keys(n).some(i=>!o.includes(i))||t&&!lQ(n.targetId)||n.name!==void 0&&(typeof n.name!="string"||!n.name.trim()||n.name.trim().length>80)?!1:typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&dQ(n.route)}function d7e(n){return RI(n,["kind","route"])&&typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&dQ(n.route)}function p7e(n,t){return!I7e.has(n)||!dQ(t)?!1:n===wi.send?RI(t,["botId","targetId","text"])&&Od(t.botId)&&lQ(t.targetId)&&typeof t.text=="string"&&!!t.text.trim():n===wi.listTargets||n===wi.listSuggestions?RI(t,["botId"])&&Od(t.botId):n===wi.createTarget?RI(t,["botId","target"])&&Od(t.botId)&&gle(t.target,{targetId:!0}):n===wi.updateTarget?RI(t,["botId","targetId","target"])&&Od(t.botId)&&lQ(t.targetId)&&gle(t.target,{targetId:!1}):n===wi.testTarget?RI(t,["botId","targetId"])&&Od(t.botId)&&lQ(t.targetId)||RI(t,["botId","target"])&&Od(t.botId)&&d7e(t.target):RI(t,["botId","targetId"])&&Od(t.botId)&&lQ(t.targetId)}function h7e(n){let t=l7e.has(n?.code)?n.code:"delivery-failed";return{code:t,message:t,details:{}}}function xK(n){for(let t of["send","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget"])if(typeof n?.[t]!="function")throw new TypeError(`A complete delivery service is required (${t})`);return async(t,o,i)=>{if(!p7e(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid delivery request.",details:{}}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"cancelled",details:{}}};try{let e;return t===wi.send?e=await n.send(o.botId,o.targetId,o.text,{signal:i}):t===wi.listTargets?e=await n.listTargets(o.botId):t===wi.listSuggestions?e=await n.listSuggestions(o.botId):t===wi.createTarget?e=await n.createTarget(o.botId,o.target):t===wi.updateTarget?e=await n.updateTarget(o.botId,o.targetId,o.target):t===wi.deleteTarget?e=await n.deleteTarget(o.botId,o.targetId):e=await n.send(o.botId,Object.hasOwn(o,"target")?o.target:o.targetId,c7e,{signal:i}),{ok:!0,value:e}}catch(e){return{ok:!1,error:h7e(e)}}}}function cle(n,t,{authority:o}={}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(g7e,xK(t),{authority:yr(o)})}var Ile="/api/dsh-im/delivery/messages",lle=1024*1024,E7e=Object.freeze({"bad-request":400,"unknown-bot":404,"unknown-target":404,"target-conflict":409,"invalid-target":422,"bot-not-connected":503,"target-rejected":422,"delivery-failed":502,cancelled:408}),KE=class extends Error{constructor(t,o){super(o),this.status=t,this.code=o}};function HE(n,t,o,i={}){if(n.destroyed||n.writableEnded)return;let e=JSON.stringify(o);n.writeHead(t,{"cache-control":"no-store","content-type":"application/json; charset=utf-8","content-length":String(Buffer.byteLength(e)),...i}),n.end(e)}function u7e(n){return typeof n=="string"&&n.split(";",1)[0].trim().toLowerCase()==="application/json"}async function C7e(n){let t=Number(n.headers["content-length"]);if(Number.isFinite(t)&&t>lle)throw new KE(413,"payload-too-large");let o=[],i=0;for await(let e of n){let a=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=a.length,i>lle)throw new KE(413,"payload-too-large");o.push(a)}try{return JSON.parse(Buffer.concat(o,i).toString("utf8"))}catch{throw new KE(400,"bad-request")}}function B7e(n){let t=xK(n);return async(o,i)=>{if(o.method!=="POST"){HE(i,405,{error:{code:"method-not-allowed",message:"method-not-allowed",details:{}}},{allow:"POST"});return}if(!u7e(o.headers["content-type"])){HE(i,415,{error:{code:"unsupported-media-type",message:"unsupported-media-type",details:{}}});return}let e=new AbortController,a=()=>e.abort(),A=()=>{i.writableEnded||a()};o.once("aborted",a),i.once("close",A);try{let r=await C7e(o),s=await t(wi.send,r,e.signal);if(s.ok){HE(i,200,s.value);return}HE(i,E7e[s.error.code]??500,{error:s.error})}catch(r){if(r instanceof KE){HE(i,r.status,{error:{code:r.code,message:r.code,details:{}}});return}HE(i,500,{error:{code:"delivery-failed",message:"delivery-failed",details:{}}})}finally{o.off("aborted",a),i.off("close",A)}}}function dle(n,t){if(!n?.webServer||typeof n.webServer.register!="function"||typeof n.effect!="function")throw new TypeError("DSH Host WebServer is required");let o={kind:"exact",path:Ile,handler:B7e(t)};return n.effect(()=>n.webServer.register(o),`dsh-im: ${Ile}`)}var f7e=/^[A-Za-z0-9_-]{1,128}$/,Q7e=/^[A-Za-z0-9._:@-]{1,128}$/,y7e=/^[a-z][a-z0-9-]{0,31}$/,m7e="__test__",S7e=Object.freeze(["ownsBot","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget","sendText"]),w7e=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function un(n,t=n,o){let i=new Error(t,o);return i.code=n,i}function xE(n){if(typeof n!="string"||!f7e.test(n))throw un("bad-request","Invalid bot id");return n}function YM(n){if(typeof n!="string"||!Q7e.test(n))throw un("bad-request","Invalid target id");return n}function YK(n,{includesTargetId:t}={}){if(!n||typeof n!="object"||Array.isArray(n))throw un("bad-request","Invalid target");if(t)YM(n.targetId);else if(Object.hasOwn(n,"targetId"))throw un("bad-request","A target id cannot be changed");return n}function D7e(n){YK(n);let t=Object.keys(n);if(t.length!==2||!t.includes("kind")||!t.includes("route"))throw un("bad-request","Invalid draft target");return n}function ple(n){if(n?.aborted)throw un("cancelled","Request cancelled")}function bd(n,t="delivery-failed"){return n?.code==="workspace-bot-not-found"?un("unknown-bot","Unknown bot",{cause:n}):w7e.has(n?.code)?n:un(t,t,{cause:n})}function O7e(n){if(!n||typeof n!="object"||typeof n.channel!="string"||!y7e.test(n.channel))throw new TypeError("A delivery adapter with a valid channel is required");for(let t of S7e)if(typeof n[t]!="function")throw new TypeError(`A complete delivery adapter is required (${t})`);return n}var jK=class{#e=new Map;registerAdapter(t){let o=O7e(t),i=Object.freeze({adapter:o});return this.#e.set(o.channel,i),()=>this.#e.get(o.channel)!==i?!1:(this.#e.delete(o.channel),!0)}async listTargets(t){let o=xE(t),i=await this.#A(o);try{let e=await i.listTargets(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid targets");return{botId:o,channel:i.channel,targets:e}}catch(e){throw bd(e)}}async listSuggestions(t){let o=xE(t),i=await this.#A(o);try{let e=await i.listSuggestions(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid suggestions");return{botId:o,channel:i.channel,suggestions:e.map(a=>Vd(i.channel,a,{targetIdRequired:!1}))}}catch(e){throw bd(e)}}async createTarget(t,o){let i=xE(t);YK(o,{includesTargetId:!0});let e=await this.#A(i);try{return await e.createTarget(i,o)}catch(a){throw bd(a)}}async updateTarget(t,o,i){let e=xE(t),a=YM(o);YK(i);let A=await this.#A(e);try{return await A.updateTarget(e,a,i)}catch(r){throw bd(r)}}async deleteTarget(t,o){let i=xE(t),e=YM(o),a=await this.#A(i);try{return await a.deleteTarget(i,e),{deleted:!0}}catch(A){throw bd(A)}}async send(t,o,i,{signal:e}={}){let a=xE(t),A=typeof o=="string"?YM(o):null,r=A===null?D7e(o):null;if(typeof i!="string"||!i.trim())throw un("bad-request","Message text is required");ple(e);let s=await this.#A(a);try{let g;if(r)g={targetId:m7e,...r};else{let c=await s.listTargets(a);if(!Array.isArray(c))throw new TypeError("Adapter returned invalid targets");if(g=c.find(I=>I?.targetId===A),!g)throw un("unknown-target","Unknown target")}return ple(e),await s.sendText(a,g,i,{signal:e}),{sent:!0}}catch(g){throw e?.aborted||g?.name==="AbortError"||g?.code==="ABORT_ERR"?un("cancelled","Request cancelled",{cause:g}):bd(g)}}async#A(t){for(let{adapter:o}of this.#e.values()){let i;try{i=await o.ownsBot(t)}catch(e){throw bd(e)}if(i)return o}throw un("unknown-bot","Unknown bot")}};function hle(){return new jK}var pQ=ze(aO(),1);import{createHash as b7e}from"node:crypto";import{readFile as Cle,realpath as As,stat as M7e}from"node:fs/promises";import{homedir as _7e}from"node:os";import{basename as T7e,dirname as qK,isAbsolute as WK,join as Ic,relative as N7e,resolve as JM,sep as R7e}from"node:path";import{fileURLToPath as k7e}from"node:url";var kI="@xmanrui/dsh-im",hQ="https://registry.npmjs.org/",v7e=15*6e4,P7e=1e4,Ele=16*1024;function ts(n,t={}){return Object.assign(new Error(n),{code:n,...t})}function jM(n,t){return typeof n?.get=="function"?n.get(t):n?.[t]}function zK(n,t){let o=N7e(n,t);return o!==".."&&!o.startsWith(`..${R7e}`)&&!WK(o)}async function G7e(n){try{return await Cle(n,"utf8")}catch(t){if(t.code==="ENOENT")return"";throw t}}async function VK(n){let t=await Cle(Ic(n,"package.json"),"utf8");return{directory:await As(n),manifest:JSON.parse(t),contents:t}}async function JK(n,t){let o=qK(await As(n));for(;;){try{let e=await VK(o);return e.manifest?.name===t?e:null}catch(e){if(e.code!=="ENOENT")throw e}let i=qK(o);if(i===o)return null;o=i}}function F7e(n){return typeof n=="string"&&n.length>0&&Buffer.byteLength(n)<=255&&!n.startsWith("-")&&![".","..","node_modules"].includes(n)&&!/[\\/\x00-\x1f\x7f<>:"|?*]/u.test(n)}function L7e(n){if(n[0]==="web")return"web";let t;for(let o=0;o0&&(pQ.default.validRange(n)!==null||/^[A-Za-z][A-Za-z0-9._-]*$/u.test(n))}async function K7e(n){if(n.manifest?.name!==kI||pQ.default.valid(n.manifest.version)===null)return!1;let t=[n.manifest.main,n.manifest.exports?.["./client"],n.manifest.dsh?.bundle?.patch];for(let o of t){if(typeof o!="string"||!o||WK(o)||o.includes("\0"))return!1;let i=JM(n.directory,o);if(!zK(n.directory,i)||!zK(n.directory,await As(i))||!(await M7e(i)).isFile())return!1}return!0}function x7e(n){if(n==null||n==="")return!0;if(typeof n!="string")return!1;try{return new URL(n).href===hQ}catch{return!1}}async function ule(n,{signal:t,timeoutMs:o,errorCode:i,capture:e=!1}){if(t?.aborted)throw ts("install-interrupted");let a=new AbortController,A,r,s=B=>{A??=B,a.abort(),r?.cancel?.()},g=()=>s("install-interrupted");t?.addEventListener("abort",g,{once:!0});let c=setTimeout(()=>s("install-timeout"),o),I="",d="";try{r=n(a.signal),r.stdout?.on("data",f=>{e&&(I=(I+f.toString()).slice(-Ele))}),r.stderr?.on("data",f=>{d=(d+f.toString()).slice(-Ele)}),r.stdout?.on("error",()=>s(i)),r.stderr?.on("error",()=>s(i));let B=await r.done;if(A)throw ts(A);if(B.exitCode!==0||B.signal)throw ts(i,{exitCode:B.exitCode,diagnosticCode:d.match(/\bERR_PNPM_[A-Z0-9_]+\b/u)?.[0]});return{exitCode:0,signal:null,...e?{stdout:I}:{}}}catch(B){throw A?ts(A):B.code===i?B:ts(i)}finally{clearTimeout(c),t?.removeEventListener("abort",g)}}function Ble(n={}){let t=n.ctx,o=n.env??process.env,i=n.argv??process.argv,e=n.execArgv??process.execArgv,a=n.execPath??process.execPath,A=n.cwd??process.cwd(),r=n.platform??process.platform,s=n.osHome??_7e(),g=n.electron??process.versions.electron,c=n.moduleUrl??import.meta.url,I=JK(k7e(c),kI).catch(()=>null),d;async function B(){let T=jM(t,"desktopProfiles"),_=jM(t,"desktopPnpm"),R=jM(t,"desktopPnpmBootstrap"),H=!!(g||T||_||R),F=T?.current,L=H?F?.name:L7e(i.slice(2)),q=H&&R?.homeDir?JM(R.homeDir):U7e(o,s),z={environmentKind:H?"desktop":"cli",homeDir:q,profileName:L};if(!F7e(L))return{...z,blockedReason:"unknown-profile"};let K=await As(Ic(q,"profiles",L)),G=await As(q),V={...z,homeDir:G,profileDir:K};if(H)try{if(typeof _?.runPlugin!="function"||typeof _?.run!="function"||!R||!F?.dir||R.activeProfileName!==L||await As(F.dir)!==K||await As(R.activeProfileDir)!==K||await As(R.appExecutable)!==await As(a))return{...V,blockedReason:"executor-unavailable"};let N=await JK(R.dshBootstrapPath,"dsh-plugin-desktop");return!N||T7e(R.dshBootstrapPath)!=="desktop-cli.js"||qK(await As(R.dshBootstrapPath))!==Ic(N.directory,"lib")?{...V,blockedReason:"executor-unavailable"}:{...V,desktop:_,executable:a,cliEntry:R.dshBootstrapPath}}catch{return{...V,blockedReason:"executor-unavailable"}}let U=jM(t,"subprocess");if(typeof U?.spawn!="function"||typeof i[1]!="string"||!WK(i[1])||r==="win32")return{...V,blockedReason:"executor-unavailable"};try{let N=await JK(i[1],"@deepseek-ai/dsh");if(!N)return{...V,blockedReason:"executor-unavailable"};let k=await As(i[1]),J=typeof N.manifest.bin=="string"?N.manifest.bin:N.manifest.bin?.dsh,X=typeof J=="string"?JM(N.directory,J):"";return k!==X&&k!==Ic(N.directory,"src","bin.ts")?{...V,blockedReason:"executor-unavailable"}:{...V,subprocess:U,executable:a,cliEntry:k}}catch{return{...V,blockedReason:"executor-unavailable"}}}function f(T,_,R,H=!1){let F=T.subprocess.spawn({argv:H?["pnpm",..._]:[a,...e,T.cliEntry,..._],cwd:H?T.profileDir:A,env:{DSH_HOME:T.homeDir,CI:"true"},stdio:{stdin:"ignore",stdout:"pipe",stderr:"pipe"},graceMs:3e3,signal:R});return{stdout:F.stdout,stderr:F.stderr,cancel:()=>F.terminate(),done:(async()=>{try{return await F.done}finally{await F.waitForExit()}})()}}async function Q(T,_){let R=["config","get","@xmanrui:registry","--json"],F=(await ule(q=>T.desktop?T.desktop.run(R,q):f(T,R,q,!0),{signal:_,timeoutMs:n.configTimeoutMs??P7e,errorCode:"registry-check-failed",capture:!0})).stdout.trim(),L;try{L=F===""||F==="undefined"?void 0:JSON.parse(F)}catch{throw ts("registry-check-failed")}if(!x7e(L))throw ts("registry-conflict")}async function y({preflight:T=!1}={}){let _,R={installedVersion:null,packageValid:!1,eligible:!1,installationKey:null};try{_=await B();for(let G of["homeDir","profileDir","profileName","environmentKind","executable","cliEntry"])R[G]=_[G]??null;if(!_.profileDir)return{...R,blockedReason:_.blockedReason??"unknown-profile"};let H=await VK(_.profileDir),F=await VK(Ic(_.profileDir,"node_modules",kI));R.sourceInstall=!H7e(H.manifest.dependencies?.[kI])||!zK(Ic(_.profileDir,"node_modules"),F.directory),R.installedVersion=typeof F.manifest.version=="string"?F.manifest.version:null,R.packageValid=await K7e(F);let L=await I,q=`${_.homeDir}\0${_.profileDir}\0${_.profileName}`,z=L?.directory===F.directory&&L?.manifest.version===F.manifest.version;d===void 0&&z&&R.packageValid&&(d=q);let K=await Promise.all(["pnpm-lock.yaml","pnpm-workspace.yaml","package-lock.json"].map(G=>G7e(Ic(_.profileDir,G))));return R.installationKey=b7e("sha256").update(JSON.stringify([q,H.contents,F.directory,F.contents,_.cliEntry,_.executable,...K])).digest("hex"),d!==void 0&&d!==q||!z&&d===void 0?R.blockedReason="installation-changed":R.packageValid?R.sourceInstall?R.blockedReason="source-install":_.blockedReason?R.blockedReason=_.blockedReason:z?T&&await Q(_):R.blockedReason="pending-restart":R.blockedReason="invalid-installation",R.eligible=!R.blockedReason,{...R,blockedReason:R.blockedReason??null}}catch(H){return{...R,blockedReason:["registry-conflict","registry-check-failed","install-timeout","install-interrupted"].includes(H.code)?H.code:_?.profileDir?"invalid-installation":"unknown-profile"}}}async function m(T,{signal:_,expectedInstallationKey:R}={}){if(pQ.default.valid(T)!==T||pQ.default.prerelease(T))throw ts("invalid-version");let H=await y();if(R!==void 0&&H.installationKey!==R)throw ts("installation-changed");if(!H.eligible)throw ts(H.blockedReason);let F=await B();await Q(F,_);let L=await y();if(!L.eligible||L.installationKey!==H.installationKey)throw ts("installation-changed");let q=["add","-w","--save-exact",`${kI}@${T}`,`--registry=${hQ}`];return ule(z=>F.desktop?F.desktop.runPlugin(q,F.profileDir,z):f(F,["plugin","--profile",F.profileName,...q],z),{signal:_,timeoutMs:n.installTimeoutMs??v7e,errorCode:"install-failed"})}return Object.freeze({inspect:y,install:m})}var vI=ze(aO(),1);import{createHash as Y7e,randomUUID as XK}from"node:crypto";import{mkdir as j7e,open as J7e,readFile as Sle,rename as q7e,stat as wle,unlink as Dle,writeFile as z7e}from"node:fs/promises";import{isAbsolute as fle,join as uQ}from"node:path";var CQ=new Set(["installing","verifying"]),V7e=new Set([...CQ,"restart-required","completed","failed","interrupted"]),Qle=256*1024,W7e=["package.json","pnpm-lock.yaml","pnpm-workspace.yaml"],qM=Symbol("no update lock");function Mt(n){return Object.assign(new Error(n),{code:n})}async function yle(n=globalThis.fetch,t=1e4){let o;try{if(o=await n(`${hQ}${encodeURIComponent(kI)}/latest`,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(t)}),!o.ok)throw Mt("check-failed");if(Number(o.headers.get("content-length"))>Qle)throw Mt("invalid-release");let i=[],e=0;for await(let c of o.body){if(e+=c.byteLength,e>Qle)throw Mt("invalid-release");i.push(Buffer.from(c))}let a=JSON.parse(Buffer.concat(i).toString("utf8")),A=a.version;if(a.name!==kI||typeof A!="string"||vI.default.valid(A)!==A||vI.default.prerelease(A))throw Mt("invalid-release");let r=a.engines?.node;if(r!==void 0&&(typeof r!="string"||!vI.default.validRange(r)))throw Mt("invalid-release");let s=new URL(a.dist?.tarball),g=a.dist?.integrity;if(s.origin!==new URL(hQ).origin||s.username||s.password||s.search||s.hash||s.pathname!==`/@xmanrui/dsh-im/-/dsh-im-${A}.tgz`||typeof g!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(g))throw Mt("invalid-release");return{version:A,nodeRange:r??"*",integrity:g,tarball:s.href}}catch(i){throw i?.code==="invalid-release"||i instanceof SyntaxError||i instanceof TypeError&&o?.ok?Mt("invalid-release"):Mt("check-failed")}}function mle(n){if(!fle(n.homeDir??"")||!fle(n.profileDir??""))return null;let t=Y7e("sha256").update(n.profileDir).digest("hex").slice(0,24),o=uQ(n.homeDir,"updates","dsh-im",t);return{directory:o,state:uQ(o,"state.json"),lock:uQ(o,"install.lock"),backup:uQ(o,"before.json")}}async function ZK(n,t=null){try{if((await wle(n)).size>10*1024*1024)throw Mt("state-unavailable");return JSON.parse(await Sle(n,"utf8"))}catch(o){if(o.code==="ENOENT")return t;throw Mt("state-unavailable")}}async function EQ(n,t){let o=`${n}.${XK()}.tmp`;try{await z7e(o,`${JSON.stringify(t,null,2)} +${n.stack}`:i}function Qxe(n){n<1028||(jg[n]=LB,LB=n)}function GB(n,t){return n=n>>>0,Sh().subarray(n/1,n/1+t)}var Kl=null;function eA(){return(Kl===null||Kl.buffer.detached===!0||Kl.buffer.detached===void 0&&Kl.buffer!==ie.memory.buffer)&&(Kl=new DataView(ie.memory.buffer)),Kl}function vr(n,t){return n=n>>>0,Sxe(n,t)}var FB=null;function Sh(){return(FB===null||FB.byteLength===0)&&(FB=new Uint8Array(ie.memory.buffer)),FB}function Fe(n){return jg[n]}function kr(n,t){try{return n.apply(this,t)}catch(o){ie.__wbindgen_export3(rA(o))}}var jg=new Array(1024).fill(void 0);jg.push(void 0,null,!0,!1);var LB=jg.length;function Yn(n){return n==null}function yxe(n,t,o,i){let e={a:n,b:t,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let r=e.a;e.a=0;try{return i(r,e.b,...A)}finally{e.a=r,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,M$.unregister(e))},M$.register(a,e,e),a}function vt(n,t){let o=t(n.length*1,1)>>>0;return Sh().set(n,o/1),KA=n.length,o}function _$(n,t){let o=t(n.length*4,4)>>>0,i=eA();for(let e=0;e>>0;return Sh().subarray(s,s+r.length).set(r),KA=r.length,s}let i=n.length,e=t(i,1)>>>0,a=Sh(),A=0;for(;A127)break;a[e+A]=r}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let r=Sh().subarray(e+A,e+i),s=UB.encodeInto(n,r);A+=s.written,e=o(e,i,A,1)>>>0}return KA=A,e}function mA(n){let t=Fe(n);return Qxe(n),t}var bD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});bD.decode();var mxe=2146435072,wL=0;function Sxe(n,t){return wL+=t,wL>=mxe&&(bD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),bD.decode(),wL=t),bD.decode(Sh().subarray(n,n+t))}var UB=new TextEncoder;"encodeInto"in UB||(UB.encodeInto=function(n,t){let o=UB.encode(n);return t.set(o),{read:n.length,written:o.length}});var KA=0,wxe,ie;function Dxe(n,t){return ie=n.exports,wxe=t,Kl=null,FB=null,ie}function N$(n){if(ie!==void 0)return ie;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=Cxe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,t);return Dxe(o,n)}var Oxe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function R$(n){let t=atob(n),o=new Uint8Array(t.length);for(let i=0;in.length===33?n:Buffer.concat([Jg,n]),Dr={generateKeyPair:()=>{let{pubKey:n,privKey:t}=oI.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(n.slice(1))}},sharedKey:(n,t)=>{let o=oI.calculateAgreement($o(t),n);return Buffer.from(o)},sign:(n,t)=>oI.calculateSignature(n,t),verify:(n,t,o)=>{try{return oI.verifySignature($o(n),t,o),!0}catch{return!1}}},PD=(n,t)=>{let o=Dr.generateKeyPair(),i=$o(o.public),e=Dr.sign(n.private,i);return{keyPair:o,signature:e,keyId:t}},v$=16;function xl(n,t,o,i){let e=OL("aes-256-gcm",t,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function Yl(n,t,o,i){let e=bL("aes-256-gcm",t,o),a=n.slice(0,n.length-v$),A=n.slice(n.length-v$);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function P$(n,t,o){let i=OL("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function G$(n,t,o){let i=bL("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function F$(n,t){return vxe(n.subarray(16),t,n.subarray(0,16))}function vxe(n,t,o){let i=bL("aes-256-cbc",t,o);return Buffer.concat([i.update(n),i.final()])}function L$(n,t){let o=kxe(16),i=OL("aes-256-cbc",t,o);return Buffer.concat([o,i.update(n),i.final()])}function qn(n,t,o="sha256"){return Rxe(o,t).update(n).digest()}function bh(n){return Nxe("sha256").update(n).digest()}async function GD(n,t){let i=new TextEncoder().encode(n),e=new Uint8Array(t instanceof Uint8Array?t:new Uint8Array(t)),a=await k$.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await k$.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var jB={replacer:(n,t)=>Buffer.isBuffer(t)||t instanceof Uint8Array||t?.type==="Buffer"?{type:"Buffer",data:Buffer.from(t?.data||t).toString("base64")}:t,reviver:(n,t)=>{if(typeof t=="object"&&t!==null&&t.type==="Buffer"&&typeof t.data=="string")return Buffer.from(t.data,"base64");if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(t);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return t}},Mh=(n,t="me")=>(n?.fromMe?t:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",K$=n=>n==null||n==="",Gxe=n=>{let o=(YB(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},x$=n=>{let t=new Uint8Array(n);if(t.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=t[t.length-1];if(o>t.length)throw new Error(`unpad given ${t.length} bytes, but pad is ${o}`);return new Uint8Array(t.buffer,t.byteOffset,t.length-o)},Y$=n=>(n.sort(),"2:"+bh(Buffer.from(n.join(""))).toString("base64").slice(0,6)),_h=n=>Gxe(ne.Message.encode(n).finish()),j$=()=>Uint16Array.from(YB(2))[0]&16383,qg=(n,t=4)=>{let o=n,i=new Uint8Array(t);for(let e=t-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},qr=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,va=(n=new Date)=>Math.floor(n.getTime()/1e3);var JB=n=>J$(n).delay,J$=n=>{let t=new Error().stack,o,i;return{delay:new Promise((A,r)=>{o=setTimeout(A,n),i=r}),cancel:()=>{clearTimeout(o),i(new FD.Boom("Cancelled",{statusCode:500,data:{stack:t}}))}}};async function Th(n,t){if(!n)return new Promise(t);let o=new Error().stack,{delay:i,cancel:e}=J$(n);return new Promise((A,r)=>{i.then(()=>r(new FD.Boom("Timed Out",{statusCode:tr.timedOut,data:{stack:o}}))).catch(s=>r(s)),t(A,r)}).finally(e)}var zr=n=>{let t=Buffer.alloc(44);if(t.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=fA(n);e?.user&&(t.write(e.user,8),t.write("@c.us",8+e.user.length))}return YB(16).copy(t,28),"3EB0"+Pxe("sha256").update(t).digest().toString("hex").toUpperCase().substring(0,18)},ML=()=>"3EB0"+YB(18).toString("hex").toUpperCase();function _L(n,t){return async(o,i)=>{let e,a;await Th(i,(A,r)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&r(g?.error||new FD.Boom("Connection Closed",{statusCode:tr.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(t,e)}).finally(()=>{n.off(t,e),n.off("connection.update",a)})}}var q$=n=>_L(n,"connection.update");var z$=()=>{let n=YB(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},Fxe={sender:ne.WebMessageInfo.Status.SERVER_ACK,played:ne.WebMessageInfo.Status.PLAYED,read:ne.WebMessageInfo.Status.READ,"read-self":ne.WebMessageInfo.Status.READ},V$=n=>{let t=Fxe[n];return typeof n>"u"?ne.WebMessageInfo.Status.DELIVERY_ACK:t},Lxe={conflict:tr.connectionReplaced},W$=n=>{let[t]=vs(n),o=t?.tag||"unknown",i=+(n.attrs.code||Lxe[o]||tr.badSession);return i===tr.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},Z$=({tag:n,attrs:t})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":t.reason==="timeout"?o="timeout":o="terminate";break;case"preaccept":o="preaccept";break;case"transport":o="transport";break;case"relaylatency":o="relaylatency";break;case"reject":o="reject";break;case"accept":o="accept";break;default:o="ringing";break}return o},U$="Unexpected server response: ",X$=n=>{let t=500;if(n?.message?.includes(U$)){let o=+n?.message.slice(U$.length);!Number.isNaN(o)&&o>=400&&(t=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(t=408);return t};function LD(n){for(let t in n)typeof n[t]>"u"&&delete n[t];return n}var H$="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function $$(n){let t=0,o=0,i=[];for(let e of n)for(t=t<<8|e&255,o+=8;o>=5;)i.push(H$.charAt(t>>>o-5&31)),o-=5;return o>0&&i.push(H$.charAt(t<<5-o&31)),i.join("")}function eee(n){return ne.Message.encode(n).finish()}var jl=ze(jr(),1);var Uxe=async(n,t)=>qA(n)||Ea(n)?n:await t.lidMapping.getLIDForPN(n)||n,Hxe=async(n,t,o,i,e)=>{let{senderAlt:a}=HD(n);if(a&&qA(a)&&Tt(t)&&i===t)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:t}]),await o.migrateSession(t,a),e.debug({sender:t,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:t,senderAlt:a,error:A},"Failed to store LID mapping")}},UD="Message absent from node",Aee="Key used already or never filled",tee="Your account has been restricted",Kxe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},Jl={SenderReachoutTimelocked:463,ParsingError:487,UnrecognizedStanza:488,UnrecognizedStanzaClass:489,UnrecognizedStanzaType:490,InvalidProtobuf:491,InvalidHostedCompanionStanza:493,MissingMessageSecret:495,SignalErrorOldCounter:496,MessageDeletedOnPeer:499,UnhandledError:500,UnsupportedAdminRevoke:550,UnsupportedLIDGroup:551,DBOperationFailed:552},TL={MessageAccountRestriction:"463",SmaxInvalid:"479"},HD=n=>{let t,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(t=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(t=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:t,recipientAlt:o}};function NL(n,t,o){let i,e,a,A=!1,r=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!r)throw new jl.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new jl.Boom("Invalid message stanza: missing from attribute",{data:n});let I=HD(n),d=m=>kt(m,t),B=m=>kt(m,o);if(Tt(s)||qA(s)||Ea(s)||wr(s)){if(c&&!mh(c)){if(!d(s)&&!B(s))throw new jl.Boom("receipient present, but msg not from me",{data:n});(d(s)||B(s))&&(A=!0),e=c}else(d(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(Jr(s)){if(!g)throw new jl.Boom("No participant in group message");(d(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(PB(s)){if(!g)throw new jl.Boom("No participant in group message");let m=d(g);Yg(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(tI(s))i="newsletter",e=s,a=s,(d(s)||B(s))&&(A=!0);else throw new jl.Boom("Unknown message type",{data:n});let f=n?.attrs?.notify,Q={remoteJid:e,remoteJidAlt:Jr(e)?void 0:I.senderAlt,remoteJidUsername:Jr(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:r,participant:g,participantAlt:Jr(e)?I.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:I.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:Q,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:f,broadcast:PB(s)};return Q.fromMe&&(y.status=ne.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var ree=(n,t,o,i,e)=>{let{fullMessage:a,author:A,sender:r}=NL(n,t,o);return{fullMessage:a,category:n.attrs.category,author:A,async decrypt(){let s=0;if(Array.isArray(n.content))for(let{tag:g,attrs:c,content:I}of n.content){if(g==="verified_name"&&I instanceof Uint8Array){let f=ne.VerifiedNameCertificate.decode(I),Q=ne.VerifiedNameCertificate.Details.decode(f.details);a.verifiedBizName=Q.verifiedName}if(g==="unavailable"&&c.type==="view_once"&&(a.key.isViewOnce=!0),c.count&&g==="enc"&&(a.retryCount=Number(c.count)),g!=="enc"&&g!=="plaintext"||!(I instanceof Uint8Array))continue;s+=1;let d,B=await Uxe(A,i);g!=="plaintext"&&await Hxe(n,A,i,B,e);try{let f=g==="plaintext"?"plaintext":c.type;switch(f){case"skmsg":d=await i.decryptGroupMessage({group:r,authorJid:A,msg:I});break;case"pkmsg":case"msg":d=await i.decryptMessage({jid:B,type:f,ciphertext:I});break;case"plaintext":d=I;break;default:throw new Error(`Unknown e2e type: ${f}`)}let Q=ne.Message.decode(f!=="plaintext"?x$(d):d);if(Q=Q.deviceSentMessage?.message||Q,Q.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:Q.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,Q):a.message=Q}catch(f){let Q={key:a.key,err:f,messageType:g==="plaintext"?"plaintext":c.type,sender:r,author:A,isSessionRecordError:xxe(f)};e.error(Q,"failed to decrypt message"),a.messageStubType=ne.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[f.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=ne.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[UD])}}};function xxe(n){let t=n?.message||n?.toString()||"";return Kxe.sessionRecordErrors.some(o=>t.includes(o))}var rc=ze(jr(),1);import{randomBytes as JU}from"crypto";import{promises as qU}from"fs";var Vn=ze(jr(),1);import{exec as xze}from"child_process";import*as yo from"crypto";import{once as CE}from"events";import{createReadStream as Fb,createWriteStream as FU,promises as fE}from"fs";import{tmpdir as Mne}from"os";import{join as Pb}from"path";import{Readable as Ff,Transform as Yze}from"stream";import{URL as LU}from"url";var UU=()=>Mne(),_ne=async()=>{let[n,t]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(pre(),dre)).catch(()=>{})]);if(t)return{sharp:t};if(n)return{jimp:n};throw new Vn.Boom("No image processing library available")},jze=n=>`WhatsApp ${Kne[n]} Keys`,Lb=async(n,t,o)=>{let{stream:i}=await Lf(n);o?.debug("got stream for raw upload");let e=yo.createHash("sha256"),a=Pb(Mne(),t+zr()),A=FU(a),r=0;try{for await(let g of i)r+=g.length,e.update(g),A.write(g)||await CE(A,"drain");A.end(),await CE(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:r}}catch(s){A.destroy(),i.destroy();try{await fE.unlink(a)}catch{}throw s}};async function Tne(n,t){if(!n)throw new Vn.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=Jn(n,112,{info:jze(t)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var Jze=async(n,t,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${t}`;xze(A,r=>{r?a(r):e()})}),HU=async(n,t=32)=>{n instanceof Ff&&(n=await Gb(n));let o=await _ne();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(t).jpeg({quality:50}).toBuffer(),original:{width:e.width,height:e.height}}}else if("jimp"in o&&typeof o.jimp?.Jimp=="object"){let i=await o.jimp.Jimp.read(n),e={width:i.width,height:i.height};return{buffer:await i.resize({w:t,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new Vn.Boom("No image processing library available")},qze=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),Ub=async(n,t)=>{let o,{width:i=640,height:e=640}=t||{};if(Buffer.isBuffer(n))o=n;else{let{stream:r}=await Lf(n);o=await Gb(r)}let a=await _ne(),A;if("sharp"in a&&typeof a.sharp?.default=="function")A=a.sharp.default(o).resize(i,e).jpeg({quality:50}).toBuffer();else if("jimp"in a&&typeof a.jimp?.Jimp=="function"){let r=await a.jimp.Jimp.read(o),s=Math.min(r.width,r.height);A=r.crop({x:0,y:0,w:s,h:s}).resize({w:i,h:e,mode:a.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50})}else throw new Vn.Boom("No image processing library available");return{img:await A}};async function Nne(n){let t=await Promise.resolve().then(()=>(One(),Dne)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await t.parseBuffer(n,void 0,i):typeof n=="string"?o=await t.parseFile(n,i):o=await t.parseStream(n,void 0,i),o.format.duration}async function Rne(n,t){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let d=Fb(n);i=await Gb(d)}else i=await Gb(n);let a=(await o(i)).getChannelData(0),A=64,r=Math.floor(a.length/A),s=[];for(let d=0;dd*g);return new Uint8Array(c.map(d=>Math.floor(100*d)))}catch(o){t?.debug("Failed to generate waveform: "+o)}}var bne=n=>{let t=new Ff({read:()=>{}});return t.push(n),t.push(null),t},Gb=async n=>{let t=[];for await(let o of n)t.push(o);return n.destroy(),Buffer.concat(t)},Lf=async(n,t)=>{if(Buffer.isBuffer(n))return{stream:bne(n),type:"buffer"};if("stream"in n)return{stream:n.stream,type:"readable"};let o=n.url.toString();if(o.startsWith("data:")){let i=Buffer.from(o.split(",")[1],"base64");return{stream:bne(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await Hb(n.url,t),type:"remote"}:{stream:Fb(n.url),type:"file"}};async function kne(n,t,o){let i,e;if(t==="image"){let{buffer:a,original:A}=await HU(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(t==="video"){let a=Pb(UU(),zr()+".jpg");try{await Jze(n,a,"00:00:00",{width:32,height:32}),i=(await fE.readFile(a)).toString("base64"),await fE.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var Hb=async(n,t={})=>{let o=await fetch(n.toString(),{dispatcher:t.dispatcher,method:"GET",headers:t.headers});if(!o.ok)throw new Vn.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof Ff?o.body:Ff.fromWeb(o.body)},vne=async(n,t,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await Lf(n,e);o?.debug("fetched media stream");let r=yo.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await Tne(r,t),I=Pb(UU(),t+zr()+"-enc"),d=FU(I),B,f;i&&(f=Pb(UU(),t+zr()+"-original"),B=FU(f));let Q=0,y=yo.createCipheriv("aes-256-cbc",s,g),m=yo.createHmac("sha256",c).update(g),T=yo.createHash("sha256"),_=yo.createHash("sha256"),R=async H=>{_.update(H),m.update(H),d.write(H)||await CE(d,"drain")};try{for await(let K of a){if(Q+=K.length,A==="remote"&&e?.maxContentLength&&Q+K.length>e.maxContentLength)throw new Vn.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(K)||await CE(B,"drain")),T.update(K),await R(y.update(K))}await R(y.final());let H=m.digest().slice(0,10);_.update(H);let F=T.digest(),L=_.digest();d.write(H);let q=CE(d,"finish"),z=B?CE(B,"finish"):Promise.resolve();return d.end(),B?.end?.(),a.destroy(),await q,await z,o?.debug("encrypted data successfully"),{mediaKey:r,originalFilePath:f,encFilePath:I,mac:H,fileEncSha256:L,fileSha256:F,fileLength:Q}}catch(H){d.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),T.destroy(),_.destroy(),a.destroy();try{await fE.unlink(I),f&&await fE.unlink(f)}catch(F){o?.error({err:F},"failed deleting tmp files")}throw H}},KU="mmg.whatsapp.net",BE=16,GU=n=>Math.floor(n/BE)*BE,Uf=(n,t=KU)=>`https://${t}${n}`,zze=n=>{if(n)try{return new LU(n).host}catch{return}},QE=async({mediaKey:n,directPath:t,url:o},i,e={})=>{let a=e.host??zze(o),A=t?Uf(t,a):o;if(!A)throw new Vn.Boom("No valid media URL or directPath present in message",{statusCode:400});let r=await Tne(n,i);return Vze(A,r,e)},Vze=async(n,{cipherKey:t,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,r=0,s=!1;if(i){let m=GU(i||0);m&&(r=m-BE,A=m,s=!0)}let g=e?GU(e||0)+BE:void 0,c=a?.headers?a.headers:void 0,I={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:Hf};(r||g)&&(I.Range=`bytes=${r}-`,g&&(I.Range+=g));let d=await Hb(n,{...a||{},headers:I}),B=Buffer.from([]),f,Q=(m,T)=>{if(i||e){let _=A>=i?void 0:Math.max(i-A,0),R=A+m.lengththis.push(F)),_()}catch(F){_(F)}},final(m){try{Q(f.final(),T=>this.push(T)),m()}catch(T){m(T)}}});return d.pipe(y,{end:!0})};var Wze=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",Pne=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new LU(n),r=A.protocol==="https:"?await import("https"):await import("http"),g=(await fE.stat(t)).size;return new Promise((c,I)=>{let d=r.request({hostname:A.hostname,port:A.port||(A.protocol==="https:"?443:80),path:A.pathname+A.search,method:"POST",headers:{...o,"Content-Length":g},agent:e,timeout:i},f=>{if(f.statusCode&&f.statusCode>=300&&f.statusCode<400&&f.headers.location){f.resume();let y=new LU(f.headers.location,n).toString();c(Pne({url:y,filePath:t,headers:o,timeoutMs:i,agent:e},a+1));return}let Q="";f.on("data",y=>Q+=y),f.on("end",()=>{try{c(JSON.parse(Q))}catch{c(void 0)}})});d.on("error",I),d.on("timeout",()=>{d.destroy(),I(new Error("Upload timeout"))});let B=Fb(t);B.pipe(d),B.on("error",f=>{d.destroy(),I(f)})})},Zze=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e})=>{let a=Fb(t),A=Ff.toWeb(a),r=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...r?{dispatcher:r}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},Xze=async(n,t)=>Wze()?(t?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),Pne(n)):(t?.debug("Using web-standard Fetch API for upload"),Zze(n)),Gne=({customUploadHosts:n,fetchAgent:t,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:r,timeoutMs:s})=>{let g=await e(!1),c,I=[...n,...g.hosts];r=qze(r);let B={...(()=>{let f=i?.headers;return f?Array.isArray(f)?Object.fromEntries(f):f:{}})(),"Content-Type":"application/octet-stream",Origin:Hf};for(let{hostname:f}of I){o.debug(`uploading to "${f}"`);let Q=encodeURIComponent(g.auth),y=`https://${f}${YU[A]}/${r}?auth=${Q}&token=${r}`,m;try{if(m=await Xze({url:y,filePath:a,headers:B,timeoutMs:s,agent:t},o),m?.url||m?.direct_path){c={mediaUrl:m.url,directPath:m.direct_path,meta_hmac:m.meta_hmac,fbid:m.fbid,ts:m.ts};break}else throw g=await e(!0),new Error(`upload failed, reason: ${JSON.stringify(m)}`)}catch(T){let _=f===I[g.hosts.length-1]?.hostname;o.warn({trace:T?.stack,uploadResult:m},`Error in uploading to ${f} ${_?"":", retrying..."}`)}}if(!c)throw new Vn.Boom("Media upload failed on all hosts",{statusCode:500});return c},Fne=n=>Jn(n,32,{info:"WhatsApp Media Retry Notification"}),Lne=(n,t,o)=>{let i={stanzaId:n.id},e=ne.ServerErrorReceipt.encode(i).finish(),a=yo.randomBytes(12),A=Fne(t),r=xl(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:CA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:r},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},Une=n=>{let t=le(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:t.attrs.jid,fromMe:t.attrs.from_me==="true",participant:t.attrs.participant}},i=le(n,"error");if(i){let e=+i.attrs.code;o.error=new Vn.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:xU(e)})}else{let e=le(n,"encrypt"),a=ka(e,"enc_p"),A=ka(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new Vn.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},Hne=({ciphertext:n,iv:t},o,i)=>{let e=Fne(o),a=Yl(n,e,t,Buffer.from(i));return ne.MediaRetryNotification.decode(a)},xU=n=>$ze[n],$ze={[ne.MediaRetryNotification.ResultType.SUCCESS]:200,[ne.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[ne.MediaRetryNotification.ResultType.NOT_FOUND]:404,[ne.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as eVe}from"crypto";var AVe=[{f:1},{f:3,s:[{f:2},{f:3},{f:8},{f:11},{f:17,s:[{f:21},{f:22}]},{f:25}]},{f:4,s:[{f:1},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:5,s:[{f:3},{f:4},{f:5},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:6,s:[{f:1},{f:17,s:[{f:21},{f:22}]},{f:30}]},{f:7,s:[{f:2},{f:7},{f:10},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:8,s:[{f:2},{f:7},{f:9},{f:17,s:[{f:21},{f:22}]},{f:21}]},{f:9,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:12,s:[{f:1},{f:2},{f:14,m:!0},{f:15}]},{f:18,s:[{f:6},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:26,s:[{f:4},{f:5},{f:8},{f:13},{f:17,s:[{f:21},{f:22}]}]},{f:28,s:[{f:1},{f:2},{f:4},{f:5},{f:6},{f:7,s:[{f:21},{f:22}]}]},{f:37,s:[{f:1,m:!0}]},{f:49,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:53,s:[{f:1,m:!0}]},{f:55,s:[{f:1,m:!0}]},{f:58,s:[{f:1,m:!0}]},{f:59,s:[{f:1,m:!0}]},{f:60,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:64,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:66,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:74,s:[{f:1,m:!0}]},{f:87,s:[{f:1,m:!0}]},{f:88,s:[{f:1},{f:2,s:[{f:1}]},{f:3,s:[{f:21},{f:22}]}]},{f:92,s:[{f:1,m:!0}]},{f:93,s:[{f:1,m:!0}]},{f:94,s:[{f:1,m:!0}]}],Yne=n=>{let t=new Map;for(let o of n)t.set(o.f,{m:o.m,children:o.s?Yne(o.s):void 0});return t},tVe=Yne(AVe),rVe=new Map,aVe="Report Token",Kb={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},xb=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,iVe=(n,t,o,i,e)=>{let a=Buffer.concat([Buffer.from(t,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return Jn(e,32,{info:a.toString("latin1")})},jne=(n,t)=>{let o=[],i=0;for(;i>3,A=e.value&7,r=i;i+=e.bytes;let s=t.get(a),g=I=>I>n.length?!1:(o.push({num:a,bytes:n.subarray(r,I)}),i=I,!0),c=I=>I>n.length?!1:(i=I,!0);if(A===Kb.VARINT){let I=jU(n,i);if(!I.ok)return null;let d=i+I.bytes;if(!s){if(!c(d))return null;continue}if(!g(d))return null;continue}if(A===Kb.FIXED64){let I=i+8;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===Kb.FIXED32){let I=i+4;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===Kb.BYTES){let I=jU(n,i);if(!I.ok)return null;let d=i+I.bytes,B=d+I.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let f=jne(n.subarray(d,B),s.children??rVe);if(f===null)return null;if(f.length>0){let Q=xne(e.value),y=xne(f.length);o.push({num:a,bytes:Buffer.concat([Q,y,f])})}i=B;continue}o.push({num:a,bytes:n.subarray(r,B)}),i=B;continue}return null}return o.length===0?Buffer.alloc(0):(o.sort((e,a)=>e.num-a.num),Buffer.concat(o.map(e=>e.bytes)))},jU=(n,t)=>{let o=0,i=0,e=0;for(;t+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},xne=n=>{let t=[],o=n>>>0;for(;o>127;)t.push(o&127|128),o>>>=7;return t.push(o),Buffer.from(t)},Jne=async(n,t,o)=>{let i=t.messageContextInfo?.messageSecret;if(!i||!o.id)return null;let e=o.fromMe?o.remoteJid:o.participant||o.remoteJid,a=o.fromMe&&o.participant||o.remoteJid,A=iVe(aVe,o.id,e,a,i),r=jne(n,tVe);if(!r||r.length===0)return null;let s=eVe("sha256",A).update(r).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var oVe={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},qne={image:ne.Message.ImageMessage,video:ne.Message.VideoMessage,audio:ne.Message.AudioMessage,sticker:ne.Message.StickerMessage,document:ne.Message.DocumentMessage},nVe=n=>n.match(Ase)?.[0],sVe=async(n,t,o)=>{let i=nVe(n);if(t&&i)try{return await t(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},zne=async n=>{let t;if(typeof n=="number")t=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),t=parseInt(o,16),t}},Kf=async(n,t)=>{let o=t.logger,i;for(let F of tse)F in n&&(i=F);if(!i)throw new rc.Boom("Invalid media type",{statusCode:400});let e={...n,media:n[i]};delete e[i];let a=typeof e.media=="object"&&"url"in e.media&&!!e.media.url&&!!t.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=oVe[i]),a){let F=await t.mediaCache.get(a);if(F){o?.debug({cacheableKey:a},"got media cache hit");let L=ne.Message.decode(F),q=`${i}Message`;return Object.assign(L[q],{...e,media:void 0}),L}}if(!!t.jid&&tI(t.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:F,fileSha256:L,fileLength:q}=await Lb(e.media,t.mediaTypeOverride||i,o),z=L.toString("base64"),{mediaUrl:K,directPath:G}=await t.upload(F,{fileEncSha256B64:z,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});await qU.unlink(F);let V=ne.Message.fromObject({[`${i}Message`]:qne[i].fromObject({url:K,directPath:G,fileSha256:L,fileLength:q,...e,media:void 0})});return e.ptv&&(V.ptvMessage=V.videoMessage,delete V.videoMessage),V.stickerMessage&&(V.stickerMessage.stickerSentTs=Date.now()),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,ne.Message.encode(V).finish())),V}let r=i==="audio"&&typeof e.seconds>"u",s=(i==="image"||i==="video")&&typeof e.jpegThumbnail>"u",g=i==="audio"&&e.ptt===!0&&typeof e.waveform>"u",c=t.backgroundColor&&i==="audio"&&e.ptt===!0,I=r||s,{mediaKey:d,encFilePath:B,originalFilePath:f,fileEncSha256:Q,fileSha256:y,fileLength:m}=await vne(e.media,t.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:I,opts:t.options}),T=Q.toString("base64"),[{mediaUrl:_,directPath:R}]=await Promise.all([(async()=>{let F=await t.upload(B,{fileEncSha256B64:T,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),F})(),(async()=>{try{if(s){let{thumbnail:F,originalImageDimensions:L}=await kne(f,i,t);e.jpegThumbnail=F,!e.width&&L&&(e.width=L.width,e.height=L.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}r&&(e.seconds=await Nne(f),o?.debug("computed audio duration")),g&&(e.waveform=await Rne(f,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await zne(t.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(F){o?.warn({trace:F.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await qU.unlink(B),f&&await qU.unlink(f),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),H=ne.Message.fromObject({[`${i}Message`]:qne[i].fromObject({url:_,directPath:R,mediaKey:d,fileEncSha256:Q,fileSha256:y,fileLength:m,mediaKeyTimestamp:va(),...e,media:void 0})});return e.ptv&&(H.ptvMessage=H.videoMessage,delete H.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,ne.Message.encode(H).finish())),H},gVe=n=>{n=n||0;let t={ephemeralMessage:{message:{protocolMessage:{type:ne.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return ne.Message.fromObject(t)},cVe=(n,t)=>{let o=n.message;if(!o)throw new rc.Boom("no content in message",{statusCode:400});o=ya(o),o=ne.Message.decode(ne.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!t?0:1,i==="conversation"&&(o.extendedTextMessage={text:o[i]},delete o.conversation,i="extendedTextMessage");let a=o?.[i];return e>0?a.contextInfo={forwardingScore:e,isForwarded:!0}:a.contextInfo={},o},Qa=(n,t)=>typeof n=="object"&&n!==null&&t in n&&n[t]!==null&&n[t]!==void 0;function dd(n,t){return typeof n=="object"&&n!==null&&t in n&&n[t]!==null}var IVe=async(n,t)=>{var o,i;let e={};if(Qa(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await sVe(n.text,t.getUrlInfo,t.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let r=A.highQualityThumbnail;r&&(a.thumbnailDirectPath=r.directPath,a.mediaKey=r.mediaKey,a.mediaKeyTimestamp=r.mediaKeyTimestamp,a.thumbnailWidth=r.width,a.thumbnailHeight=r.height,a.thumbnailSha256=r.fileSha256,a.thumbnailEncSha256=r.fileEncSha256)}t.backgroundColor&&(a.backgroundArgb=await zne(t.backgroundColor)),t.font&&(a.font=t.font),e.extendedTextMessage=a}else if(Qa(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new rc.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=ne.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=ne.Message.ContactsArrayMessage.create(n.contacts)}else if(Qa(n,"location"))e.locationMessage=ne.Message.LocationMessage.create(n.location);else if(Qa(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=ne.Message.ReactionMessage.create(n.react);else if(Qa(n,"delete"))e.protocolMessage={key:n.delete,type:ne.Message.ProtocolMessage.Type.REVOKE};else if(Qa(n,"forward"))e=cVe(n.forward,n.force);else if(Qa(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?Yf:0:n.disappearingMessagesInChat;e=gVe(a)}else if(Qa(n,"groupInvite")){if(e.groupInviteMessage={},e.groupInviteMessage.inviteCode=n.groupInvite.inviteCode,e.groupInviteMessage.inviteExpiration=n.groupInvite.inviteExpiration,e.groupInviteMessage.caption=n.groupInvite.text,e.groupInviteMessage.groupJid=n.groupInvite.jid,e.groupInviteMessage.groupName=n.groupInvite.subject,t.getProfilePicUrl){let a=await t.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:t?.options?.dispatcher});if(A.ok){let r=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=r}}}}else if(Qa(n,"pin"))e.pinInChatMessage={},e.messageContextInfo={},e.pinInChatMessage.key=n.pin,e.pinInChatMessage.type=n.type,e.pinInChatMessage.senderTimestampMs=Date.now(),e.messageContextInfo.messageAddOnDurationInSecs=n.type===1?n.time||86400:0;else if(Qa(n,"buttonReply"))switch(n.type){case"template":e.templateButtonReplyMessage={selectedDisplayText:n.buttonReply.displayText,selectedId:n.buttonReply.id,selectedIndex:n.buttonReply.index};break;case"plain":e.buttonsResponseMessage={selectedButtonId:n.buttonReply.id,selectedDisplayText:n.buttonReply.displayText,type:ne.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(dd(n,"ptv")&&n.ptv){let{videoMessage:a}=await Kf({video:n.video},t);e.ptvMessage=a}else if(Qa(n,"product")){let{imageMessage:a}=await Kf({image:n.product.productImage},t);e.productMessage=ne.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(Qa(n,"listReply"))e.listResponseMessage={...n.listReply};else if(Qa(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&t.getCallLink){let A=await t.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?ese:$ne)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||JU(32)},e.eventMessage.name=n.event.name,e.eventMessage.description=n.event.description,e.eventMessage.startTime=a,e.eventMessage.endTime=n.event.endDate?n.event.endDate.getTime()/1e3:void 0,e.eventMessage.isCanceled=n.event.isCancelled??!1,e.eventMessage.extraGuestsAllowed=n.event.extraGuestsAllowed,e.eventMessage.isScheduleCall=n.event.isScheduleCall??!1,e.eventMessage.location=n.event.location}else if(Qa(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new rc.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new rc.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||JU(32)};let a={name:n.poll.name,selectableOptionsCount:n.poll.selectableCount,options:n.poll.values.map(A=>({optionName:A}))};n.poll.toAnnouncementGroup?e.pollCreationMessageV2=a:n.poll.selectableCount===1?e.pollCreationMessageV3=a:e.pollCreationMessage=a}else Qa(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:Qa(n,"sharePhoneNumber")?e.protocolMessage={type:ne.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:Qa(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:Qa(n,"limitSharing")?e.protocolMessage={type:ne.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await Kf(n,t);if(dd(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),dd(n,"mentions")&&n.mentions?.length||dd(n,"mentionAll")&&n.mentionAll){let a=Object.keys(e)[0],A=e[a];A&&"contextInfo"in A?(A.contextInfo=A.contextInfo||{},n.mentions?.length&&(A.contextInfo.mentionedJid=n.mentions),n.mentionAll&&(A.contextInfo.nonJidMentions=1)):A&&(A.contextInfo={mentionedJid:n.mentions,nonJidMentions:n.mentionAll?1:0})}if(dd(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:ne.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),dd(n,"contextInfo")&&n.contextInfo){let a=Object.keys(e)[0],A=e[a];"contextInfo"in A&&A.contextInfo?A.contextInfo={...A.contextInfo,...n.contextInfo}:A&&(A.contextInfo=n.contextInfo)}return dd(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:ne.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),xb(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=JU(32))),ne.Message.create(e)},lVe=(n,t,o)=>{o.timestamp||(o.timestamp=new Date);let i=ya(t),e=xf(i),a=va(o.timestamp),{quoted:A,userJid:r}=o;if(A&&!tI(n)){let g=A.key.fromMe?r:A.participant||A.key.participant||A.key.remoteJid,c=ya(A.message),I=xf(c);c=ne.Message.create({[I]:c[I]});let d=c[I];typeof d=="object"&&d&&"contextInfo"in d&&delete d.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=CA(g),B.stanzaId=A.key.id,B.quotedMessage=c,n!==A.key.remoteJid&&(B.remoteJid=A.key.remoteJid),B&&i[e]&&(i[e].contextInfo=B)}o?.ephemeralExpiration&&e!=="protocolMessage"&&e!=="ephemeralMessage"&&!tI(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||Yf}),t=ne.Message.create(t);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||zr()},message:t,messageTimestamp:a,messageStubParameters:[],participant:Jr(n)||Yg(n)?r:void 0,status:yh.PENDING};return ne.WebMessageInfo.fromObject(s)},Vne=async(n,t,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),lVe(n,await IVe(t,{...o,jid:n}),o)),xf=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},ya=n=>{if(!n)return;for(let o=0;o<5;o++){let i=t(n);if(!i)break;n=i.message}return n;function t(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},Wne=n=>{let t=o=>o.imageMessage?{imageMessage:o.imageMessage}:o.documentMessage?{documentMessage:o.documentMessage}:o.videoMessage?{videoMessage:o.videoMessage}:o.locationMessage?{locationMessage:o.locationMessage}:{conversation:"contentText"in o?o.contentText:"hydratedContentText"in o?o.hydratedContentText:""};return n=ya(n),n?.buttonsMessage?t(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?t(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?t(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?t(n?.templateMessage?.fourRowTemplate):n};var zU=(n,t)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===t.userJid);o?Object.assign(o,t):n.userReceipt.push(t)},VU=(n,t)=>{let o=Mh(t.key),i=(n.reactions||[]).filter(e=>Mh(e.key)!==o);t.text=t.text||"",i.push(t),n.reactions=i};var Zne=n=>{let t={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;t[A]||(t[A]={jid:o,participant:e,messageIds:[]}),t[A].messageIds.push(i)}return Object.values(t)},dVe=[410,404],WU=async(n,t,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&dVe.includes(A.status))return i.logger.info({key:n.key},"sending reupload media request..."),n=await i.reuploadRequest(n),await a();throw A});async function a(){let A=Wne(n.message);if(!A)throw new rc.Boom("No message present",{statusCode:400,data:n});let r=xf(A),s=r?.replace("Message",""),g=A[r];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new rc.Boom(`"${r}" message is not a media message`);let c;"thumbnailDirectPath"in g&&!("url"in g)?(c={directPath:g.thumbnailDirectPath,mediaKey:g.mediaKey},s="thumbnail-link"):c=g;let I=await QE(c,s,o);if(t==="buffer"){let d=[];for await(let B of I)d.push(B);return Buffer.concat(d)}return I}},Xne=n=>{n=Wne(n);let t=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!t)throw new rc.Boom("given message is not a media message",{statusCode:400,data:n});return t};var Yb=ze(jr(),1);import{createHash as uVe}from"crypto";function pVe(n,t){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:$o(t)}),hVe=async({get:n},t,o)=>{let i=[];for(let e=t;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=t-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=Dr.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,t]}},jf=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:qg(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),XU=(n,t)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:qg(t,3)},{tag:"value",attrs:{},content:n.public}]}),ZU=n=>typeof n=="number"&&Number.isInteger(n),ase=n=>{let t=le(n,"keys");if(!t)return null;let o=ka(t,"type");if(!o||o.length!==1||o[0]!==Jg[0])return null;let i=ka(t,"identity"),e=le(t,"skey");if(!i||i.length!==32||!e)return null;let a=rI(n,"registration",4);if(!ZU(a))return null;let A=ka(e,"value"),r=ka(e,"signature"),s=rI(e,"id",3);if(!A||A.length!==32||!r||!ZU(s))return null;let g=le(t,"key"),c;if(g){let I=ka(g,"value"),d=rI(g,"id",3);if(!I||I.length!==32||!ZU(d))return null;c={keyId:d,publicKey:$o(I)}}return{registrationId:a,identityKey:$o(i),signedPreKey:{keyId:s,publicKey:$o(A),signature:r},preKey:c}},ise=async(n,t)=>{let o=A=>A?{keyId:rI(A,"id",3),publicKey:$o(ka(A,"value")),signature:ka(A,"signature")}:void 0,i=PA(le(n,"list"),"user");for(let A of i)Vi(A);let a=pVe(i,100);for(let A of a)for(let r of A){let s=le(r,"skey"),g=le(r,"key"),c=ka(r,"identity"),I=r.attrs.jid,d=rI(r,"registration",4);await t.injectE2ESession({jid:I,session:{registrationId:d,identityKey:$o(c),signedPreKey:o(s),preKey:o(g)}})}},ose=(n,t,o,i)=>{let{user:e,device:a}=fA(t),A=[];for(let r of n){let{devices:s,id:g}=r,c=fA(g),{user:I,server:d}=c,{domainType:B}=c,f=s?.deviceList;if(Array.isArray(f))for(let{id:Q,keyIndex:y,isHosted:m}of f)(!i||Q!==0)&&(e!==I&&o!==I||a!==Q)&&(Q===0||y)&&(m&&(B=B===zt.LID?zt.HOSTED_LID:zt.HOSTED),A.push({user:I,device:Q,domainType:B,server:g$(d,B)}))}return A},$U=async({creds:n,keys:t},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=EVe(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await t.set({"pre-key":i});let r=await hVe(t,a[0],a[0]+a[1]);return{update:A,preKeys:r}},nse=async(n,t)=>{let{creds:o}=n,{update:i,preKeys:e}=await $U(n,t),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:OA},content:[{tag:"registration",attrs:{},content:qg(o.registrationId)},{tag:"type",attrs:{},content:Jg},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>XU(e[+A],+A))},jf(o.signedPreKey)]};return{update:i,node:a}};var CVe=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?ne.ClientPayload.UserAgent.Platform.ANDROID:ne.ClientPayload.UserAgent.Platform.WEB,releaseChannel:ne.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),sse={"Mac OS":ne.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:ne.ClientPayload.WebInfo.WebSubPlatform.WIN32},BVe=n=>{let t=ne.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&sse[n.browser[0]]&&n.browser[1]==="Desktop"&&(t=sse[n.browser[0]]),{webSubPlatform:t}},gse=n=>{let t={connectType:ne.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:ne.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:CVe(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(t.webInfo=BVe(n)),n.pushName&&(t.pushName=n.pushName),t},cse=(n,t)=>{let{user:o,device:i}=fA(n),e={...gse(t),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return ne.ClientPayload.fromObject(e)},fVe=n=>{let t=n.toUpperCase();return t==="ANDROID"?ne.DeviceProps.PlatformType.ANDROID_PHONE:ne.DeviceProps.PlatformType[t]||ne.DeviceProps.PlatformType.CHROME},Ise=({registrationId:n,signedPreKey:t,signedIdentityKey:o},i)=>{let e=uVe("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:fVe(i.browser[1]),requireFullSync:i.syncFullHistory,historySyncConfig:{storageQuotaMb:10240,inlineInitialPayloadInE2EeMsg:!0,recentSyncDaysLimit:void 0,supportCallLogHistory:!1,supportBotUserAgentChatHistory:!0,supportCagReactionsAndPolls:!0,supportBizHostedMsg:!0,supportRecentSyncChunkMessageCountTuning:!0,supportHostedGroupMsg:!0,supportFbidBotChatHistory:!0,supportAddOnHistorySyncMigration:void 0,supportMessageAssociation:!0,supportGroupHistory:!1,onDemandReady:void 0,supportGuestChat:void 0},version:{primary:10,secondary:15,tertiary:7}},A=ne.DeviceProps.encode(a).finish(),r={...gse(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:qg(n),eKeytype:Jg,eIdent:o.public,eSkeyId:qg(t.keyId,3),eSkeyVal:t.keyPair.public,eSkeySig:t.signature}};return ne.ClientPayload.fromObject(r)},lse=(n,{advSecretKey:t,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=le(n,"pair-success"),A=le(a,"device-identity"),r=le(a,"platform"),s=le(a,"device"),g=le(a,"biz");if(!A||!s)throw new Yb.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,I=s.attrs.jid,d=s.attrs.lid,{details:B,hmac:f,accountType:Q}=ne.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);Q!==void 0&&Q===ne.ADVEncryptionType.HOSTED&&(y=eH);let m=qn(Buffer.concat([y,B]),Buffer.from(t,"base64"));if(Buffer.compare(f,m)!==0)throw new Yb.Boom("Invalid account signature");let T=ne.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:_,accountSignature:R,details:H}=T,F=ne.ADVDeviceIdentity.decode(H),L=F.deviceType===ne.ADVEncryptionType.HOSTED?eH:dse,q=Buffer.concat([L,H,o.public]);if(!Dr.verify(_,q,R))throw new Yb.Boom("Failed to verify account signature");let z=Buffer.concat([pse,H,o.public,_]);T.deviceSignature=Dr.sign(o.private,z);let K=rse(d,_),G=Jf(T,!1),V={tag:"iq",attrs:{to:OA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":F.keyIndex.toString()},content:G}]}]};return{creds:{account:T,me:{id:I,name:c,lid:d},signalIdentities:[...i||[],K],platform:r?.attrs.name},reply:V}},Jf=(n,t)=>(n={...n},(!t||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),ne.ADVSignedDeviceIdentity.encode(n).finish());var yE=ze(jr(),1);var use=12,hse=Buffer.alloc(0),Ese=n=>{let t=new ArrayBuffer(use);return new DataView(t).setUint32(8,n),new Uint8Array(t)},AH=class{constructor(t,o){this.encKey=t,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(use)}encrypt(t){let o=this.writeCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,xl(t,this.encKey,this.iv,hse)}decrypt(t){let o=this.readCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,Yl(t,this.decKey,this.iv,hse)}},Cse=({keyPair:{private:n,public:t},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(Bse),A=a.byteLength===32?a:bh(a),r=A,s=A,g=A,c=0,I=!1,d=Buffer.alloc(0),B=null,f=!1,Q=null,y;e?(y=Buffer.alloc(7+e.byteLength+o.length),y.write("ED",0,"utf8"),y.writeUint8(0,2),y.writeUint8(1,3),y.writeUint8(e.byteLength>>16,4),y.writeUint16BE(e.byteLength&65535,5),y.set(e,7),y.set(o,7+e.byteLength)):y=Buffer.from(o);let m=q=>{B||(A=bh(Buffer.concat([A,q])))},T=q=>{if(B)return B.encrypt(q);let z=xl(q,s,Ese(c++),A);return m(z),z},_=q=>{if(B)return B.decrypt(q);let z=Yl(q,g,Ese(c++),A);return m(q),z},R=q=>{let z=Jn(Buffer.from(q),64,{salt:r,info:""});return[z.subarray(0,32),z.subarray(32)]},H=q=>{let[z,K]=R(q);r=z,s=K,g=K,c=0},F=async()=>{f=!0;let[q,z]=R(new Uint8Array(0));B=new AH(q,z),f=!1,i.trace("Noise handler transitioned to Transport state"),Q&&(i.trace({length:d.length},"Flushing buffered frames after transport ready"),await L(Q),Q=null)},L=async q=>{let z;for(;;){if(d.length<3||(z=d[0]<<16|d[1]<<8|d[2],d.length{m(q.ephemeral),H(Dr.sharedKey(n,q.ephemeral));let K=_(q.static);H(Dr.sharedKey(n,K));let G=_(q.payload),{intermediate:V,leaf:U}=ne.CertChain.decode(G);if(!U?.details||!U?.signature)throw new yE.Boom("invalid noise leaf certificate",{statusCode:400});if(!V?.details||!V?.signature)throw new yE.Boom("invalid noise intermediate certificate",{statusCode:400});let N=ne.CertChain.NoiseCertificate.Details.decode(V.details),{issuerSerial:k}=N,J=Dr.verify(N.key,U.details,U.signature),X=Dr.verify(tH.PUBLIC_KEY,V.details,V.signature);if(!J)throw new yE.Boom("noise certificate signature invalid",{statusCode:400});if(!X)throw new yE.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(k!==tH.SERIAL)throw new yE.Boom("certification match failed",{statusCode:400});let ae=T(z.public);return H(Dr.sharedKey(z.private,q.ephemeral)),ae},encodeFrame:q=>{B&&(q=B.encrypt(q));let z=q.byteLength,K=I?0:y.length,G=Buffer.allocUnsafe(K+3+z);return I||(G.set(y),I=!0),G[K]=z>>>16&255,G[K+1]=z>>>8&255,G[K+2]=z&255,G.set(q,K+3),G},decodeFrame:async(q,z)=>{if(f){d=Buffer.concat([d,q]),Q=z;return}d.length===0?d=Buffer.from(q):d=Buffer.concat([d,q]),await L(z)}}};import{pipeline as QVe}from"stream/promises";import{promisify as yVe}from"util";import{createInflate as mVe,inflate as SVe}from"zlib";var wVe=yVe(SVe),DVe=n=>{for(let t of n){let o=t.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(Tt(i)||wr(i)))return i}},OVe=async(n,t)=>{let o=await QE(n,"md-msg-hist",{options:t}),i=mVe(),e=[];i.on("data",r=>e.push(r)),await QVe(o,i);let a=Buffer.concat(e);return ne.HistorySync.decode(a)},bVe=(n,t)=>{let o=[],i=[],e=[],a=[];t?.trace({progress:n.progress},"processing history of type "+n.syncType?.toString());for(let A of n.phoneNumberToLidMappings||[])A.lidJid&&A.pnJid&&a.push({lid:A.lidJid,pn:A.pnJid});switch(n.syncType){case ne.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case ne.HistorySync.HistorySyncType.RECENT:case ne.HistorySync.HistorySyncType.FULL:case ne.HistorySync.HistorySyncType.ON_DEMAND:for(let A of n.conversations){i.push({id:A.id,name:A.displayName||A.name||A.username||void 0,username:A.username||void 0,lid:A.lidJid||A.accountLid||void 0,phoneNumber:A.pnJid||void 0});let r=A.id,s=qA(r)||Ea(r),g=Tt(r)||wr(r);if(s&&A.pnJid)a.push({lid:r,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:r});else if(s&&!A.pnJid){let I=DVe(A.messages||[]);I&&a.push({lid:r,pn:I})}let c=A.messages||[];delete A.messages;for(let I of c){let d=I.message;o.push(d),A.messages?.length||(A.messages=[{message:d}]),!d.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=qr(d.messageTimestamp)),(d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_BSP||d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_FB)&&d.messageStubParameters?.[0]&&i.push({id:d.key.participant||d.key.remoteJid,verifiedName:d.messageStubParameters?.[0]})}e.push(A)}break;case ne.HistorySync.HistorySyncType.PUSH_NAME:for(let A of n.pushnames)i.push({id:A.id,notify:A.pushname});break}return{chats:e,contacts:i,messages:o,lidPnMappings:a,pastParticipants:n.pastParticipants,syncType:n.syncType,progress:n.progress}},fse=async(n,t,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=ne.HistorySync.decode(await wVe(n.initialHistBootstrapInlinePayload)):i=await OVe(n,t),bVe(i,o)},jb=n=>(n?ya(n):void 0)?.protocolMessage?.historySyncNotification;var In=ze(jr(),1);var tg;(function(n){n.Chat="label_jid",n.Message="label_message"})(tg||(tg={}));var Qse=new wh;var yse=(n,t,o)=>{let i=[];if(!t)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=Tt(t),A=a?t:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:t,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&qA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:t}}),i},mse=(n,t)=>{for(let o of t)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var qf=n=>{let t=T$(n);return{indexKey:t.indexKey,valueEncryptionKey:t.valueEncryptionKey,valueMacKey:t.valueMacKey,snapshotMacKey:t.snapshotMacKey,patchMacKey:t.patchMacKey}},Sse=(n,t,o,i)=>{let e=n===ne.SyncdMutation.SyncdOperation.SET?1:2,a=typeof o=="string"?Buffer.from(o,"base64"):o,A=new Uint8Array(1+a.length);A[0]=e,A.set(a,1);let r=new Uint8Array(8);r[7]=A.length;let s=new Uint8Array(A.length+t.length+r.length);return s.set(A,0),s.set(t,A.length),s.set(r,A.length+t.length),qn(s,i,"sha512").subarray(0,32)},wse=n=>{let t=Buffer.alloc(8);return t.writeUint32BE(n,4),t},Dse=({indexValueMap:n,hash:t})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let r=Buffer.from(e).toString("base64"),s=n[r];if(A===ne.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[r]}else o.push(a),n[r]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=Qse.subtractThenAdd(t,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},rH=(n,t,o,i)=>{let e=Buffer.concat([n,wse(t),Buffer.from(o,"utf-8")]);return qn(e,i,"sha256")},Ose=(n,t,o,i,e)=>{let a=Buffer.concat([n,...t,wse(o),Buffer.from(i,"utf-8")]);return qn(a,e)},Jb=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),aH=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),iH=2,zf=n=>n?.data?.isMissingKey===!0,bse=(n,t)=>t>=iH||n?.name==="TypeError",Mse=async({type:n,index:t,syncAction:o,apiVersion:i,operation:e},a,A,r)=>{let s=a?await r(a):void 0;if(!s)throw new In.Boom(`myAppStateKey ("${a}") not present`,{data:{isMissingKey:!0}});let g=Buffer.from(a,"base64");A={...A,indexValueMap:{...A.indexValueMap}};let c=Buffer.from(JSON.stringify(t)),I=ne.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),d=ne.SyncActionData.encode(I).finish(),B=qf(s.keyData),f=L$(d,B.valueEncryptionKey),Q=Sse(e,f,g,B.valueMacKey),y=qn(c,B.indexKey),m=Dse(A);m.mix({indexMac:y,valueMac:Q,operation:e}),Object.assign(A,m.finish()),A.version+=1;let T=rH(A.hash,A.version,n,B.snapshotMacKey),_={patchMac:Ose(T,[Q],A.version,n,B.patchMacKey),snapshotMac:T,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([f,Q])},keyId:{id:g}}}]},R=y.toString("base64");return A.indexValueMap[R]={valueMac:Q},{patch:_,state:A}},_se=async(n,t,o,i,e)=>{let a=Dse(t),A=new Map;for(let s of n){let g="operation"in s?s.operation:ne.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,I;try{I=await r(c.keyId.id)}catch(T){if(zf(T))throw T;continue}let d=c.value.blob,B=d.subarray(0,-32),f=d.subarray(-32);if(e){let T=Sse(g,B,c.keyId.id,I.valueMacKey);if(Buffer.compare(T,f)!==0)continue}let Q;try{Q=F$(B,I.valueEncryptionKey)}catch{continue}let y=ne.SyncActionData.decode(Q);if(e){let T=qn(y.index,I.indexKey);if(Buffer.compare(T,c.index.blob)!==0)throw new In.Boom("HMAC index verification failed")}let m=Buffer.from(y.index).toString();i({syncAction:y,index:JSON.parse(m)}),a.mix({indexMac:c.index.blob,valueMac:f,operation:g})}return a.finish();async function r(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let I=await o(g);if(!I)throw new In.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let d=qf(I.keyData);return A.set(g,d),d}},MVe=async(n,t,o,i,e,a)=>{if(a){let r=Buffer.from(n.keyId.id).toString("base64"),s=await i(r);if(!s)throw new In.Boom(`failed to find key "${r}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=qf(s.keyData),c=n.mutations.map(d=>d.record.value.blob.slice(-32)),I=Ose(n.snapshotMac,c,qr(n.version.version),t,g.patchMacKey);if(Buffer.compare(I,n.patchMac)!==0)throw new In.Boom("Invalid patch mac")}return await _se(n.mutations,o,i,e,a)},Tse=async(n,t)=>{let o=le(n,"sync"),i=PA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=le(a,"patches"),r=PA(A||a,"patch"),s=le(a,"snapshot"),g=[],c=a.attrs.name,I=a.attrs.has_more_patches==="true",d;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=ne.ExternalBlobReference.decode(s.content),f=await Nse(B,t);d=ne.SyncdSnapshot.decode(f)}for(let{content:B}of r)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let f=ne.SyncdPatch.decode(B);f.version||(f.version={version:+a.attrs.version+1}),g.push(f)}e[c]={patches:g,hasMorePatches:I,snapshot:d}})),e},Nse=async(n,t)=>{let o=await QE(n,"md-app-state",{options:t}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},_Ve=async(n,t)=>{let o=await Nse(n,t);return ne.SyncdMutations.decode(o)},Rse=async(n,t,o,i,e=!0,a)=>{let A=Jb();A.version=qr(t.version.version);let r={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await _se(t.records,A,o,s?I=>{let d=I.syncAction.index?.toString();r[d]=I}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let I=Buffer.from(t.keyId.id).toString("base64"),d=await o(I);if(!d)throw new In.Boom(`failed to find key "${I}" to decode mutation`,{data:{isMissingKey:!0}});let B=qf(d.keyData),f=rH(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(t.mac,f)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:r}},oH=async(n,t,o,i,e,a,A,r=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of t){let{version:I,keyId:d,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:I},"downloading external patch");let m=await _Ve(c.externalMutations,e);A?.debug({name:n,version:I,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let f=qr(I.version);s.version=f;let Q=typeof a>"u"||f>a,y;try{y=await MVe(c,n,s,i,Q?m=>{let T=m.syncAction.index?.toString();g[T]=m}:()=>{},r)}catch(m){if(zf(m))throw m;A?.warn({name:n,version:f,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,r){let m=Buffer.from(d.id).toString("base64"),T=await i(m);if(!T)throw new In.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let _=qf(T.keyData),R=rH(s.hash,s.version,n,_.snapshotMacKey);if(Buffer.compare(B,R)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},kse=(n,t)=>{let o=ne.SyncdMutation.SyncdOperation,i=a=>{let A;return Array.isArray(a)?A={lastMessageTimestamp:a[a.length-1]?.messageTimestamp,messages:a?.length?a.map(s=>{if(!s.key?.id||!s.key?.remoteJid)throw new In.Boom("Incomplete key",{statusCode:400,data:s});if(Jr(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new In.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!qr(s.messageTimestamp))throw new In.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=CA(s.key.participant)),s}):void 0}:A=a,A},e;if("mute"in n)e={syncAction:{muteAction:{muted:!!n.mute,muteEndTimestamp:n.mute||void 0}},index:["mute",t],type:"regular_high",apiVersion:2,operation:o.SET};else if("archive"in n)e={syncAction:{archiveChatAction:{archived:!!n.archive,messageRange:i(n.lastMessages)}},index:["archive",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("markRead"in n)e={syncAction:{markChatAsReadAction:{read:n.markRead,messageRange:i(n.lastMessages)}},index:["markChatAsRead",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:r}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:r,messageTimestamp:a}},index:["deleteMessageForMe",t,A.id,A.fromMe?"1":"0","0"],type:"regular_high",apiVersion:3,operation:o.SET}}else if("clear"in n)e={syncAction:{clearChatAction:{messageRange:i(n.lastMessages)}},index:["clearChat",t,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",t],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",t],type:"critical_unblock_low",apiVersion:2,operation:n.contact?o.SET:o.REMOVE};else if("disableLinkPreviews"in n)e={syncAction:{privacySettingDisableLinkPreviewsAction:n.disableLinkPreviews||{}},index:["setting_disableLinkPreviews"],type:"regular",apiVersion:8,operation:o.SET};else if("star"in n){let a=n.star.messages[0];e={syncAction:{starAction:{starred:!!n.star.star}},index:["star",t,a.id,a.fromMe?"1":"0","0"],type:"regular_low",apiVersion:2,operation:o.SET}}else if("delete"in n)e={syncAction:{deleteChatAction:{messageRange:i(n.lastMessages)}},index:["deleteChat",t,"1"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pushNameSetting"in n)e={syncAction:{pushNameSetting:{name:n.pushNameSetting}},index:["setting_pushName"],type:"critical_block",apiVersion:1,operation:o.SET};else if("quickReply"in n)e={syncAction:{quickReplyAction:{count:0,deleted:n.quickReply.deleted||!1,keywords:[],message:n.quickReply.message||"",shortcut:n.quickReply.shortcut||""}},index:["quick_reply",n.quickReply.timestamp||String(Math.floor(Date.now()/1e3))],type:"regular",apiVersion:2,operation:o.SET};else if("addLabel"in n)e={syncAction:{labelEditAction:{name:n.addLabel.name,color:n.addLabel.color,predefinedId:n.addLabel.predefinedId,deleted:n.addLabel.deleted}},index:["label_edit",n.addLabel.id],type:"regular",apiVersion:3,operation:o.SET};else if("addChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[tg.Chat,n.addChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[tg.Chat,n.removeChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[tg.Message,n.addMessageLabel.labelId,t,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[tg.Message,n.removeMessageLabel.labelId,t,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new In.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},vse=(n,t,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:r},index:[s,g,c,I]}=n;if(r?.muteAction)t.emit("chats.update",[{id:g,muteEndTime:r.muteAction?.muted?qr(r.muteAction.muteEndTimestamp):null,conditional:d(g,void 0)}]);else if(r?.archiveChatAction||s==="archive"||s==="unarchive"){let f=r?.archiveChatAction,Q=f?f.archived:s==="archive",y=A?.unarchiveChats?f?.messageRange:void 0;t.emit("chats.update",[{id:g,archived:Q,conditional:d(g,y)}])}else if(r?.markChatAsReadAction){let f=r.markChatAsReadAction,Q=a&&f.read;t.emit("chats.update",[{id:g,unreadCount:Q?null:f?.read?0:-1,conditional:d(g,f?.messageRange)}])}else if(r?.deleteMessageForMeAction||s==="deleteMessageForMe")t.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:I==="1"}]});else if(r?.contactAction){let f=yse(r.contactAction,g,e);mse(t,f)}else if(r?.pushNameSetting){let f=r?.pushNameSetting?.name;f&&o?.name!==f&&t.emit("creds.update",{me:{...o,name:f}})}else if(r?.pinAction)t.emit("chats.update",[{id:g,pinned:r.pinAction?.pinned?qr(r.timestamp):null,conditional:d(g,void 0)}]);else if(r?.unarchiveChatsSetting){let f=!!r.unarchiveChatsSetting.unarchiveChats;t.emit("creds.update",{accountSettings:{unarchiveChats:f}}),e?.info(`archive setting updated => '${r.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=f)}else if(r?.starAction||s==="star"){let f=r?.starAction?.starred;typeof f!="boolean"&&(f=n.index[n.index.length-1]==="1"),t.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:I==="1"},update:{starred:f}}])}else if(r?.deleteChatAction||s==="deleteChat")a||t.emit("chats.delete",[g]);else if(r?.labelEditAction){let{name:f,color:Q,deleted:y,predefinedId:m}=r.labelEditAction;t.emit("labels.edit",{id:g,name:f,color:Q,deleted:y,predefinedId:m?String(m):void 0})}else r?.labelAssociationAction?t.emit("labels.association",{type:r.labelAssociationAction.labeled?"add":"remove",association:s===tg.Chat?{type:tg.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:tg.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):r?.localeSetting?.locale?t.emit("settings.update",{setting:"locale",value:r.localeSetting.locale}):r?.timeFormatAction?t.emit("settings.update",{setting:"timeFormat",value:r.timeFormatAction}):r?.pnForLidChatAction?r.pnForLidChatAction.pnJid&&t.emit("lid-mapping.update",{lid:g,pn:r.pnForLidChatAction.pnJid}):r?.privacySettingRelayAllCalls?t.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:r.privacySettingRelayAllCalls}):r?.statusPrivacy?t.emit("settings.update",{setting:"statusPrivacy",value:r.statusPrivacy}):r?.lockChatAction?t.emit("chats.lock",{id:g,locked:!!r.lockChatAction.locked}):r?.privacySettingDisableLinkPreviewsAction?t.emit("settings.update",{setting:"disableLinkPreviews",value:r.privacySettingDisableLinkPreviewsAction}):r?.notificationActivitySettingAction?.notificationActivitySetting?t.emit("settings.update",{setting:"notificationActivitySetting",value:r.notificationActivitySettingAction.notificationActivitySetting}):r?.lidContactAction?t.emit("contacts.upsert",[{id:g,name:r.lidContactAction.fullName||r.lidContactAction.firstName||r.lidContactAction.username||void 0,username:r.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):r?.privacySettingChannelsPersonalisedRecommendationAction?t.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:r.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function d(f,Q){return a?y=>{let m=y.historySets.chats[f]||y.chatUpserts[f];if(m)return Q?B(m,Q):!0}:void 0}function B(f,Q){let y=Number(Q?.lastMessageTimestamp||Q?.lastSystemMessageTimestamp||0),m=Number(f?.lastMessageRecvTimestamp||0);return y>=m}};var TVe=class{_eventListeners;_maxListeners;_logger;_throwOnEmitError=!1;_throwOnEmptyListeners=!1;_errorEvent="error";constructor(n){this._eventListeners=new Map,this._maxListeners=100,this._logger=n?.logger,n?.throwOnEmitError!==void 0&&(this._throwOnEmitError=n.throwOnEmitError),n?.throwOnEmptyListeners!==void 0&&(this._throwOnEmptyListeners=n.throwOnEmptyListeners)}get logger(){return this._logger}set logger(n){this._logger=n}get throwOnEmitError(){return this._throwOnEmitError}set throwOnEmitError(n){this._throwOnEmitError=n}get throwOnEmptyListeners(){return this._throwOnEmptyListeners}set throwOnEmptyListeners(n){this._throwOnEmptyListeners=n}once(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let t=this._eventListeners.get(n);return t?t.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,t){let o=this._eventListeners.get(n)??[];return o.unshift(t),this._eventListeners.set(n,o),this}prependOnceListener(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,t){return this.on(n,t),this}on(n,t){this._eventListeners.has(n)||this._eventListeners.set(n,[]);let o=this._eventListeners.get(n);return o&&(o.length>=this._maxListeners&&console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${o.length+1} ${n} listeners added. Use setMaxListeners() to increase limit.`),o.push(t)),this}removeListener(n,t){return this.off(n,t),this}off(n,t){let o=this._eventListeners.get(n)??[],i=o.indexOf(t);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...t){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...t),o=!0;if(n===this._errorEvent){let e=t[0]instanceof Error?t[0]:new Error(`${t[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,t),o}listeners(n){return this._eventListeners.get(n)??[]}removeAllListeners(n){return n!==void 0?this._eventListeners.delete(n):this._eventListeners.clear(),this}setMaxListeners(n){this._maxListeners=n;for(let t of this._eventListeners.values())t.length>n&&t.splice(n)}getAllListeners(){let n=[];for(let t of this._eventListeners.values())n=[...n,...t];return n}sendLog(n,t){if(!this._logger)return;let o;switch(typeof t=="string"?o=t:Array.isArray(t)&&t.length>0&&t[0]instanceof Error?o=t[0].message:t instanceof Error?o=t.message:Array.isArray(t)&&t.length>0&&typeof t[0]?.message=="string"?o=t[0].message:o=JSON.stringify(t),n){case"error":{this._logger.error?.(o,{event:n,data:t});break}case"warn":{this._logger.warn?.(o,{event:n,data:t});break}case"trace":{this._logger.trace?.(o,{event:n,data:t});break}case"debug":{this._logger.debug?.(o,{event:n,data:t});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:t});break}default:{this._logger.info?.(o,{event:n,data:t});break}}}},OI=class extends TVe{_hooks;_throwOnHookError=!1;_enforceBeforeAfter=!1;_deprecatedHooks;_allowDeprecated=!0;constructor(n){super({logger:n?.logger,throwOnEmitError:n?.throwOnEmitError,throwOnEmptyListeners:n?.throwOnEmptyListeners}),this._hooks=new Map,this._deprecatedHooks=n?.deprecatedHooks?new Map(n.deprecatedHooks):new Map,n?.throwOnHookError!==void 0?this._throwOnHookError=n.throwOnHookError:n?.throwHookErrors!==void 0&&(this._throwOnHookError=n.throwHookErrors),n?.enforceBeforeAfter!==void 0&&(this._enforceBeforeAfter=n.enforceBeforeAfter),n?.allowDeprecated!==void 0&&(this._allowDeprecated=n.allowDeprecated)}get hooks(){return this._hooks}get throwHookErrors(){return this._throwOnHookError}set throwHookErrors(n){this._throwOnHookError=n}get throwOnHookError(){return this._throwOnHookError}set throwOnHookError(n){this._throwOnHookError=n}get enforceBeforeAfter(){return this._enforceBeforeAfter}set enforceBeforeAfter(n){this._enforceBeforeAfter=n}get deprecatedHooks(){return this._deprecatedHooks}set deprecatedHooks(n){this._deprecatedHooks=n}get allowDeprecated(){return this._allowDeprecated}set allowDeprecated(n){this._allowDeprecated=n}validateHookName(n){if(this._enforceBeforeAfter){let t=n.trim().toLocaleLowerCase();if(!t.startsWith("before")&&!t.startsWith("after"))throw new Error(`Hook event "${n}" must start with "before" or "after" when enforceBeforeAfter is enabled`)}}checkDeprecatedHook(n){if(this._deprecatedHooks.has(n)){let t=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${t?`: ${t}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,t){this.onHookEntry({event:n,handler:t})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let t=this._hooks.get(n.event);t?t.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,t){this.onHookEntry({event:n,handler:t})}onHooks(n){for(let t of n)this.onHook(t.event,t.handler)}prependHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(t):this._hooks.set(n,[t])}prependOnceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.prependHook(n,o)}onceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.onHook(n,o)}removeHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let t of n)this.removeHook(t.event,t.handler)}async hook(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){for(let i of o)if(i.constructor.name!=="AsyncFunction")try{i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...t){await this.hook(`before:${n}`,...t)}async afterHook(n,...t){await this.hook(`after:${n}`,...t)}async callHook(n,...t){await this.hook(n,...t)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var NVe=class{_enabled=!0;_maxSize=4e3;_store=new Map;_keys=[];constructor(n){n?.enabled!==void 0&&(this._enabled=n.enabled),n?.maxSize!==void 0&&(this._maxSize=n.maxSize)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get maxSize(){return this._maxSize}set maxSize(n){this._maxSize=n}get store(){return this._store}get size(){return this._store.size}get(n){return this._store.get(n)}set(n,t){if(this._enabled){if(this._store.has(n)){this._store.set(n,t);return}if(this._store.size>=this._maxSize){let o=this._keys.shift();o&&this._store.delete(o)}this._keys.push(n),this._store.set(n,t)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},RVe=class{get name(){return"crc32"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;t=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}let o=3988292384,i=4294967295;for(let a=0;a>>1^o&-(i&1)}return i=(i^4294967295)>>>0,i.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},qb=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let t=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}},kVe=class{get name(){return"djb2"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let o=5381;for(let e=0;e>>0;return o.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},vVe=class{get name(){return"fnv1"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;t=new Uint8Array(A.buffer,A.byteOffset,A.byteLength)}let o=2166136261,i=16777619,e=o;for(let A=0;A>>0;return e.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},PVe=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;t=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=t.length,a=Math.floor(e/4),A=this._seed;for(let c=0;c>>16,A=this._imul(A,2246822507),A^=A>>>13,A=this._imul(A,3266489909),A^=A>>>16,A=A>>>0,A.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}_imul(n,t){if(Math.imul)return Math.imul(n,t);let o=n>>>16&65535,i=n&65535,e=t>>>16&65535,a=t&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,t){return n<>>32-t}},GVe=class{_providers=new Map;_getFuzzy=!0;constructor(n){n?.providers&&this.loadProviders(n?.providers),n?.getFuzzy!==void 0&&(this._getFuzzy=!!n?.getFuzzy)}loadProviders(n){for(let t of n)this._providers.set(t.name,t)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,t){let o=t?.fuzzy??this._getFuzzy;n=n.trim();let i=this._providers.get(n);return i===void 0&&o===!0&&(n=n.toLowerCase(),i=this._providers.get(n)),i===void 0&&o===!0&&(n=n.replaceAll("-",""),i=this._providers.get(n)),i}add(n){this._providers.set(n.name,n)}remove(n){return this._providers.delete(n)}},nH=class extends OI{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new GVe;_defaultAlgorithm="SHA-256";_defaultAlgorithmSync="djb2";_cache;constructor(n){super(n),n?.parse&&(this._parse=n.parse),n?.stringify&&(this._stringify=n.stringify),n?.defaultAlgorithm&&(this._defaultAlgorithm=n.defaultAlgorithm),n?.defaultAlgorithmSync&&(this._defaultAlgorithmSync=n.defaultAlgorithmSync),this._cache=new NVe(n?.cache),this.loadProviders(n?.providers,{includeBase:n?.includeBase??!0})}get parse(){return this._parse}set parse(n){this._parse=n}get stringify(){return this._stringify}set stringify(n){this._stringify=n}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return this._providers.names}get defaultAlgorithm(){return this._defaultAlgorithm}set defaultAlgorithm(n){this._defaultAlgorithm=n}get defaultAlgorithmSync(){return this._defaultAlgorithmSync}set defaultAlgorithmSync(n){this._defaultAlgorithmSync=n}get cache(){return this._cache}async toHash(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithm,maxLength:t?.maxLength};await this.beforeHook("toHash",o);let i=this._stringify(o.data),e=`${o.algorithm}:${i}`;if(this._cache.enabled){let c=this._cache.get(e);if(c!==void 0){let I=c;t?.maxLength&&I.length>t.maxLength&&(I=I.substring(0,t.maxLength));let d={hash:I,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",d),d.hash}}let A=new TextEncoder().encode(i),r=this._providers.get(o.algorithm);r||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),r=new qb({algorithm:this._defaultAlgorithm}));let s=await r.toHash(A);this._cache.enabled&&this._cache.set(e,s),t?.maxLength&&s.length>t?.maxLength&&(s=s.substring(0,t.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}toHashSync(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithmSync,maxLength:t?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let I=this._cache.get(a);if(I!==void 0){let d=I;t?.maxLength&&d.length>t.maxLength&&(d=d.substring(0,t.maxLength));let B={hash:d,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let r=new TextEncoder().encode(e),s=this._providers.get(i);if(!s&&(this.emit("warn",`Invalid algorithm '${i}' not found. Falling back to default algorithm '${this._defaultAlgorithmSync}'.`),s=this._providers.get(this._defaultAlgorithmSync),!s))throw new Error(`Hash provider '${this._defaultAlgorithmSync}' (default) not found`);if(!s.toHashSync)throw new Error(`Hash provider '${i}' does not support synchronous hashing. Use toHash() instead or choose a different algorithm (djb2, fnv1, murmur, crc32).`);let g=s.toHashSync(r);this._cache.enabled&&this._cache.set(a,g),t?.maxLength&&g.length>t?.maxLength&&(g=g.substring(0,t.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}loadProviders(n,t={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);t.includeBase&&(this.providers.add(new qb({algorithm:"SHA-256"})),this.providers.add(new qb({algorithm:"SHA-384"})),this.providers.add(new qb({algorithm:"SHA-512"})),this.providers.add(new RVe),this.providers.add(new kVe),this.providers.add(new vVe),this.providers.add(new PVe))}};var cH=n=>{let t;if(n!==void 0){if(typeof n=="number")t=n;else{if(typeof n!="string")return;if(n=n.trim(),Number.isNaN(Number(n))){let o=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(n);if(!o)throw new Error(`Unsupported time format: "${n}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,e]=o,a=Number.parseFloat(i);switch(e.toLowerCase()){case"ms":t=a;break;case"s":t=a*1e3;break;case"m":t=a*1e3*60;break;case"h":t=a*1e3*60*60;break;case"hr":t=a*1e3*60*60;break;case"d":t=a*1e3*60*60*24;break;default:t=Number(n)}}else t=Number(n)}return t}},pd=(n,t)=>{t??=new Date;let o=cH(n);return o===void 0?t.getTime():t.getTime()+o};var Vf=(function(n){return n.SHA256="SHA-256",n.SHA384="SHA-384",n.SHA512="SHA-512",n.DJB2="djb2",n.FNV1="fnv1",n.MURMER="murmer",n.CRC32="crc32",n})({});function sH(n,t={algorithm:"djb2",serialize:JSON.stringify}){let o=t?.algorithm??"djb2",i=(t?.serialize??JSON.stringify)(n);return new nH().toHashSync(i,{algorithm:o})}function Pse(n,t={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=t?.min??0,i=t?.max??10,e=t?.algorithm??"djb2",a=t?.serialize??JSON.stringify,A=t?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let r=a(n);return new nH().toNumberSync(r,{algorithm:e,min:o,max:i,hashLength:A})}function IH(n,t){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=t;return(...A)=>{let r=FVe(n,A,{keyPrefix:i,serialize:a});t.createKey&&(r=t.createKey(n,A,t));let s=e.get(r);if(s===void 0)try{s=n(...A),e.set(r,s,o)}catch(g){e.emit("error",g),t.cacheErrors&&e.set(r,g,o)}return s}}function lH(n,t,o){let i=typeof n=="function"?n(o):n,e;try{e=o.cache.get(i)}catch(a){if(o.cache.emit("error",a),o.throwErrors===!0||o.throwErrors==="store")throw a}if(e===void 0)try{try{e=t()}catch(a){throw new zb(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new zb(a,"store")}}catch(a){let A=a instanceof zb?a.context:void 0,r=a instanceof zb?a.error:a;if(o.cache.emit("error",r),o.cacheErrors&&A==="function")try{o.cache.set(i,r,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw r}return e}function FVe(n,t,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${sH(t,{serialize:e})}`:`${n.name}::${sH(t,{serialize:e})}`}var zb=class{error;context;constructor(n,t){this.error=n,this.context=t}};var bI=class{_counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0};_vsize=0;_ksize=0;_enabled=!1;_lastUpdated;_lastReset;_subscriptions=[];_trackedKeys=new Map;_trackKeys=!1;_maxTrackedKeys;constructor(n){n?.enabled&&(this._enabled=n.enabled),n?.trackKeys&&(this._trackKeys=n.trackKeys),n?.maxTrackedKeys!==void 0&&(this._maxTrackedKeys=n.maxTrackedKeys),n?.emitter&&n?.eventMap&&this.subscribe(n.emitter,n.eventMap)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get trackKeys(){return this._trackKeys}set trackKeys(n){this._trackKeys=n}get maxTrackedKeys(){return this._maxTrackedKeys}set maxTrackedKeys(n){this._maxTrackedKeys=n}get trackedKeys(){return this._trackedKeys}get hits(){return this._counters.hits}get misses(){return this._counters.misses}get gets(){return this._counters.gets}get sets(){return this._counters.sets}get deletes(){return this._counters.deletes}get clears(){return this._counters.clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._counters.count}get hitRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.hits/n}get missRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.misses/n}get lastUpdated(){return this._lastUpdated}get lastReset(){return this._lastReset}increment(n,t=1){this._enabled&&(this._counters[n]+=t,this.touch())}decrement(n,t=1){this._enabled&&(this._counters[n]-=t,this.touch())}incrementHits(n=1){this.increment("hits",n)}incrementMisses(n=1){this.increment("misses",n)}incrementGets(n=1){this.increment("gets",n)}incrementSets(n=1){this.increment("sets",n)}incrementDeletes(n=1){this.increment("deletes",n)}incrementClears(n=1){this.increment("clears",n)}incrementVSize(n){this._enabled&&(this._vsize+=this.roughSizeOfObject(n),this.touch())}decreaseVSize(n){this._enabled&&(this._vsize=Math.max(0,this._vsize-this.roughSizeOfObject(n)),this.touch())}incrementKSize(n){this._enabled&&(this._ksize+=this.roughSizeOfString(n),this.touch())}decreaseKSize(n){this._enabled&&(this._ksize=Math.max(0,this._ksize-this.roughSizeOfString(n)),this.touch())}incrementCount(n=1){this.increment("count",n)}decreaseCount(n=1){this._enabled&&(this._counters.count=Math.max(0,this._counters.count-n),this.touch())}setCount(n){this._enabled&&(this._counters.count=n,this.touch())}roughSizeOfString(n){return n.length*2}roughSizeOfObject(n){let t=[],o=[n],i=0;for(;o.length>0;){let e=o.pop();if(typeof e=="boolean")i+=4;else if(typeof e=="string")i+=e.length*2;else if(typeof e=="number")i+=8;else{if(e==null){i+=4;continue}if(t.includes(e))continue;t.push(e);for(let a in e)i+=a.length*2,o.push(e[a])}}return i}enable(){this._enabled=!0}disable(){this._enabled=!1}clear(){this.reset()}reset(){this._counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0},this._vsize=0,this._ksize=0,this._trackedKeys.clear(),this._lastReset=Date.now(),this._lastUpdated=void 0}resetStoreValues(){this._vsize=0,this._ksize=0,this._counters.count=0}toJSON(){return{enabled:this._enabled,hits:this._counters.hits,misses:this._counters.misses,gets:this._counters.gets,sets:this._counters.sets,deletes:this._counters.deletes,clears:this._counters.clears,vsize:this._vsize,ksize:this._ksize,count:this._counters.count,hitRate:this.hitRate,missRate:this.missRate,trackedKeys:this._trackedKeys.size,lastUpdated:this._lastUpdated,lastReset:this._lastReset}}snapshot(){return this.toJSON()}recordKey(n,t,o=1){if(!this._enabled||!this._trackKeys)return;let i=this._trackedKeys.get(n);i||(i={hits:0,misses:0,gets:0,sets:0,deletes:0},this._trackedKeys.set(n,i),this.pruneTrackedKeys(n)),i[t]+=o,this.touch()}mostUsedKeys(n=100,t){return this.sortedKeyEntries(t,"desc").slice(0,n)}leastUsedKeys(n=100,t){return this.sortedKeyEntries(t,"asc").slice(0,n)}keyStats(n){let t=this._trackedKeys.get(n);return t?this.toKeyEntry(n,t):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,t){let o=t.hits+t.misses;return{key:n,count:this.totalOf(t),hits:t.hits,misses:t.misses,gets:t.gets,sets:t.sets,deletes:t.deletes,hitRate:o===0?0:t.hits/o}}sortedKeyEntries(n,t){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=t==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,r=n?a[n]:a.count;return A!==r?(A-r)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=t)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,t){for(let[o,i]of Object.entries(t)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let t=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){t.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=t}applyEvent(n,t){if(this._enabled){if(typeof n=="function"){n(this,...t);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var LVe=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},dH=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let t=new LVe(n);this.head?(t.next=this.head,this.head.prev=t,this.head=t):this.head=this.tail=t,this.nodesMap.set(n,t)}moveToFront(n){let t=this.nodesMap.get(n);if(!t||this.head===t)return;t.prev&&(t.prev.next=t.next);t.next&&(t.next.prev=t.prev);t===this.tail&&(this.tail=t.prev),t.prev=void 0,t.next=this.head;this.head&&(this.head.prev=t),this.head=t,this.tail??=t}getOldest(){return this.tail?this.tail.value:void 0}removeOldest(){if(!this.tail)return;let n=this.tail.value;return this.tail.prev?(this.tail=this.tail.prev,this.tail.next=void 0):this.head=this.tail=void 0,this.nodesMap.delete(n),n}remove(n){let t=this.nodesMap.get(n);return t?(t.prev?t.prev.next=t.next:(this.head=t.next,this.head&&(this.head.prev=void 0)),t.next?t.next.prev=t.prev:(this.tail=t.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var Gse=16777216,pH=class extends OI{_lru=new dH;_storeHashSize=16;_storeHashAlgorithm=Vf.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new bI({enabled:!1});constructor(n){super(),n?.ttl&&this.setTtl(n.ttl),n?.maxTtl!==void 0&&this.setMaxTtl(n.maxTtl),n?.useClone!==void 0&&(this._useClone=n.useClone),n?.stats&&(this._stats.enabled=n.stats),n?.storeHashSize&&n.storeHashSize>0&&(this._storeHashSize=n.storeHashSize),n?.lruSize&&(n.lruSize>16777216?this.emit("error",new Error(`LRU size cannot be larger than ${Gse} due to Map limitations.`)):this._lruSize=n.lruSize),n?.checkInterval&&(this._checkInterval=n.checkInterval),n?.storeHashAlgorithm&&(this._storeHashAlgorithm=n.storeHashAlgorithm),this._store=Array.from({length:this._storeHashSize},()=>new Map),this.startIntervalCheck()}get ttl(){return this._ttl}set ttl(n){this.setTtl(n)}get maxTtl(){return this._maxTtl}set maxTtl(n){this.setMaxTtl(n)}get useClone(){return this._useClone}set useClone(n){this._useClone=n}get lruSize(){return this._lruSize}set lruSize(n){if(n>16777216){this.emit("error",new Error(`LRU size cannot be larger than ${Gse} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new dH;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let t of this._store)n+=t.size;return n}get stats(){return this._stats}get storeHashSize(){return this._storeHashSize}set storeHashSize(n){n!==this._storeHashSize&&(this._storeHashSize=n,this._store=Array.from({length:this._storeHashSize},()=>new Map),this._stats.enabled&&this._stats.resetStoreValues())}get storeHashAlgorithm(){return this._storeHashAlgorithm}set storeHashAlgorithm(n){this._storeHashAlgorithm=n}get keys(){let n=[];for(let t of this._store)for(let o of t.keys()){let i=t.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),t.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let t of this._store)for(let o of t.values()){if(this.hasExpired(o)){this.recordExpiration(o),t.delete(o.key),this.lruRemove(o.key);continue}n.push(o)}return n.values()}get store(){return this._store}get(n){this.hookSync("BEFORE_GET",n);let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}this.lruMoveToFront(n);let i;return this._useClone?i=this.clone(o.value):i=o.value,this.recordRead(!0),this.hookSync("AFTER_GET",{key:n,result:i}),i}getMany(n){this.hookSync("BEFORE_GET_MANY",n);let t=[];for(let o of n)t.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:t}),t}getRaw(n){let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let t=[];for(let o of n)t.push(this.getRaw(o));return t}set(n,t,o){let i={key:n,value:t,ttl:o};this.hookSync("BEFORE_SET",i);let e=this.getStore(i.key),a,A=i.ttl;if(A!==void 0||this._ttl!==void 0)if(typeof A=="object"){if(A.expire&&(a=typeof A.expire=="number"?A.expire:A.expire.getTime()),A.ttl){let s=pd(A.ttl);s!==void 0&&(a=s)}}else{let s=pd(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=pd(this._maxTtl);(a===void 0||a>s)&&(a=s)}if(this._lruSize>0){if(e.has(i.key))this.lruMoveToFront(i.key);else if(this.lruAddToFront(i.key),this._lru.size>this._lruSize){let s=this._lru.getOldest();s&&(this._lru.removeOldest(),this.delete(s))}}if(this._stats.enabled){let s=e.get(i.key);s?this._stats.decreaseVSize(s.value):(this._stats.incrementKSize(i.key),this._stats.incrementCount()),this._stats.incrementVSize(i.value),this._stats.incrementSets()}let r={key:i.key,value:i.value,expires:a};e.set(i.key,r),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let t of n)this.set(t.key,t.value,t.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let t=[];for(let o of n){let i=this.get(o);t.push(!!i)}return t}take(n){let t=this.get(n);if(t)return this.delete(n),t}takeMany(n){let t=[];for(let o of n)t.push(this.take(o));return t}delete(n){this.hookSync("BEFORE_DELETE",n);let t=this.getStore(n);if(this._stats.enabled){let o=t.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}t.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let t of n)this.delete(t);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new dH,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let t=this.getKeyStoreHash(n);return this._store[t]||=new Map,this._store[t]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):Pse(n,{min:0,max:this._storeHashSize-1,algorithm:this._storeHashAlgorithm})}clone(n){return this.isPrimitive(n)?n:structuredClone(n)}lruAddToFront(n){this._lruSize!==0&&this._lru.addToFront(n)}lruMoveToFront(n){this._lruSize!==0&&this._lru.moveToFront(n)}lruRemove(n){this._lruSize!==0&&this._lru.remove(n)}lruResize(){for(;this._lru.size>this._lruSize;){let n=this._lru.getOldest();n&&(this._lru.removeOldest(),this.delete(n))}}checkExpiration(){for(let n of this._store)for(let t of n.values())t.expires&&Date.now()>t.expires&&(this.recordExpiration(t),n.delete(t.key),this.lruRemove(t.key))}startIntervalCheck(){if(this._checkInterval>0){this._interval&&clearInterval(this._interval),this._interval=setInterval(()=>{this.checkExpiration()},this._checkInterval).unref()}}stopIntervalCheck(){this._interval&&clearInterval(this._interval),this._interval=0,this._checkInterval=0}wrap(n,t){return IH(n,{ttl:t?.ttl??this._ttl,keyPrefix:t?.keyPrefix,createKey:t?.createKey,cache:this})}getOrSet(n,t,o){return lH(n,t,{cache:this,ttl:o?.ttl??this._ttl,cacheErrors:o?.cacheErrors,throwErrors:o?.throwErrors})}recordRead(n){this._stats.enabled&&(n?this._stats.incrementHits():this._stats.incrementMisses(),this._stats.incrementGets())}recordExpiration(n){this._stats.enabled&&(this._stats.decreaseKSize(n.key),this._stats.decreaseVSize(n.value),this._stats.decreaseCount())}isPrimitive(n){return n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}setTtl(n){typeof n=="string"||n===void 0?this._ttl=n:n>0?this._ttl=n:this._ttl=void 0}setMaxTtl(n){typeof n=="string"||n===void 0?this._maxTtl=n:n>0?this._maxTtl=n:this._maxTtl=void 0}hasExpired(n){return!!(n.expires&&Date.now()>n.expires)}};var JVe=class extends OI{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new bI({enabled:!0});_cacheable=new pH;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,t,o=0){if(typeof n!="string"&&typeof n!="number")throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`",n);if(o&&typeof o!="number"&&typeof o!="string")throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.",this.formatKey(n));let i=this.formatKey(n),e=0;this.options.stdTTL&&(e=this.getExpirationTimestamp(this.options.stdTTL)),o&&(e=this.getExpirationTimestamp(o));let a=0;if(e&&e>0&&(a=e),this.options.maxKeys){let{maxKeys:A}=this.options;if(A>-1&&this.store.size>=A)throw this.createError("Cache max keys amount exceeded",this.formatKey(n))}return this.store.set(i,{key:i,value:t,ttl:a}),this.emit("set",i,t,e),this._stats.incrementKSize(i),this._stats.incrementVSize(t),this._stats.setCount(this.store.size),!0}mset(n){if(!Array.isArray(n))throw this.createError("The keys argument has to be an array.");for(let t of n)this.set(t.key,t.value,t.ttl);return!0}get(n){let t=this.store.get(this.formatKey(n));if(t){if(t.ttl>0){if(t.ttl0){let n=this.options.checkperiod*1e3;this.intervalId=setInterval(()=>{this.checkData()},n).unref();return}this.intervalId=0}stopInterval(){this.intervalId!==0&&(clearInterval(this.intervalId),this.intervalId=0)}formatKey(n){return n.toString()}getExpirationTimestamp(n){if(typeof n=="string")return pd(n);let t=Date.now(),o=n*1e3;return t+o}checkData(){for(let[n,t]of this.store.entries())t.ttl>0&&t.ttl{let a={resolve:i,reject:e,weight:t,priority:o},A=Lse(this._queue,r=>o<=r.priority);A===-1&&t<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(t){return zVe(this,arguments,void 0,function*(o,i=1,e=0){let[a,A]=yield this.acquire(i,e);try{return yield o(a)}finally{A()}})}waitForUnlock(t=1,o=0){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return this._couldLockImmediately(t,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),VVe(this._weightedWaiters[t-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatchQueue()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatchQueue()}cancel(){this._queue.forEach(t=>t.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(t){let o=this._value;this._value-=t.weight,t.resolve([o,this._newReleaser(t.weight)])}_newReleaser(t){let o=!1;return()=>{o||(o=!0,this.release(t))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let t=this._value;t>0;t--){let o=this._weightedWaiters[t-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[t-1]=[])}else{let t=this._queue[0].priority;for(let o=this._value;o>0;o--){let i=this._weightedWaiters[o-1];if(!i)continue;let e=i.findIndex(a=>a.priority<=t);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(t,o){return(this._queue.length===0||this._queue[0].priorityt.priority<=i.priority);n.splice(o+1,0,t)}function Lse(n,t){for(let o=n.length-1;o>=0;o--)if(t(n[o]))return o;return-1}var WVe=function(n,t,o,i){function e(a){return a instanceof o?a:new o(function(A){A(a)})}return new(o||(o=Promise))(function(a,A){function r(c){try{g(i.next(c))}catch(I){A(I)}}function s(c){try{g(i.throw(c))}catch(I){A(I)}}function g(c){c.done?a(c.value):e(c.value).then(r,s)}g((i=i.apply(n,t||[])).next())})},ic=class{constructor(t){this._semaphore=new hH(1,t)}acquire(){return WVe(this,arguments,void 0,function*(t=0){let[,o]=yield this._semaphore.acquire(1,t);return o})}runExclusive(t,o=0){return this._semaphore.runExclusive(()=>t(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(t=0){return this._semaphore.waitForUnlock(1,t)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as AWe}from"crypto";var uH=ze(Hse(),1);var CH=class n extends Error{name="TimeoutError";constructor(t,o){super(t,o),Error.captureStackTrace?.(this,n)}},Kse=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function BH(n,t){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=t,r,s,c=new Promise((I,d)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){d(Kse(A));return}if(A&&(s=()=>{d(Kse(A))},A.addEventListener("abort",s,{once:!0})),n.then(I,d),o===Number.POSITIVE_INFINITY)return;let B=new CH;r=a.setTimeout.call(void 0,()=>{if(i){try{I(i())}catch(f){d(f)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?I():e instanceof Error?d(e):(B.message=e??`Promise timed out after ${o} milliseconds`,d(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,r),r=void 0},c}function fH(n,t,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],t)<=0?(i=++A,e-=a+1):e=a}return i}var $Ve=100,mE=class{#e=[];#A=0;enqueue(t,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:t};if(a===0){this.#e.length=0,this.#A=0,this.#e.push(A);return}if(this.#e.at(-1).priority>=i){this.#e.push(A);return}this.#t();let r=fH(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(r,0,A)}setPriority(t,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===t);if(i===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:t})}remove(t){let o=this.#e.findIndex((i,e)=>e$Ve&&this.#A>this.#e.length/2&&this.#t(),t?.run}filter(t){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);if(t.strict&&t.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(t.strict&&t.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=t.carryoverIntervalCount??t.carryoverConcurrencyCount??!1,this.#A=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#r=t.intervalCap,this.#i=t.interval,this.#d=t.strict,this.#I=new t.queueClass,this.#p=t.queueClass,this.concurrency=t.concurrency,t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);this.timeout=t.timeout,this.#C=t.autoStart===!1,this.#J()}#S(t){for(;this.#g=this.#i)this.#g++;else break}(this.#g>100&&this.#g>this.#c.length/2||this.#g===this.#c.length)&&(this.#c=this.#c.slice(this.#g),this.#g=0)}#m(t){this.#d?this.#c.push(t):this.#t++}#y(){this.#d?this.#c.length>this.#g&&this.#c.pop():this.#t>0&&this.#t--}#b(){return this.#c.length-this.#g}get#h(){return this.#A?!0:this.#d?this.#b()=this.#r){let i=this.#c[this.#g],e=this.#i-(t-i);return this.#T(e),!0}return!1}if(this.#n===void 0){let o=this.#a-t;if(o<0)this.#t=this.#e?this.#E:0;else return this.#T(o),!0}return!1}#T(t){this.#s===void 0&&(this.#s=setTimeout(()=>{this.#D()},t))}#M(){this.#n&&(clearInterval(this.#n),this.#n=void 0)}#P(){this.#s&&(clearTimeout(this.#s),this.#s=void 0)}#N(){if(this.#I.size===0){if(this.#M(),this.emit("empty"),this.#E===0){if(this.#P(),this.#d&&this.#g>0){let o=Date.now();this.#S(o)}this.emit("idle")}return!1}let t=!1;if(!this.#C){let o=Date.now(),i=!this.#w(o);if(this.#h&&this.#R){let e=this.#I.dequeue();this.#A||(this.#m(o),this.#x()),i&&this.#F(),this.emit("active"),e(),t=!0}}return t}#F(){this.#A||this.#n!==void 0||this.#d||(this.#n=setInterval(()=>{this.#k()},this.#i),this.#a=Date.now()+this.#i)}#k(){this.#d||(this.#n!==void 0&&(this.#t===0&&this.#E===0?this.#M():this.#a=Date.now()+this.#i),this.#t=this.#e?this.#E:0),this.#K(),this.#x()}#K(){for(;this.#N(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#K()}setPriority(t,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#I.setPriority(t,o)}async add(t,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#B++).toString()},o.timeout!==void 0&&!(Number.isFinite(o.timeout)&&o.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${o.timeout}\` (${typeof o.timeout})`);return new Promise((i,e)=>{let a=Symbol(`task-${o.id}`),A=()=>{},r=async()=>{A(),this.#E++,this.#f.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(d){throw this.#G(),this.#f.delete(a),d}let c=t({signal:o.signal});if(o.timeout!==void 0&&(c=BH(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#E} running, ${this.#I.size} waiting)`})),o.signal){let{signal:d}=o;c=Promise.race([c,new Promise((B,f)=>{g=()=>{f(d.reason)},d.addEventListener("abort",g,{once:!0})})])}let I=await c;i(I),this.emit("completed",I)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#f.delete(a),queueMicrotask(()=>{this.#_()})}};this.#I.enqueue(r,o);let s=()=>{if(this.#I instanceof mE){this.#I.remove(r);return}this.#I.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#N(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#Q.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#Q.add(A)}this.emit("add"),this.#N()})}async addAll(t,o){return Promise.all(t.map(async i=>this.add(i,o)))}start(){return this.#C?(this.#C=!1,this.#K(),this):this}pause(){this.#C=!0}clear(){for(let t of this.#Q)t();this.#I=new this.#p,this.#M(),this.#L(),this.emit("empty"),this.#E===0&&(this.#P(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#I.size!==0&&await this.#U("empty")}async onSizeLessThan(t){this.#I.sizethis.#I.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#U(t,o){let i=Array.isArray(t)?t:[t];return new Promise(e=>{let a=()=>{if(!(o&&!o())){for(let A of i)this.off(A,a);e()}};for(let A of i)this.on(A,a)})}get size(){return this.#I.size}sizeBy(t){return this.#I.filter(t).length}get pending(){return this.#E}get isPaused(){return this.#C}#J(){this.#A||(this.on("add",()=>{this.#I.size>0&&this.#x()}),this.on("next",()=>{this.#x()}))}#x(){this.#A||this.#o||(this.#o=!0,queueMicrotask(()=>{this.#o=!1,this.#L()}))}#G(){this.#A||(this.#y(),this.#x())}#L(){let t=this.#l;if(this.#A||this.#I.size===0){t&&(this.#l=!1,this.emit("rateLimitCleared"));return}let o;if(this.#d){let e=Date.now();this.#S(e),o=this.#b()}else o=this.#t;let i=o>=this.#r;i!==t&&(this.#l=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#l}get isSaturated(){return this.#E===this.#u&&this.#I.size>0||this.isRateLimited&&this.#I.size>0}get runningTasks(){return[...this.#f.values()].map(t=>({...t,timeoutRemaining:t.timeout?Math.max(0,t.startTime+t.timeout-Date.now()):void 0}))}};var Wb=class{constructor(t,o){this.store=t,this.logger=o,this.queues=new Map}getQueue(t){return this.queues.has(t)||this.queues.set(t,new hd({concurrency:1})),this.queues.get(t)}async processOperations(t,o,i,e,a){let A=t[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let r=[],s={};for(let g in A)A[g]===null?r.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),r.length>0&&await this.processDeletions(o,r,i,e,a)})}async processDeletions(t,o,i,e,a){if(a)for(let A of o)i[t]?.[A]?(i[t][A]=null,e[t][A]=null):this.logger.warn(`Skipping deletion of non-existent ${t} in transaction: ${A}`);else{let A=await this.store.get(t,o);for(let r of o)A[r]?(i[t][r]=null,e[t][r]=null):this.logger.warn(`Skipping deletion of non-existent ${t}: ${r}`)}}async validateDeletions(t,o){let i=t[o];if(i)return this.getQueue(o).add(async()=>{let e=Object.keys(i).filter(A=>i[A]===null);if(e.length===0)return;let a=await this.store.get(o,e);for(let A of e)a[A]||(this.logger.warn(`Skipping deletion of non-existent ${o}: ${A}`),delete t[o][A])})}};var Yse=(n,t,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new eWe,a=new Map,A=new Map,r=new Map,s=new Wb(n,t);function g(Q){return a.has(Q)||a.set(Q,new hd({concurrency:1})),a.get(Q)}function c(Q){return A.has(Q)||(A.set(Q,new ic),r.set(Q,0)),A.get(Q)}function I(Q){let y=r.get(Q)??0;r.set(Q,y+1)}function d(Q){let y=(r.get(Q)??1)-1;if(r.set(Q,y),y<=0){let m=A.get(Q);m&&!m.isLocked()&&(A.delete(Q),r.delete(Q))}}function B(){return!!e.getStore()}async function f(Q){if(Object.keys(Q).length===0){t.trace("no mutations in transaction");return}t.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(Q,y);let T=m.cache[Q]||{},_=y.filter(H=>!(H in T));if(_.length>0){m.dbQueries++,t.trace({type:Q,count:_.length},"fetching missing keys in transaction");let H=await c(Q).runExclusive(()=>n.get(Q,_));m.cache[Q]=m.cache[Q]||{},Object.assign(m.cache[Q],H)}let R={};for(let H of y){let F=m.cache[Q]?.[H];F!=null&&(R[H]=F)}return R},set:async Q=>{let y=e.getStore();if(!y){let m=Object.keys(Q);for(let T of m){let _=T;_==="pre-key"&&await s.validateDeletions(Q,_)}await Promise.all(m.map(T=>g(T).add(async()=>{let _={[T]:Q[T]};await n.set(_)})));return}t.trace({types:Object.keys(Q)},"caching in transaction");for(let m in Q){let T=m;y.cache[T]=y.cache[T]||{},y.mutations[T]=y.mutations[T]||{},T==="pre-key"?await s.processOperations(Q,T,y.cache,y.mutations,!0):(Object.assign(y.cache[T],Q[T]),Object.assign(y.mutations[T],Q[T]))}},isInTransaction:B,transaction:async(Q,y)=>{if(e.getStore())return t.trace("reusing existing transaction context"),Q();let T=c(y);I(y);try{return await T.runExclusive(async()=>{let _={cache:{},mutations:{},dbQueries:0};t.trace("entering transaction");try{let R=await e.run(_,Q);return await f(_.mutations),t.trace({dbQueries:_.dbQueries},"transaction completed"),R}catch(R){throw t.error({error:R},"transaction failed, rolling back"),R}})}finally{d(y)}}}},jse=n=>{let t=n.me?.id;if(!t)throw new xse.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return t},Jse=()=>{let n=Dr.generateKeyPair();return{noiseKey:Dr.generateKeyPair(),pairingEphemeralKeyPair:Dr.generateKeyPair(),signedIdentityKey:n,signedPreKey:PD(n,1),registrationId:j$(),advSecretKey:AWe(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},registered:!1,pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0,additionalData:void 0}};import{mkdir as tWe,readFile as rWe,stat as aWe,unlink as iWe,writeFile as oWe}from"fs/promises";import{join as QH}from"path";var qse=new Map,yH=n=>{let t=qse.get(n);return t||(t=new ic,qse.set(n,t)),t},zse=async n=>{let t=async(r,s)=>{let g=QH(n,a(s));return yH(g).acquire().then(async I=>{try{await oWe(g,JSON.stringify(r,jB.replacer))}finally{I()}})},o=async r=>{try{let s=QH(n,a(r));return await yH(s).acquire().then(async c=>{try{let I=await rWe(s,{encoding:"utf-8"});return JSON.parse(I,jB.reviver)}finally{c()}})}catch{return null}},i=async r=>{try{let s=QH(n,a(r));return yH(s).acquire().then(async c=>{try{await iWe(s)}catch{}finally{c()}})}catch{}},e=await aWe(n).catch(()=>{});if(e){if(!e.isDirectory())throw new Error(`found something that is not a directory at ${n}, either delete it or specify a different location`)}else await tWe(n,{recursive:!0});let a=r=>r?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||Jse();return{state:{creds:A,keys:{get:async(r,s)=>{let g={};return await Promise.all(s.map(async c=>{let I=await o(`${r}-${c}.json`);r==="app-state-sync-key"&&I&&(I=ne.Message.AppStateSyncKeyData.fromObject(I)),g[c]=I})),g},set:async r=>{let s=[];for(let g in r)for(let c in r[g]){let I=r[g][c],d=`${g}-${c}.json`;s.push(I?t(I,d):i(d))}await Promise.all(s)}}},saveCreds:async()=>t(A,"creds.json")}};var nWe=192,sWe=async(n,{thumbnailWidth:t,fetchOpts:o})=>{let i=await Hb(n,o);return await HU(i,t)},Vse=async(n,t={thumbnailWidth:nWe,fetchOpts:{timeout:3e3}})=>{try{let o=0,i=5,{getLinkPreview:e}=await import("link-preview-js"),a=n;!n.startsWith("https://")&&!n.startsWith("http://")&&(a="https://"+a);let A=await e(a,{...t.fetchOpts,followRedirects:"follow",handleRedirects:(r,s)=>{let g=new URL(r),c=new URL(s);return o>=i?!1:c.hostname===g.hostname||c.hostname==="www."+g.hostname||"www."+c.hostname===g.hostname?(o+=1,!0):!1},headers:t.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[r]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:r};if(t.uploadImage){let{imageMessage:g}=await Kf({image:{url:r}},{upload:t.uploadImage,mediaTypeOverride:"thumbnail-link",options:t.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=r?(await sWe(r,t)).buffer:void 0}catch(g){t.logger?.debug({err:g.stack,url:a},"error in generating thumbnail")}return s}}catch(o){if(!o.message.includes("receive a valid"))throw o}};import CWe from"events";var SH=ze(jr(),1);var gWe=/^1313555\d{4}$|^131655500\d{2}$/;function cWe(n){if(!n)return!1;let t=n.split("@")[0]??"";return t==="0"||gWe.test(t)||mh(n)?!1:!!(Tt(n)||qA(n)||wr(n)||Ea(n)||n.endsWith("@c.us"))}var Zb=604800,IWe=4,_I="__index";async function Xb(n){let o=(await n.get("tctoken",[_I]))[_I];if(!o?.token?.length)return[];try{let i=JSON.parse(Buffer.from(o.token).toString());return Array.isArray(i)?i.filter(e=>typeof e=="string"&&e.length>0&&e!==_I):[]}catch{return[]}}async function SE(n,t){let o=await Xb(n),i=new Set(o);for(let e of t)e&&e!==_I&&i.add(e);return{[_I]:{token:Buffer.from(JSON.stringify([...i]))}}}function Ed(n){if(n==null)return!0;let t=typeof n=="string"?parseInt(n):n;if(isNaN(t))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/Zb)-(IWe-1))*Zb;return ti}async function rg(n,t){return qA(n)?n:await t(n)??n}async function Zf(n,t,o,i){return t?qA(n)?n:await o(n)??n:qA(n)&&i?await i(n)??n:n}async function mH({authState:n,jid:t,baseContent:o=[],getLIDForPN:i}){try{let e=await rg(t,i),A=(await n.keys.get("tctoken",[e]))?.[e],r=A?.token,s=A?.timestamp;if(!r?.length||s===void 0||Ed(s)){if(r){let g=A?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:A.senderTimestamp}:null;await n.keys.set({tctoken:{[e]:g}})}return o.length>0?o:void 0}return o.push({tag:"tctoken",attrs:{t:String(s)},content:r}),o}catch{return o.length>0?o:void 0}}async function wE({result:n,fallbackJid:t,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=le(n,"tokens");if(!a)return;let A=PA(a,"token");for(let r of A){if(r.attrs.type!=="trusted_contact"||!(r.content instanceof Uint8Array))continue;let s=CA(t||r.attrs.jid);if(!cWe(s))continue;let g=await rg(s,i),I=(await o.get("tctoken",[g]))[g],d=I?.timestamp?Number(I.timestamp):0,B=r.attrs.t?Number(r.attrs.t):0;B&&(d>0&&d>B||(await o.set({tctoken:{[g]:{...I,token:Buffer.from(r.content),timestamp:r.attrs.t}}}),e?.(g)))}}var lWe=new Set([RA.CALL_MISSED_GROUP_VIDEO,RA.CALL_MISSED_GROUP_VOICE,RA.CALL_MISSED_VIDEO,RA.CALL_MISSED_VOICE]),dWe=new Set([RA.GROUP_PARTICIPANT_ADD]);async function pWe(n,t,o,i){let e=t.lidMapping.getLIDForPN.bind(t.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?qr(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let I=CA(g.id),d=await rg(I,e);a.push({storageJid:d,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?qr(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),r=await o.get("tctoken",A),s={};for(let g of a){let c=r[g.storageJid],I=c?.timestamp?Number(c.timestamp):0;I>0&&I>=g.ts||(s[g.storageJid]={...c,token:g.token,timestamp:String(g.ts),...g.senderTs!==void 0?{senderTimestamp:g.senderTs}:{}})}if(Object.keys(s).length){i?.debug({count:Object.keys(s).length},"storing tctokens from history sync");try{let g=await SE(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Zse=(n,t,o)=>{wr(n.key.remoteJid)||Ea(n.key.remoteJid)?n.key.remoteJid=Sr(fA(n.key?.remoteJid)?.user,wr(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=CA(n.key.remoteJid),wr(n.key.participant)||Ea(n.key.participant)?n.key.participant=Sr(fA(n.key.participant)?.user,wr(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=CA(n.key.participant);let i=ya(n.message);i?.reactionMessage&&e(i.reactionMessage.key),i?.pollUpdateMessage&&e(i.pollUpdateMessage.pollCreationMessageKey);function e(a){n.key.fromMe||(a.fromMe=a.fromMe?!1:kt(a.participant||a.remoteJid,t)||kt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},wH=n=>{let t=ya(n.message),o=!!xf(t);return(!!t||lWe.has(n.messageStubType)||dWe.has(n.messageStubType))&&o&&!t?.protocolMessage&&!t?.reactionMessage&&!t?.pollUpdateMessage},DH=n=>!n.key.fromMe&&!n.messageStubType,hWe=({remoteJid:n,participant:t,fromMe:o})=>{if(!n)throw new SH.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:t,fromMe:o}});if(PB(n)&&!Yg(n)&&!o){if(!t)throw new SH.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return t}return n};function EWe({encPayload:n,encIv:t},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([I(i),I(o),I(a),I("Event Response"),new Uint8Array([1])]),r=qn(e,new Uint8Array(32),"sha256"),s=qn(A,r,"sha256"),g=I(`${i}\0${a}`),c=Yl(n,s,t,g);return ne.Message.EventResponseMessage.decode(c);function I(d){return Buffer.from(d)}}var uWe=async(n,{shouldProcessHistoryMsg:t,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:r,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:I}=e,d={id:CA(hWe(n.key))},B=wH(n);B&&(d.messages=[{message:n}],d.conversationTimestamp=qr(n.messageTimestamp),DH(n)&&(d.unreadCount=(d.unreadCount||0)+1));let f=ya(n.message);(B||f?.reactionMessage?.key?.fromMe)&&I?.unarchiveChats&&(d.archived=!1,d.readOnly=!1);let Q=f?.protocolMessage;if(Q){let y=new Set([ne.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,ne.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,ne.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,ne.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(Q.type!==null&&Q.type!==void 0&&y.has(Q.type)&&!n.key.fromMe){r?.warn({msgId:n.key.id,type:Q.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(Q.type){case ne.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=Q.historySyncNotification,T=t,_=!e.processedHistoryMessages?.length;if(r?.info({histNotification:m,process:T,id:n.key.id,isLatest:_},"got history notification"),T){m.syncType!==ne.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let G=await fse(m,s,r);G.lidPnMappings?.length&&(r?.debug({count:G.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(G.lidPnMappings).catch(V=>r?.warn({err:V},"failed to store LID-PN mappings from history sync"))),await pWe(G.chats,a,A,r),i.emit("messaging-history.set",{...G,isLatest:m.syncType!==ne.HistorySync.HistorySyncType.ON_DEMAND?_:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case ne.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let R=Q.appStateSyncKeyShare.keys;if(R?.length){let G="";await A.transaction(async()=>{let V=[];for(let{keyData:U,keyId:N}of R){let k=Buffer.from(N.keyId).toString("base64");V.push(k),await A.set({"app-state-sync-key":{[k]:U}}),G=k}r?.info({newAppStateSyncKeyId:G,newKeys:V},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:G})}else r?.info({protocolMsg:Q},"recv app state sync with 0 keys");break;case ne.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:Q.key.id},update:{message:null,messageStubType:RA.REVOKE,key:n.key}}]);break;case ne.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(d,{ephemeralSettingTimestamp:qr(n.messageTimestamp),ephemeralExpiration:Q.ephemeralExpiration||null});break;case ne.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let H=Q.peerDataOperationRequestResponseMessage;if(H){let G=H.peerDataOperationResult||[];for(let V of G){let U=V?.placeholderMessageResendResponse;if(U?.webMessageInfoBytes)try{let N=ne.WebMessageInfo.decode(U.webMessageInfoBytes),k=N.key?.id,J=k?await o?.get(k):void 0;k&&await o?.del(k);let X;J&&typeof J=="object"?(J.message=N.message,N.messageTimestamp&&(J.messageTimestamp=N.messageTimestamp),X=J):X=N,r?.debug({msgId:k,requestId:H.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[X],type:"notify",requestId:H.stanzaId})}catch(N){r?.warn({err:N,stanzaId:H.stanzaId},"failed to decode placeholder resend response")}}}break;case ne.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:Q.key?.id},update:{message:{editedMessage:{message:Q.editedMessage}},messageTimestamp:Q.timestampMs?Math.floor(qr(Q.timestampMs)/1e3):n.messageTimestamp}}]);break;case ne.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let F=Q.memberLabel;F?.label&&i.emit("group.member-tag.update",{groupId:d.id,label:F.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case ne.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let L=Q.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:z}=ne.LIDMigrationMappingSyncPayload.decode(L);r?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:z},"got lid mappings and chat db migration timestamp");let K=[];for(let{pn:G,latestLid:V,assignedLid:U}of q){let N=V||U;K.push({lid:`${N}@lid`,pn:`${G}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(K),K.length)for(let{pn:G,lid:V}of K)await a.migrateSession(G,V)}}else if(f?.reactionMessage){let y={...f.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:f.reactionMessage?.key}])}else if(f?.encEventResponseMessage){let y=f.encEventResponseMessage,m=y.eventCreationMessageKey,T=await g(m);if(T)try{let _=CA(c),R=m.participant||m.remoteJid,H=qA(R)?await a.lidMapping.getPNForLID(R):R,F=Mh({remoteJid:CA(H),fromMe:_===H},_),L=Mh(n.key,_),q=T?.messageContextInfo?.messageSecret;if(!q)r?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let z=EWe(y,{eventEncKey:q,eventCreatorJid:F,eventMsgId:m.id,responderJid:L}),K={eventResponseMessageKey:n.key,senderTimestampMs:z.timestampMs,response:z};i.emit("messages.update",[{key:m,update:{eventResponses:[K]}}])}}catch(_){r?.warn({err:_,creationMsgKey:m},"failed to decrypt event response")}else r?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,T=F=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:F}),_=F=>{i.emit("groups.update",[{id:y,...F,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},R=(F,L,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:F.lid,participantPn:F.pn,action:L,method:q})},H=()=>m.find(F=>kt(c,F.phoneNumber));switch(n.messageStubType){case RA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("modify");break;case RA.GROUP_PARTICIPANT_LEAVE:case RA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("remove"),H()&&(d.readOnly=!0);break;case RA.GROUP_PARTICIPANT_ADD:case RA.GROUP_PARTICIPANT_INVITE:case RA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],H()&&(d.readOnly=!1),T("add");break;case RA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("demote");break;case RA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(J=>JSON.parse(J))||[],T("promote");break;case RA.GROUP_CHANGE_ANNOUNCE:let F=n.messageStubParameters?.[0];_({announce:F==="true"||F==="on"});break;case RA.GROUP_CHANGE_RESTRICT:let L=n.messageStubParameters?.[0];_({restrict:L==="true"||L==="on"});break;case RA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];d.name=q,_({subject:q});break;case RA.GROUP_CHANGE_DESCRIPTION:let z=n.messageStubParameters?.[0];d.description=z,_({desc:z});break;case RA.GROUP_CHANGE_INVITE_LINK:let K=n.messageStubParameters?.[0];_({inviteCode:K});break;case RA.GROUP_MEMBER_ADD_MODE:let G=n.messageStubParameters?.[0];_({memberAddMode:G==="all_member_add"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let V=n.messageStubParameters?.[0];_({joinApprovalMode:V==="on"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let U=JSON.parse(n.messageStubParameters?.[0]),N=n.messageStubParameters?.[1],k=n.messageStubParameters?.[2];R(U,N,k);break}}Object.keys(d).length>1&&i.emit("chats.update",[d])},Xse=uWe;var BWe=["messaging-history.set","chats.upsert","chats.update","chats.delete","contacts.upsert","contacts.update","messages.upsert","messages.update","messages.delete","messages.reaction","message-receipt.update","groups.update"],fWe=new Set(BWe),$se=n=>{let t=new CWe,o=new Set,i=OH(),e=!1,a=null,A=null,r=0,s=1e4,g=3e4;t.on("event",d=>{for(let B in d)t.emit(B,d[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,r=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),I())},g)),r++}function I(){if(!e)return!1;n.debug({bufferCount:r},"Flushing event buffer"),e=!1,r=0,a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.size>s&&(n.debug({cacheSize:o.size},"Clearing history cache"),o.clear());let d=OH(),B=Object.values(i.chatUpdates),f=0;for(let y of B)y.conditional&&(f+=1,d.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let Q=yWe(i);return Object.keys(Q).length&&t.emit("event",Q),i=d,n.trace({conditionalChatUpdatesLeft:f},"released buffered events"),!0}return{process(d){let B=async f=>{await d(f)};return t.on("event",B),()=>{t.off("event",B)}},emit(d,B){if(d==="messages.upsert"){let{type:f}=B,Q=Object.values(i.messageUpserts);if(Q.length>0){let y=Q[0].type;y!==f&&(n.debug({bufferedType:y,newType:f},"messages.upsert type mismatch, emitting buffered messages"),t.emit("event",{"messages.upsert":{messages:Q.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&fWe.has(d)?(QWe(i,o,d,B,n),!0):t.emit("event",{[d]:B})},isBuffering(){return e},buffer:c,flush:I,createBufferedFunction(d){return async(...B)=>{c();try{let f=await d(...B);return r===1&&setTimeout(()=>{e&&r===1&&I()},100),f}catch(f){throw f}finally{r=Math.max(0,r-1),r===0&&(A||(A=setTimeout(I,100)))}}},on:(...d)=>t.on(...d),off:(...d)=>t.off(...d),removeAllListeners:(...d)=>t.removeAllListeners(...d),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=OH(),e=!1,r=0,t.removeAllListeners(),n.debug("Event buffer destroyed")}}},OH=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function QWe(n,t,o,i,e){switch(o){case"messaging-history.set":for(let Q of i.chats){let y=Q.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=Q.endOfHistoryTransferType),!m&&!t.has(y)&&(n.historySets.chats[y]=Q,t.add(y),a(Q))}for(let Q of i.contacts){let y=n.historySets.contacts[Q.id];if(y)Object.assign(y,LD(Q));else{let m=`c:${Q.id}`,T=Q.notify||Q.name||Q.verifiedName;(!t.has(m)||T)&&(n.historySets.contacts[Q.id]=Q,t.add(m))}}for(let Q of i.messages){let y=DE(Q.key);!n.historySets.messages[y]&&!t.has(y)&&(n.historySets.messages[y]=Q,t.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let Q=new Map,y=T=>`${T.userJid||""}:${T.leaveTs||""}:${T.leaveReason||""}`,m=T=>{let _=T.groupJid??JSON.stringify(T),R=Q.get(_);if(!R){Q.set(_,{...T,pastParticipants:[...T.pastParticipants||[]]});return}let H=new Set((R.pastParticipants||[]).map(y));for(let F of T.pastParticipants||[]){let L=y(F);H.has(L)||(R.pastParticipants.push(F),H.add(L))}};for(let T of n.historySets.pastParticipants||[])m(T);for(let T of i.pastParticipants)m(T);n.historySets.pastParticipants=[...Q.values()]}n.historySets.progress=i.progress,n.historySets.chunkOrder=i.chunkOrder,n.historySets.peerDataRequestSessionId=i.peerDataRequestSessionId,n.historySets.isLatest=i.isLatest||n.historySets.isLatest;break;case"chats.upsert":for(let Q of i){let y=Q.id||"",m=n.chatUpserts[y];y&&!m&&(m=n.historySets.chats[y],m&&e.debug({chatId:y},"absorbed chat upsert in chat set")),m?m=$b(m,Q):(m=Q,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let Q of i){let y=Q.id,m=Q.conditional?Q.conditional(n):!0;if(m){delete Q.conditional;let T=n.historySets.chats[y]||n.chatUpserts[y];if(T)$b(T,Q);else{let _=n.chatUpdates[y]||{};n.chatUpdates[y]=$b(_,Q)}}else m===void 0&&(n.chatUpdates[y]=Q);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let Q of i)n.chatDeletes.has(Q)||n.chatDeletes.add(Q),n.chatUpdates[Q]&&delete n.chatUpdates[Q],n.chatUpserts[Q]&&delete n.chatUpserts[Q],n.historySets.chats[Q]&&delete n.historySets.chats[Q];break;case"contacts.upsert":for(let Q of i){let y=n.contactUpserts[Q.id];y||(y=n.historySets.contacts[Q.id],y&&e.debug({contactId:Q.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,LD(Q)):(y=Q,n.contactUpserts[Q.id]=y),n.contactUpdates[Q.id]&&(y=Object.assign(n.contactUpdates[Q.id],LD(Q)),delete n.contactUpdates[Q.id])}break;case"contacts.update":let r=i;for(let Q of r){let y=Q.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,Q);else{let T=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(T,Q)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let Q of s){let y=DE(Q.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(Q.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(Q,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=Q:n.messageUpserts[y]={message:Q,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:Q,update:y}of c){let m=DE(Q),T=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(T)Object.assign(T,y),y.status===yh.READ&&!Q.fromMe&&A(T);else{let _=n.messageUpdates[m]||{key:Q,update:{}};Object.assign(_.update,y),n.messageUpdates[m]=_}}break;case"messages.delete":let I=i;if("keys"in I){let{keys:Q}=I;for(let y of Q){let m=DE(y);n.messageDeletes[m]||(n.messageDeletes[m]=y),n.messageUpserts[m]&&delete n.messageUpserts[m],n.messageUpdates[m]&&delete n.messageUpdates[m]}}break;case"messages.reaction":let d=i;for(let{key:Q,reaction:y}of d){let m=DE(Q),T=n.messageUpserts[m];T?VU(T.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:Q,reactions:[]},VU(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:Q,receipt:y}of B){let m=DE(Q),T=n.messageUpserts[m];T?zU(T.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:Q,userReceipt:[]},zU(n.messageReceipts[m],y))}break;case"groups.update":let f=i;for(let Q of f){let y=Q.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,Q))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(r){let s=r.id||"",g=n.chatUpdates[s];if(g){let c=g.conditional?g.conditional(n):!0;c?(delete g.conditional,e.debug({chatId:s},"absorbed chat update in existing chat"),Object.assign(r,$b(g,r)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(r){let s=r.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];wH(r)&&DH(r)&&typeof g?.unreadCount=="number"&&g.unreadCount>0&&(e.debug({chatId:g.id},"decrementing chat counter"),g.unreadCount-=1,g.unreadCount===0&&delete g.unreadCount)}}function yWe(n){let t={};n.historySets.empty||(t["messaging-history.set"]={chats:Object.values(n.historySets.chats),messages:Object.values(n.historySets.messages),contacts:Object.values(n.historySets.contacts),pastParticipants:n.historySets.pastParticipants,syncType:n.historySets.syncType,progress:n.historySets.progress,isLatest:n.historySets.isLatest,chunkOrder:n.historySets.chunkOrder,peerDataRequestSessionId:n.historySets.peerDataRequestSessionId});let o=Object.values(n.chatUpserts);o.length&&(t["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(t["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(t["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;t["messages.upsert"]={messages:a.map(f=>f.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(t["messages.update"]=A);let r=Object.values(n.messageDeletes);r.length&&(t["messages.delete"]={keys:r});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:f})=>f.flatMap(Q=>({key:B,reaction:Q})));s.length&&(t["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:f})=>f.flatMap(Q=>({key:B,receipt:Q})));g.length&&(t["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(t["contacts.upsert"]=c);let I=Object.values(n.contactUpdates);I.length&&(t["contacts.update"]=I);let d=Object.values(n.groupUpdates);return d.length&&(t["groups.update"]=d),t}function $b(n,t){return t.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,t.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof t.unreadCount=="number"&&(t={...t},t.unreadCount>=0&&(t.unreadCount=Math.max(t.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,t)}var DE=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var mWe=512,bH="\0",ege=3600*1e3,SWe=3e3,oc;(function(n){n[n.UnknownError=0]="UnknownError",n[n.SignalErrorNoSession=1]="SignalErrorNoSession",n[n.SignalErrorInvalidKey=2]="SignalErrorInvalidKey",n[n.SignalErrorInvalidKeyId=3]="SignalErrorInvalidKeyId",n[n.SignalErrorInvalidMessage=4]="SignalErrorInvalidMessage",n[n.SignalErrorInvalidSignature=5]="SignalErrorInvalidSignature",n[n.SignalErrorFutureMessage=6]="SignalErrorFutureMessage",n[n.SignalErrorBadMac=7]="SignalErrorBadMac",n[n.SignalErrorInvalidSession=8]="SignalErrorInvalidSession",n[n.SignalErrorInvalidMsgKey=9]="SignalErrorInvalidMsgKey",n[n.BadBroadcastEphemeralSetting=10]="BadBroadcastEphemeralSetting",n[n.UnknownCompanionNoPrekey=11]="UnknownCompanionNoPrekey",n[n.AdvFailure=12]="AdvFailure",n[n.StatusRevokeDelay=13]="StatusRevokeDelay"})(oc||(oc={}));var Age=new Set([oc.SignalErrorInvalidMessage,oc.SignalErrorBadMac]),eM=class{constructor(t,o){this.logger=t,this.recentMessagesMap=new Kg({max:mWe,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(bH);if(a>-1){let A=e.slice(a+bH.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Kg({ttl:ege*2,ttlAutopurge:!0}),this.retryCounters=new Kg({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Kg({max:1024,ttl:900*1e3,ttlAutopurge:!0}),this.pendingPhoneRequests={},this.maxMsgRetryCount=5,this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0},this.maxMsgRetryCount=o}addRecentMessage(t,o,i){let e={to:t,id:o},a=this.keyToString(e);this.recentMessagesMap.set(a,{message:i,timestamp:Date.now()}),this.messageKeyIndex.set(o,a),this.logger.debug(`Added message to retry cache: ${t}/${o}`)}getRecentMessage(t,o){let i={to:t,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(t,o,i){if(!o)return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&Age.has(i))return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:t,errorCode:oc[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${oc[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(t);return!a||e-a>ege?(this.sessionRecreateHistory.set(t,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(t){if(t===void 0||t==="")return;let o=parseInt(t,10);if(!Number.isNaN(o))return o>=oc.UnknownError&&o<=oc.StatusRevokeDelay?o:oc.UnknownError}isMacError(t){return t!==void 0&&Age.has(t)}incrementRetryCount(t){return this.retryCounters.set(t,(this.retryCounters.get(t)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(t)}getRetryCount(t){return this.retryCounters.get(t)||0}hasExceededMaxRetries(t){return this.getRetryCount(t)>=this.maxMsgRetryCount}markRetrySuccess(t){this.statistics.successfulRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}markRetryFailed(t){this.statistics.failedRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}schedulePhoneRequest(t,o,i=SWe){this.cancelPendingPhoneRequest(t),this.pendingPhoneRequests[t]=setTimeout(()=>{delete this.pendingPhoneRequests[t],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${t} with ${i}ms delay`)}cancelPendingPhoneRequest(t){let o=this.pendingPhoneRequests[t];o&&(clearTimeout(o),delete this.pendingPhoneRequests[t],this.logger.debug(`Cancelled pending phone request for message ${t}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let t of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(t);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(t,o,i){this.baseKeys.set(`${t}:${o}`,i)}hasSameBaseKey(t,o,i){let e=this.baseKeys.get(`${t}:${o}`);if(!e||e.length!==i.length)return!1;for(let a=0;a["Ubuntu",n,"22.04.4"],macOS:n=>["Mac OS",n,"14.4.1"],baileys:n=>["Baileys",n,"6.5.0"],windows:n=>["Windows",n,"10.0.22631"],android:n=>[n,"Android",""],appropriate:n=>[OWe[wWe()]||"Ubuntu",n,DWe()]};var Wn;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.CHROME=1]="CHROME",n[n.EDGE=2]="EDGE",n[n.FIREFOX=3]="FIREFOX",n[n.IE=4]="IE",n[n.OPERA=5]="OPERA",n[n.SAFARI=6]="SAFARI",n[n.ELECTRON=7]="ELECTRON",n[n.UWP=8]="UWP",n[n.OTHER_WEB_CLIENT=9]="OTHER_WEB_CLIENT"})(Wn||(Wn={}));var bWe={Chrome:Wn.CHROME,Edge:Wn.EDGE,Firefox:Wn.FIREFOX,IE:Wn.IE,Opera:Wn.OPERA,Safari:Wn.SAFARI},MWe=([n,t])=>t==="Desktop"?n==="Windows"?Wn.UWP:Wn.ELECTRON:bWe[t]||Wn.OTHER_WEB_CLIENT,MH=n=>MWe(n).toString(),tge=(n,t,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,t,o,i,MH(e)].join(",");async function rge(n,t){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!le(n,"identity"))return{action:"no_identity_node"};t.logger.info({jid:o},"identity changed");let e=fA(o);if(e?.device&&e.device!==0)return t.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(t.meId&&(kt(o,t.meId)||t.meLid&&kt(o,t.meLid)))return t.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(t.debounceCache.get(o))return t.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};t.debounceCache.set(o,!0);let A=!K$(n.attrs.offline);if(!(await t.validateSession(o)).exists)return t.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(t.logger.debug({jid:o},"old session exists, will refresh session"),A)return t.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};t.onBeforeSessionRefresh?.(o);try{return await t.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return t.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function age(n,t,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return t&&(a.attrs.error=t.toString()),e.participant&&(a.attrs.participant=e.participant),e.recipient&&(a.attrs.recipient=e.recipient),e.type&&(a.attrs.type=e.type),i==="message"&&o&&(a.attrs.from=o),a}function _We(n){return n===null||n===""}function TWe(n){return n>2147483647||n<-2147483648?n&4294967295:n}function ige(n){let t=0;if(!_We(n))for(let o=0;oo.iteration===t)}addSenderMessageKey(t){this.senderKeyStateStructure.senderMessageKeys.push({iteration:t.getIteration(),seed:t.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(t){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===t);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new ud(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var nc=class n{constructor(t){if(this.MAX_STATES=5,this.senderKeyStates=[],t)for(let o of t)this.senderKeyStates.push(new Cd(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(t){return t===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===t)}addSenderKeyState(t,o,i,e){this.senderKeyStates.push(new Cd(t,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(t,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new Cd(t,o,i,e))}serialize(){return this.senderKeyStates.map(t=>t.getStructure())}static deserialize(t){let o=Buffer.from(t).toString("utf-8"),i=JSON.parse(o,jB.reviver);return new n(i)}};var sge=ze(Vc(),1);import*as tM from"crypto";function gge(){return tM.randomBytes(32)}function cge(){return tM.randomInt(2147483647)}function Ige(n){return n||(n=(0,sge.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var Bd=class{constructor(){this.UNSUPPORTED_VERSION=1,this.CURRENT_VERSION=3,this.WHISPER_TYPE=2,this.PREKEY_TYPE=3,this.SENDERKEY_TYPE=4,this.SENDERKEY_DISTRIBUTION_TYPE=5,this.ENCRYPTED_MESSAGE_OVERHEAD=53}};var fd=class extends Bd{constructor(t,o,i,e,a){if(super(),a)try{let A=a.slice(1),r=ne.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=r.id,this.iteration=r.iteration,this.chainKey=typeof r.chainKey=="string"?Buffer.from(r.chainKey,"base64"):r.chainKey,this.signatureKey=typeof r.signingKey=="string"?Buffer.from(r.signingKey,"base64"):r.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=t,this.iteration=o,this.chainKey=i,this.signatureKey=e;let r=ne.SenderKeyDistributionMessage.encode(ne.SenderKeyDistributionMessage.create({id:t,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),r])}}intsToByteHighAndLow(t,o){return((t<<4|o)&255)%256}serialize(){return this.serialized}getType(){return this.SENDERKEY_DISTRIBUTION_TYPE}getIteration(){return this.iteration}getChainKey(){return this.chainKey}getSignatureKey(){return this.signatureKey}getId(){return this.id}};var OE=class{constructor(t){this.senderKeyStore=t}async process(t,o){let i=await this.senderKeyStore.loadSenderKey(t);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(t,i)}async create(t){let o=await this.senderKeyStore.loadSenderKey(t);if(o.isEmpty()){let e=cge(),a=gge(),A=Ige();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(t,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new fd(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var aM=ze(Ll(),1);var rM=ze(Vc(),1);var bE=class extends Bd{constructor(t,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],r=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=ne.SenderKeyMessage.decode(r).toJSON();this.serialized=a,this.messageVersion=(A&255)>>4,this.keyId=g.id,this.iteration=g.iteration,this.ciphertext=typeof g.ciphertext=="string"?Buffer.from(g.ciphertext,"base64"):g.ciphertext,this.signature=s}else{let A=((this.CURRENT_VERSION<<4|this.CURRENT_VERSION)&255)%256,r=Buffer.from(i),s=ne.SenderKeyMessage.encode(ne.SenderKeyMessage.create({id:t,iteration:o,ciphertext:r})).finish(),g=this.getSignature(e,Buffer.concat([Buffer.from([A]),s]));this.serialized=Buffer.concat([Buffer.from([A]),s,Buffer.from(g)]),this.messageVersion=this.CURRENT_VERSION,this.keyId=t,this.iteration=o,this.ciphertext=r,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(t){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,rM.verifySignature)(t,o,i))throw new Error("Invalid signature!")}getSignature(t,o){return Buffer.from((0,rM.calculateSignature)(t,o))}serialize(){return this.serialized}getType(){return 4}};var ME=class{constructor(t,o){this.senderKeyStore=t,this.senderKeyName=o}async encrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for encryption");let i=o.getSenderKeyState();if(!i)throw new Error("No session to encrypt message");let e=i.getSenderChainKey().getIteration(),a=this.getSenderKey(i,e===0?0:e+1),A=await this.getCipherText(a.getIv(),a.getCipherKey(),t),r=new bE(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),r.serialize()}async decrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new bE(null,null,null,null,t),e=o.getSenderKeyState(i.getKeyId());if(!e)throw new Error("No session found to decrypt message");i.verifySignature(e.getSigningKeyPublic());let a=this.getSenderKey(e,i.getIteration()),A=await this.getPlainText(a.getIv(),a.getCipherKey(),i.getCipherText());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),A}getSenderKey(t,o){let i=t.getSenderChainKey();if(i.getIteration()>o){if(t.hasSenderMessageKey(o)){let e=t.removeSenderMessageKey(o);if(!e)throw new Error("No sender message key found for iteration");return e}throw new Error(`Received message with old counter: ${i.getIteration()}, ${o}`)}if(o-i.getIteration()>2e3)throw new Error("Over 2000 messages into the future!");for(;i.getIteration()0){let r=[...i];this.logger.trace(`Batch fetching ${r.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",r);for(let g of r){let c=s[g];c&&(e.set(g,c),this.mappingCache.set(`pn:${g}`,c),this.mappingCache.set(`lid:${c}`,g))}}let a={};for(let{pnUser:r,lidUser:s}of o){if(e.get(r)===s){this.logger.debug({pnUser:r,lidUser:s},"LID mapping already exists, skipping");continue}a[r]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[r,s]of Object.entries(a))A[r]=s,A[`${s}_reverse`]=r;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[r,s]of Object.entries(a))this.mappingCache.set(`pn:${r}`,s),this.mappingCache.set(`lid:${s}`,r)}async getLIDForPN(t){return(await this.getLIDsForPNs([t]))?.[0]?.lid||null}async getLIDsForPNs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightLIDLookups.get(i);if(e)return this.logger.trace(`Coalescing getLIDsForPNs request for ${o.length} PNs`),e;let a=this._getLIDsForPNsImpl(t);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(t){let o={},i={},e=[],a=(A,r,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=r.device!==void 0?r.device:0,I=`${g}${c?`:${c}`:""}@${r.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${I} (user mapping with device ${c})`),i[A]={lid:I,pn:A},!0};for(let A of t){if(!Tt(A)&&!wr(A))continue;let r=fA(A);if(!r)continue;let s=r.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,r,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:r})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],r=await this.keys.get("lid-mapping",A);for(let s of A){let g=r[s];g&&typeof g=="string"&&(this.mappingCache.set(`pn:${s}`,g),this.mappingCache.set(`lid:${g}`,s))}for(let{pn:s,pnUser:g,decoded:c}of e){let I=this.mappingCache.get(`pn:${g}`);if(I&&typeof I=="string"){if(!a(s,c,I)){this.logger.warn(`Invalid entry for ${s} (pair not resolved)`);continue}}else{this.logger.trace(`No LID mapping found for PN user ${g}; batch getting from USync`);let d=c.device||0,B=CA(s);wr(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(d):o[B]=[d]}}}if(Object.keys(o).length>0){let A=await this.pnToLIDFunc?.(Object.keys(o));if(A&&A.length>0){await this.storeLIDPNMappings(A);for(let r of A){let g=fA(r.pn)?.user;if(!g)continue;let c=fA(r.lid)?.user;if(c)for(let I of o[r.pn]){let d=`${c}${I?`:${I}`:""}@${I===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${r.pn} \u2192 ${d} (user mapping with device ${I})`);let B=`${g}${I?`:${I}`:""}@${I===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:d,pn:B}}}}else this.logger.warn("USync fetch yielded no results for pending PNs")}return Object.values(i).length>0?Object.values(i):null}async getPNForLID(t){return(await this.getPNsForLIDs([t]))?.[0]?.pn||null}async getPNsForLIDs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightPNLookups.get(i);if(e)return this.logger.trace(`Coalescing getPNsForLIDs request for ${o.length} LIDs`),e;let a=this._getPNsForLIDsImpl(t);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(t){let o={},i=[],e=(a,A,r)=>{if(!r||typeof r!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${r}:${s}@${A.domainType===zt.HOSTED_LID?"hosted":"s.whatsapp.net"}`;return this.logger.trace(`Found reverse mapping: ${a} \u2192 ${g}`),o[a]={lid:a,pn:g},!0};for(let a of t){if(!qA(a))continue;let A=fA(a);if(!A)continue;let r=A.user,s=this.mappingCache.get(`lid:${r}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:r,decoded:A})}if(i.length){let a=[...new Set(i.map(r=>`${r.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:r,lidUser:s,decoded:g}of i){let c=this.mappingCache.get(`lid:${s}`);(!c||typeof c!="string")&&(c=A[`${s}_reverse`],c&&typeof c=="string"&&(this.mappingCache.set(`lid:${s}`,c),this.mappingCache.set(`pn:${c}`,s))),c&&typeof c=="string"?e(r,g,c):this.logger.trace(`No reverse mapping found for LID user: ${s}`)}}return Object.values(o).length?Object.values(o):null}close(){this.mappingCache.clear()}};function NWe(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=dge.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function pge(n,t,o){let i=new iM(n.keys,t,o),e=RWe(n,i),a=n.keys,A=new Kg({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),r=async(g,c)=>{let I=oM(g,c),d=I.toString(),{[d]:B}=await n.keys.get("sender-key",[d]);B||await e.storeSenderKey(I,new nc);let f=await new OE(e).create(I);return{senderName:I,skdm:f}};return{decryptGroupMessage({group:g,authorJid:c,msg:I}){let d=oM(g,c),B=new ME(e,d);return a.transaction(async()=>B.decrypt(I),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let I=new OE(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let d=oM(g.groupId,c),B=new fd(null,null,null,null,g.axolotlSenderKeyDistributionMessage),f=d.toString(),{[f]:Q}=await n.keys.get("sender-key",[f]);return Q||await e.storeSenderKey(d,new nc),a.transaction(async()=>{let{[f]:y}=await n.keys.get("sender-key",[f]);y||await e.storeSenderKey(d,new nc),await I.process(d,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:I}){let d=Zn(g),B=new ag.SessionCipher(e,d);if(c==="pkmsg"){let Q=NWe(I);if(Q){let y=d.toString();await e.saveIdentity(y,Q)&&t.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function f(){let Q;switch(c){case"pkmsg":Q=await B.decryptPreKeyWhisperMessage(I);break;case"msg":Q=await B.decryptWhisperMessage(I);break}return Q}return a.transaction(async()=>await f(),g)},async encryptMessage({jid:g,data:c}){let I=Zn(g),d=new ag.SessionCipher(e,I);return a.transaction(async()=>{let{type:B,body:f}=await d.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(f,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:I}){return a.transaction(async()=>{let{senderName:d,skdm:B}=await r(g,c);return{ciphertext:await new ME(e,d).encrypt(I),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:I}=await r(g,c);return I.serialize()},g)},async hasSenderKey({group:g,meId:c}){let I=oM(g,c).toString(),{[I]:d}=await n.keys.get("sender-key",[I]);return!!d},async getSessionInfo(g){let c=Zn(g).toString(),I=await e.loadSession(c);if(!I)return null;let d=I.getOpenSession?.(),B=d?.indexInfo?.baseKey,f=d?.registrationId;return!B||typeof f!="number"?null:{baseKey:new Uint8Array(B),registrationId:f}},async injectE2ESession({jid:g,session:c}){t.trace({jid:g},"injecting E2EE session");let I=new ag.SessionBuilder(e,Zn(g));return a.transaction(async()=>{await I.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return Zn(g).toString()},lidMapping:i,async validateSession(g){try{let c=Zn(g),I=await e.loadSession(c.toString());return I?I.haveOpenSession()?{exists:!0}:{exists:!1,reason:"no open session"}:{exists:!1,reason:"no session"}}catch{return{exists:!1,reason:"validation error"}}},async deleteSession(g){if(!g.length)return;let c={};return g.forEach(I=>{let d=Zn(I);c[d.toString()]=null}),a.transaction(async()=>{await n.keys.set({session:c})},`delete-${g.length}-sessions`)},close(){A.clear(),i.close()},async migrateSession(g,c){if(!g||!qA(c)&&!Ea(c))return{migrated:0,skipped:0,total:0};if(!Tt(g)&&!wr(g))return{migrated:0,skipped:0,total:1};let{user:I}=fA(g);t.debug({fromJid:g},"bulk device migration - loading all user devices");let{[I]:d}=await a.get("device-list",[I]);if(!d)return{migrated:0,skipped:0,total:0};let{device:B}=fA(g),f=B?.toString()||"0";d.includes(f)||d.push(f);let y=d.filter(_=>{let R=`${I}.${_}`;return!A.has(R)}).map(_=>`${I}.${_}`),m=await a.get("session",y),T=[];for(let[_,R]of Object.entries(m))if(R){let H=_.split(".")[1];if(!H)continue;let F=parseInt(H),L=F===0?`${I}@s.whatsapp.net`:`${I}:${F}@s.whatsapp.net`;F===99&&(L=`${I}:99@hosted`),T.push(L)}return t.debug({fromJid:g,totalDevices:d.length,devicesWithSessions:T.length,devices:T},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let _=T.map(K=>{let G=I$(K,c),V=fA(K),U=fA(G);return{fromJid:K,toJid:G,pnUser:V.user,lidUser:U.user,deviceId:V.device||0,fromAddr:Zn(K),toAddr:Zn(G)}}),R=_.length,H=0,F=Array.from(new Set(_.map(K=>K.fromAddr.toString()))),L=await a.get("session",F),q={};for(let K of _){let G=K.fromAddr.toString(),V=K.toAddr.toString(),U=L[G];if(U){let N=ag.SessionRecord.deserialize(U);N.haveOpenSession()&&(q[V]=N.serialize(),q[G]=null,H++)}}if(Object.keys(q).length>0){await a.set({session:q}),t.debug({migratedSessions:H},"bulk session migration complete");for(let K of _)if(q[K.toAddr.toString()]){let G=`${K.pnUser}.${K.deviceId}`;A.set(G,!0)}}let z=R-H;return{migrated:H,skipped:z,total:R}},`migrate-${T.length}-sessions-${fA(c)?.user}`)}}}var Zn=n=>{let t=fA(n),{user:o,device:i,server:e,domainType:a}=t;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==zt.WHATSAPP?`${o}_${a}`:o,r=i||0;if(i===99&&t.server!=="hosted"&&t.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new ag.ProtocolAddress(A,r)},oM=(n,t)=>new Xf(n,Zn(t));function RWe({creds:n,keys:t},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[r,s]=a.split("_"),g=parseInt(s||"0");if(g===zt.LID||g===zt.HOSTED_LID)return e;let c=`${r}${A!=="0"?`:${A}`:""}@${g===zt.HOSTED?"hosted":"s.whatsapp.net"}`,I=await o.getLIDForPN(c);if(I)return Zn(I).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await t.get("session",[a]);if(A)return ag.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await t.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await t.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:r}=await t.get("identity-key",[A]),s=r?.length===a.length&&r.every((g,c)=>g===a[c]);return r&&!s?(await t.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):r?!1:(await t.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>t.set({"pre-key":{[e]:null}}),loadSignedPreKey:()=>{let e=n.signedPreKey;return{privKey:Buffer.from(e.keyPair.private),pubKey:Buffer.from(e.keyPair.public)}},loadSenderKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("sender-key",[a]);return A?nc.deserialize(A):new nc},storeSenderKey:async(e,a)=>{let A=e.toString(),r=JSON.stringify(a.serialize());await t.set({"sender-key":{[A]:Buffer.from(r,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from($o(e.public))}}}}var EIe=ze(hIe(),1),aQ=(0,EIe.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var sXe=[2,3e3,1043857760];var Hf="https://web.whatsapp.com",$ne="https://call.whatsapp.com/video/",ese="https://call.whatsapp.com/voice/",kE="CB:",uIe="TAG:";var dse=Buffer.from([6,0]),pse=Buffer.from([6,1]),eH=Buffer.from([6,5]),lFA=Buffer.from([6,6]),Yf=10080*60,CIe=1440*60,BIe=336*60*60,Bse="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",gXe=3,Jg=Buffer.from([5]),fIe=Buffer.from([87,65,6,gXe]),Ase=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,tH={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},iQ=[ne.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,ne.HistorySync.HistorySyncType.PUSH_NAME,ne.HistorySync.HistorySyncType.RECENT,ne.HistorySync.HistorySyncType.FULL,ne.HistorySync.HistorySyncType.ON_DEMAND,ne.HistorySync.HistorySyncType.NON_BLOCKING_DATA,ne.HistorySync.HistorySyncType.INITIAL_STATUS_V3],MI={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},QIe={version:sXe,browser:AM.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:aQ.child({class:"baileys"}),emitOwnEvents:!0,defaultQueryTimeoutMs:6e4,customUploadHosts:[],retryRequestDelayMs:250,maxMsgRetryCount:5,fireInitQueries:!0,auth:void 0,markOnlineOnConnect:!0,syncFullHistory:!0,patchMessageBeforeSending:n=>n,shouldSyncHistoryMessage:({syncType:n})=>n!==ne.HistorySync.HistorySyncType.FULL,shouldIgnoreJid:()=>!1,linkPreviewImageThumbnailWidth:192,transactionOpts:{maxCommitRetries:10,delayBetweenTriesMs:3e3},generateHighQualityLinkPreview:!1,enableAutoSessionRecreation:!0,enableRecentMessageCache:!0,options:{},appStateMacVerification:{patch:!1,snapshot:!1},countryCode:"US",getMessage:async()=>{},cachedGroupMetadata:async()=>{},makeSignalRepository:pge},YU={image:"/mms/image",video:"/mms/video",document:"/mms/document",audio:"/mms/audio",sticker:"/mms/image","thumbnail-link":"/mms/image","product-catalog-image":"/product/image","md-app-state":"","md-msg-hist":"/mms/md-app-state","biz-cover-photo":"/pps/biz-cover-photo"},Kne={audio:"Audio",document:"Document",gif:"Video",image:"Image",ppic:"",product:"Image",ptt:"Audio",sticker:"Image",video:"Video","thumbnail-document":"Document Thumbnail","thumbnail-image":"Image Thumbnail","thumbnail-video":"Video Thumbnail","thumbnail-link":"Link Thumbnail","md-msg-hist":"History","md-app-state":"App State","product-catalog-image":"","payment-bg-image":"Payment Background",ptv:"Video","biz-cover-photo":"Image"},tse=Object.keys(YU),yIe=12e4,oQ=5,mIe=812,SIe=3e4,yK={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var wIe=ze(jr(),1);import{createHash as cXe}from"crypto";import{createWriteStream as IXe,promises as lXe}from"fs";import{tmpdir as dXe}from"os";import{join as pXe}from"path";var DIe=n=>{let t=le(n,"product_catalog"),o=PA(t,"product").map(nQ),i=le(t,"paging");return{products:o,nextPageCursor:i?jA(i,"after"):void 0}},OIe=n=>{let t=le(n,"collections");return{collections:PA(t,"collection").map(i=>{let e=jA(i,"id"),a=jA(i,"name"),A=PA(i,"product").map(nQ);return{id:e,name:a,products:A,status:uXe(i)}})}},bIe=n=>{let t=le(n,"order"),o=PA(t,"product").map(a=>{let A=le(a,"image");return{id:jA(a,"id"),name:jA(a,"name"),imageUrl:jA(A,"url"),price:+jA(a,"price"),currency:jA(a,"currency"),quantity:+jA(a,"quantity")}}),i=le(t,"price");return{price:{total:+jA(i,"total"),currency:jA(i,"currency")},products:o}},mK=(n,t)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof t.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(t.name)}),typeof t.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(t.description)}),typeof t.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(t.retailerId)}),t.images.length&&i.push({tag:"media",attrs:{},content:t.images.map(a=>{if(!("url"in a))throw new wIe.Boom("Expected img for product to already be uploaded",{statusCode:400});return{tag:"image",attrs:{},content:[{tag:"url",attrs:{},content:Buffer.from(a.url.toString())}]}})}),typeof t.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(t.price.toString())}),typeof t.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(t.currency)}),"originCountryCode"in t&&(typeof t.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(t.originCountryCode)}]})),typeof t.isHidden<"u"&&(o.is_hidden=t.isHidden.toString()),{tag:"product",attrs:o,content:i}},nQ=n=>{let t=n.attrs.is_hidden==="true",o=jA(n,"id"),i=le(n,"media"),e=le(n,"status_info");return{id:o,imageUrls:EXe(i),reviewStatus:{whatsapp:jA(e,"status")},availability:"in stock",name:jA(n,"name"),retailerId:jA(n,"retailer_id"),url:jA(n,"url"),description:jA(n,"description"),price:+jA(n,"price"),currency:jA(n,"currency"),isHidden:t}};async function SK(n,t,o=3e4){return n={...n,images:n.images?await hXe(n.images,t,o):n.images},n}var hXe=async(n,t,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let I=e.url.toString();if(I.includes(".whatsapp.net"))return{url:I}}let{stream:a}=await Lf(e),A=cXe("sha256"),r=pXe(dXe(),"img"+zr()),s=IXe(r);for await(let I of a)A.update(I),s.write(I);let g=A.digest("base64"),{directPath:c}=await t(r,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await lXe.unlink(r).catch(I=>console.log("Error deleting temp file ",I)),{url:Uf(c)}})),EXe=n=>{let t=le(n,"image");return{requested:jA(t,"request_image_url"),original:jA(t,"original_image_url")}},uXe=n=>{let t=le(n,"status_info");return{status:jA(t,"status"),canAppeal:jA(t,"can_appeal")==="true"}};var gQ=ze(jr(),1);import{randomBytes as _K}from"crypto";var pn=null;try{pn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Gt(n,t,o){this.low=n|0,this.high=t|0,this.unsigned=!!o}Gt.prototype.__isLong__;Object.defineProperty(Gt.prototype,"__isLong__",{value:!0});function si(n){return(n&&n.__isLong__)===!0}function MIe(n){var t=Math.clz32(n&-n);return n?31-t:t}Gt.isLong=si;var _Ie={},TIe={};function wd(n,t){var o,i,e;return t?(n>>>=0,(e=0<=n&&n<256)&&(i=TIe[n],i)?i:(o=St(n,0,!0),e&&(TIe[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=_Ie[n],i)?i:(o=St(n,n<0?-1:0,!1),e&&(_Ie[n]=o),o))}Gt.fromInt=wd;function hn(n,t){if(isNaN(n))return t?sc:es;if(t){if(n<0)return sc;if(n>=vIe)return FIe}else{if(n<=-RIe)return Ao;if(n+1>=RIe)return GIe}return n<0?hn(-n,t).neg():St(n%PE|0,n/PE|0,t)}Gt.fromNumber=hn;function St(n,t,o){return new Gt(n,t,o)}Gt.fromBits=St;var bM=Math.pow;function DK(n,t,o){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(o=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?sc:es;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return DK(n.substring(1),t,o).neg();for(var e=hn(bM(o,8)),a=es,A=0;A>>0:this.low};He.toNumber=function(){return this.unsigned?(this.high>>>0)*PE+(this.low>>>0):this.high*PE+(this.low>>>0)};He.toString=function(t){if(t=t||10,t<2||36>>0,c=g.toString(t);if(A=s,A.isZero())return c+r;for(;c.length<6;)c="0"+c;r=""+c+r}};He.getHighBits=function(){return this.high};He.getHighBitsUnsigned=function(){return this.high>>>0};He.getLowBits=function(){return this.low};He.getLowBitsUnsigned=function(){return this.low>>>0};He.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ao)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,o=31;o>0&&(t&1<>21;return t?this.unsigned?!1:t===-1&&!(this.low===0&&this.high===-2097152):!0};He.isZero=function(){return this.high===0&&this.low===0};He.eqz=He.isZero;He.isNegative=function(){return!this.unsigned&&this.high<0};He.isPositive=function(){return this.unsigned||this.high>=0};He.isOdd=function(){return(this.low&1)===1};He.isEven=function(){return(this.low&1)===0};He.equals=function(t){return si(t)||(t=En(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};He.eq=He.equals;He.notEquals=function(t){return!this.eq(t)};He.neq=He.notEquals;He.ne=He.notEquals;He.lessThan=function(t){return this.comp(t)<0};He.lt=He.lessThan;He.lessThanOrEqual=function(t){return this.comp(t)<=0};He.lte=He.lessThanOrEqual;He.le=He.lessThanOrEqual;He.greaterThan=function(t){return this.comp(t)>0};He.gt=He.greaterThan;He.greaterThanOrEqual=function(t){return this.comp(t)>=0};He.gte=He.greaterThanOrEqual;He.ge=He.greaterThanOrEqual;He.compare=function(t){if(si(t)||(t=En(t)),this.eq(t))return 0;var o=this.isNegative(),i=t.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};He.comp=He.compare;He.negate=function(){return!this.unsigned&&this.eq(Ao)?Ao:this.not().add(vE)};He.neg=He.negate;He.add=function(t){si(t)||(t=En(t));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=t.high>>>16,r=t.high&65535,s=t.low>>>16,g=t.low&65535,c=0,I=0,d=0,B=0;return B+=a+g,d+=B>>>16,B&=65535,d+=e+s,I+=d>>>16,d&=65535,I+=i+r,c+=I>>>16,I&=65535,c+=o+A,c&=65535,St(d<<16|B,c<<16|I,this.unsigned)};He.subtract=function(t){return si(t)||(t=En(t)),this.add(t.neg())};He.sub=He.subtract;He.multiply=function(t){if(this.isZero())return this;if(si(t)||(t=En(t)),pn){var o=pn.mul(this.low,this.high,t.low,t.high);return St(o,pn.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?sc:es;if(this.eq(Ao))return t.isOdd()?Ao:es;if(t.eq(Ao))return this.isOdd()?Ao:es;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(kIe)&&t.lt(kIe))return hn(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,r=t.high>>>16,s=t.high&65535,g=t.low>>>16,c=t.low&65535,I=0,d=0,B=0,f=0;return f+=A*c,B+=f>>>16,f&=65535,B+=a*c,d+=B>>>16,B&=65535,B+=A*g,d+=B>>>16,B&=65535,d+=e*c,I+=d>>>16,d&=65535,d+=a*g,I+=d>>>16,d&=65535,d+=A*s,I+=d>>>16,d&=65535,I+=i*c+e*g+a*s+A*r,I&=65535,St(B<<16|f,I<<16|d,this.unsigned)};He.mul=He.multiply;He.divide=function(t){if(si(t)||(t=En(t)),t.isZero())throw Error("division by zero");if(pn){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var o=(this.unsigned?pn.div_u:pn.div_s)(this.low,this.high,t.low,t.high);return St(o,pn.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?sc:es;var i,e,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return sc;if(t.gt(this.shru(1)))return PIe;a=sc}else{if(this.eq(Ao)){if(t.eq(vE)||t.eq(wK))return Ao;if(t.eq(Ao))return vE;var A=this.shr(1);return i=A.div(t).shl(1),i.eq(es)?t.isNegative()?vE:wK:(e=this.sub(t.mul(i)),a=i.add(e.div(t)),a)}else if(t.eq(Ao))return this.unsigned?sc:es;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=es}for(e=this;e.gte(t);){i=Math.max(1,Math.floor(e.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(i)/Math.LN2),s=r<=48?1:bM(2,r-48),g=hn(i),c=g.mul(t);c.isNegative()||c.gt(e);)i-=s,g=hn(i,this.unsigned),c=g.mul(t);g.isZero()&&(g=vE),a=a.add(g),e=e.sub(c)}return a};He.div=He.divide;He.modulo=function(t){if(si(t)||(t=En(t)),pn){var o=(this.unsigned?pn.rem_u:pn.rem_s)(this.low,this.high,t.low,t.high);return St(o,pn.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};He.mod=He.modulo;He.rem=He.modulo;He.not=function(){return St(~this.low,~this.high,this.unsigned)};He.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};He.clz=He.countLeadingZeros;He.countTrailingZeros=function(){return this.low?MIe(this.low):MIe(this.high)+32};He.ctz=He.countTrailingZeros;He.and=function(t){return si(t)||(t=En(t)),St(this.low&t.low,this.high&t.high,this.unsigned)};He.or=function(t){return si(t)||(t=En(t)),St(this.low|t.low,this.high|t.high,this.unsigned)};He.xor=function(t){return si(t)||(t=En(t)),St(this.low^t.low,this.high^t.high,this.unsigned)};He.shiftLeft=function(t){return si(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?St(this.low<>>32-t,this.unsigned):St(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):St(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};He.shr=He.shiftRight;He.shiftRightUnsigned=function(t){return si(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?St(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?St(this.high,0,this.unsigned):St(this.high>>>t-32,0,this.unsigned)};He.shru=He.shiftRightUnsigned;He.shr_u=He.shiftRightUnsigned;He.rotateLeft=function(t){var o;return si(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?St(this.high,this.low,this.unsigned):t<32?(o=32-t,St(this.low<>>o,this.high<>>o,this.unsigned)):(t-=32,o=32-t,St(this.high<>>o,this.low<>>o,this.unsigned))};He.rotl=He.rotateLeft;He.rotateRight=function(t){var o;return si(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?St(this.high,this.low,this.unsigned):t<32?(o=32-t,St(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,o=32-t,St(this.low<>>t,this.high<>>t,this.unsigned))};He.rotr=He.rotateRight;He.toSigned=function(){return this.unsigned?St(this.low,this.high,!1):this};He.toUnsigned=function(){return this.unsigned?this:St(this.low,this.high,!0)};He.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};He.toBytesLE=function(){var t=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};He.toBytesBE=function(){var t=this.high,o=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};Gt.fromBytes=function(t,o,i){return i?Gt.fromBytesLE(t,o):Gt.fromBytesBE(t,o)};Gt.fromBytesLE=function(t,o){return new Gt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,o)};Gt.fromBytesBE=function(t,o){return new Gt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],o)};typeof BigInt=="function"&&(Gt.fromBigInt=function(t,o){var i=Number(BigInt.asIntN(32,t)),e=Number(BigInt.asIntN(32,t>>BigInt(32)));return St(i,e,o)},Gt.fromValue=function(t,o){return typeof t=="bigint"?Gt.fromBigInt(t,o):En(t,o)},He.toBigInt=function(){var t=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new ic;return{mutex(t){return n.runExclusive(t)}}},LIe=()=>{let n=new Map;return{async mutex(t,o){let i=n.get(t);i||(i={mutex:new ic,refCount:0},n.set(t,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(t)===i&&n.delete(t)}}}};function UIe(n,t,o=10){let i=[],e=!1;return{enqueue:(A,r)=>{if(i.push({type:A,node:r}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&t.isWsOpen();){let{type:c,node:I}=i.shift(),d=n.get(c);if(!d){t.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await d(I).catch(B=>t.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await t.yieldToEventLoop())}e=!1})().catch(g=>t.onUnexpectedError(g,"processing offline nodes"))}}}var LM=ze(jr(),1);var NI=ze(jr(),1);var MM=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(t){let o=[],i;if(t.tag==="devices"){Vi(t);let e=le(t,"device-list"),a=le(t,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:r}of e.content){let s=+r.id,g=+r["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(r.is_hosted&&r.is_hosted==="true")})}a?.tag==="key-index-list"&&(i={timestamp:+a.attrs.ts,signedKeyIndex:a?.content,expectedTimestamp:a.attrs.expected_ts?+a.attrs.expected_ts:void 0})}return{deviceList:o,keyIndex:i}}};var ng=class{withId(t){return this.id=t,this}withLid(t){return this.lid=t,this}withPhone(t){return this.phone=t,this}withUsername(t){return this.username=t,this}withUsernameKey(t){return this.usernameKey=t,this}withType(t){return this.type=t,this}withPersonaId(t){return this.personaId=t,this}};var _M=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(t){return t.phone?{tag:"contact",attrs:{},content:t.phone}:t.username?{tag:"contact",attrs:{username:t.username,...t.usernameKey?{pin:t.usernameKey}:{},...t.lid?{lid:t.lid}:{}}}:t.type?{tag:"contact",attrs:{type:t.type}}:{tag:"contact",attrs:{}}}parser(t){return t.tag==="contact"?(Vi(t),t?.attrs?.type==="in"):!1}};var TM=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="status"){Vi(t);let o=t?.content?.toString()??null,i=new Date(+(t?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):t.attrs?.code&&+t.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var NM=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="disappearing_mode"){Vi(t);let o=+t?.attrs.duration,i=new Date(+(t?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var RM=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(t){return null}parser(t){return t.tag==="username"?(Vi(t),typeof t.content=="string"?t.content:null):null}};var kM=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(t){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:t.personaId}}]}}parser(t){let o=le(t,"bot"),i=le(o,"profile"),e=le(i,"commands"),a=le(i,"prompts"),A=[],r=[];for(let s of PA(e,"command"))A.push({name:jA(s,"name"),description:jA(s,"description")});for(let s of PA(a,"prompt"))r.push(`${jA(s,"emoji")} ${jA(s,"text")}`);return{isDefault:!!le(i,"default"),jid:t.attrs.jid,name:jA(i,"name"),attributes:jA(i,"attributes"),description:jA(i,"description"),category:jA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:jA(e,"description"),commands:A,prompts:r}}};var vM=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(t){return t.lid?{tag:"lid",attrs:{jid:t.lid}}:null}parser(t){return t.tag==="lid"?t.attrs.val:null}};var sg=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(t){return this.mode=t,this}withContext(t){return this.context=t,this}withUser(t){return this.users.push(t),this}parseUSyncQueryResult(t){if(t?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=le(t,"usync"),a=e?le(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,r)=>{let s=r?.attrs.jid;if(s){let g=Array.isArray(r?.content)?Object.fromEntries(r.content.map(c=>{let I=c.tag,d=o[I];return d?[I,d(c)]:[I,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new MM),this}withContactProtocol(){return this.protocols.push(new _M),this}withStatusProtocol(){return this.protocols.push(new TM),this}withDisappearingModeProtocol(){return this.protocols.push(new NM),this}withBotProfileProtocol(){return this.protocols.push(new kM),this}withLIDProtocol(){return this.protocols.push(new vM),this}withUsernameProtocol(){return this.protocols.push(new RM),this}};var $r=ze(jr(),1);import{randomBytes as bK}from"crypto";import{URL as QXe}from"url";import{promisify as yXe}from"util";var PM=class{constructor(t={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,t)}};import{EventEmitter as BXe}from"events";var GM=class extends BXe{constructor(t,o){super(),this.url=t,this.config=o,this.setMaxListeners(0)}};var FM=class extends GM{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===Yo.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===Yo.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===Yo.CLOSING}get isConnecting(){return this.socket?.readyState===Yo.CONNECTING}connect(){if(this.socket)return;this.socket=new Yo(this.url,{origin:Hf,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let t=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of t)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let t=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await t,this.socket=null}send(t,o){return this.socket?.send(t,o),!!this.socket}};var OK=ze(jr(),1);var fXe=(n,t,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:OA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:t},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),sQ=async(n,t,o,i,e)=>{let a=await fXe(n,t,i,e),A=le(a,"result");if(A?.content){let s=JSON.parse(A.content.toString());if(s.errors&&s.errors.length>0){let c=s.errors.map(B=>B.message||"Unknown error").join(", "),I=s.errors[0],d=I.extensions?.error_code||400;throw new OK.Boom(`GraphQL server error: ${c}`,{statusCode:d,data:I})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let r=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new OK.Boom(`Failed to ${r}, unexpected response structure.`,{statusCode:400,data:a})};var HIe=n=>{let{waWebSocketUrl:t,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:r,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:I}=n,d=new PM,B=0,f=z$(),Q=()=>`${f}${oe++}`;r&&i.warn({},"\u26A0\uFE0F The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version."),a[1].toLocaleLowerCase().includes("android")&&i.warn("\u26A0\uFE0F Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk."),iQ.map(de=>n.shouldSyncHistoryMessage({syncType:de})).filter(de=>de===!1).length===iQ.length&&i.warn("\u26A0\uFE0F DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS");let m=typeof t=="string"?new QXe(t):t;if(n.mobile||m.protocol==="tcp:")throw new $r.Boom("Mobile API is not supported anymore",{statusCode:tr.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let T=Dr.generateKeyPair(),_=Cse({keyPair:T,NOISE_HEADER:fIe,logger:i,routingInfo:A?.creds?.routingInfo}),R=new FM(m,n);R.connect();let H=yXe(R.send),F=async de=>{if(!R.isOpen)throw new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed});let Qe=_.encodeFrame(de);await Th(o,async(Me,oA)=>{try{await H.call(R,Qe),Me()}catch(dA){oA(dA)}})},L=de=>{i.level==="trace"&&i.trace({xml:xn(de),msg:"xml send"});let Qe=l$(de);return F(Qe)},q=async(de,Qe=s)=>{let Me,oA;try{return await Th(Qe,(FA,Yt)=>(Me=ct=>{FA(ct)},oA=ct=>{Yt(ct||new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed}))},R.on(`TAG:${de}`,Me),R.on("close",oA),R.on("error",oA),()=>Yt(new $r.Boom("Query Cancelled"))))}catch(dA){if(dA instanceof $r.Boom&&dA.output?.statusCode===tr.timedOut){i?.warn?.({msgId:de},"timed out waiting for message");return}throw dA}finally{Me&&R.off(`TAG:${de}`,Me),oA&&(R.off("close",oA),R.off("error",oA))}},z=async(de,Qe)=>{de.attrs.id||(de.attrs.id=Q());let Me=de.attrs.id,oA=await Th(Qe,async(dA,FA)=>{let Yt=q(Me,Qe).catch(FA);L(de).then(async()=>dA(await Yt)).catch(FA)});return oA&&"tag"in oA&&Vi(oA),oA},K=async()=>{let de=await z({tag:"iq",attrs:{to:OA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!le(de,"digest"))throw await Xe(),new Error("encrypt/get digest returned no digest node")},G=async()=>{let de=(J.signedPreKey.keyId||0)+1,Qe=await PD(J.signedIdentityKey,de);await z({tag:"iq",attrs:{to:OA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[jf(Qe)]}]}),k.emit("creds.update",{signedPreKey:Qe})},V=async de=>{if(de.protocols.length===0)throw new $r.Boom("USyncQuery must have at least one protocol");let Me=de.users.map(ct=>({tag:"user",attrs:{jid:ct.phone?void 0:ct.id},content:de.protocols.map(br=>br.getUserElement(ct)).filter(br=>br!==null)})),oA={tag:"list",attrs:{},content:Me},dA={tag:"query",attrs:{},content:de.protocols.map(ct=>ct.getQueryElement())},FA={tag:"iq",attrs:{to:OA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:de.context,mode:de.mode,sid:Q(),last:"true",index:"0"},content:[dA,oA]}]},Yt=await z(FA);return de.parseUSyncQueryResult(Yt)},U=async(...de)=>{let Qe=new sg,Me=!1;for(let dA of de)if(qA(dA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{Me||(Me=!0,Qe=Qe.withContactProtocol());let FA=`+${dA.replace("+","").split("@")[0]?.split(":")[0]}`;Qe.withUser(new ng().withPhone(FA))}if(Qe.users.length===0)return[];let oA=await V(Qe);if(oA)return oA.list.filter(dA=>!!dA.contact).map(({contact:dA,id:FA})=>({jid:FA,exists:dA}))},N=async de=>{let Qe=new sg().withLIDProtocol().withContext("background");for(let oA of de)if(qA(oA)){i?.warn("LID user found in LID fetch call");continue}else Qe.withUser(new ng().withId(oA));if(Qe.users.length===0)return[];let Me=await V(Qe);return Me?Me.list.filter(oA=>!!oA.lid).map(({lid:oA,id:dA})=>({pn:dA,lid:oA})):[]},k=$se(i),{creds:J}=A,X=Yse(A.keys,i,g),ae=I({creds:J,keys:X},i,N),De,oe=1,Se,Be,Re=!1,Ne=[],Je=(de,Qe)=>{i.error({err:de},`unexpected error in '${Qe}'`)},ve=async de=>{if(!R.isOpen)throw new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed});let Qe,Me,oA=Th(o,(dA,FA)=>{Qe=dA,Me=MK(FA),R.on("frame",Qe),R.on("close",Me),R.on("error",Me)}).finally(()=>{R.off("frame",Qe),R.off("close",Me),R.off("error",Me)});return de&&F(de).catch(Me),oA},aA=async()=>{let de={clientHello:{ephemeral:T.public}};de=ne.HandshakeMessage.fromObject(de),i.info({browser:a,helloMsg:de},"connected to WA");let Qe=ne.HandshakeMessage.encode(de).finish(),Me=await ve(Qe),oA=ne.HandshakeMessage.decode(Me);i.trace({handshake:oA},"handshake recv from WA");let dA=_.processHandshake(oA,J.noiseKey),FA;J.me?(FA=cse(J.me.id,n),i.info({node:FA},"logging in...")):(FA=Ise(J,n),i.info({node:FA},"not logged in, attempting registration..."));let Yt=_.encrypt(ne.ClientPayload.encode(FA).finish());await F(ne.HandshakeMessage.encode({clientFinish:{static:dA,payload:Yt}}).finish()),await _.finishInit(),Ze()},fe=async()=>{let de=await z({tag:"iq",attrs:{id:Q(),xmlns:"encrypt",type:"get",to:OA},content:[{tag:"count",attrs:{}}]});return+le(de,"count").attrs.value},Ie=null,Xe=async(de=oQ)=>{if(Ie){i.debug("Pre-key upload already in progress, waiting for completion"),await Ie;return}let Qe=async Me=>{i.info({count:de,retryCount:Me},"uploading pre-keys");let oA=await X.transaction(async()=>{i.debug({requestedCount:de},"generating pre-keys with requested count");let{update:dA,node:FA}=await nse({creds:J,keys:X},de);return k.emit("creds.update",dA),FA},J?.me?.id||"upload-pre-keys");try{await z(oA),i.info({count:de},"uploaded pre-keys successfully")}catch(dA){if(i.error({uploadError:dA.toString(),count:de},"Failed to upload pre-keys to server"),Me<3){let FA=Math.min(1e3*Math.pow(2,Me),1e4);return i.info(`Retrying pre-key upload in ${FA}ms`),await new Promise(Yt=>setTimeout(Yt,FA)),Qe(Me+1)}throw dA}};Ie=Promise.race([Qe(0),new Promise((Me,oA)=>setTimeout(()=>oA(new $r.Boom("Pre-key upload timeout",{statusCode:408})),SIe))]);try{await Ie}finally{Ie=null}},je=async()=>{let de=J.nextPreKeyId-1;return de<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await X.get("pre-key",[de.toString()]))[de.toString()],currentPreKeyId:de}},be=async()=>{try{let de=0,Qe=await fe();Qe===0?de=mIe:de=oQ;let{exists:Me,currentPreKeyId:oA}=await je();i.info(`${Qe} pre-keys found on server`),i.info(`Current prekey ID: ${oA}, exists in storage: ${Me}`);let dA=Qe<=de,FA=!Me&&oA>0;if(dA||FA){let ct=[];dA&&ct.push(`server count low (${Qe})`),FA&&ct.push(`current prekey ${oA} missing from storage`),i.info(`Uploading PreKeys due to: ${ct.join(", ")}`),await Xe(de)}else i.info(`PreKey validation passed - Server: ${Qe}, Current prekey ${oA} exists`)}catch(de){i.error({error:de},"Failed to check/upload pre-keys during initialization")}},EA=async de=>{await _.decodeFrame(de,Qe=>{De=new Date;let Me=!1;if(Me=R.emit("frame",Qe),!(Qe instanceof Uint8Array)){let oA=Qe.attrs.id;i.level==="trace"&&i.trace({xml:xn(Qe),msg:"recv xml"}),Me=R.emit(`${uIe}${oA}`,Qe)||Me;let dA=Qe.tag,FA=Qe.attrs||{},Yt=Array.isArray(Qe.content)?Qe.content[0]?.tag:"";for(let ct of Object.keys(FA))Me=R.emit(`${kE}${dA},${ct}:${FA[ct]},${Yt}`,Qe)||Me,Me=R.emit(`${kE}${dA},${ct}:${FA[ct]}`,Qe)||Me,Me=R.emit(`${kE}${dA},${ct}`,Qe)||Me;Me=R.emit(`${kE}${dA},,${Yt}`,Qe)||Me,Me=R.emit(`${kE}${dA}`,Qe)||Me,!Me&&i.level==="debug"&&i.debug({unhandled:!0,msgId:oA,fromMe:!1,frame:Qe},"communication recv")}})},hA=async de=>{if(Re){i.trace({trace:de?.stack},"connection already closed");return}if(Re=!0,i.info({trace:de?.stack},de?"connection errored":"connection closed"),clearInterval(Se),clearTimeout(Be),R.removeAllListeners("close"),R.removeAllListeners("open"),R.removeAllListeners("message"),ae.close?.(),!R.isClosed&&!R.isClosing)try{await R.close()}catch{}for(let Qe of Ne)try{await Qe(de)}catch(Me){i.error({err:Me},"error in socket end handler")}k.emit("connection.update",{connection:"close",lastDisconnect:{error:de,date:new Date}}),k.removeAllListeners("connection.update"),k.destroy()},iA=async()=>{if(R.isOpen)return;if(R.isClosed||R.isClosing)throw new $r.Boom("Connection Closed",{statusCode:tr.connectionClosed});let de,Qe;await new Promise((Me,oA)=>{de=()=>Me(void 0),Qe=MK(oA),R.on("open",de),R.on("close",Qe),R.on("error",Qe)}).finally(()=>{R.off("open",de),R.off("close",Qe),R.off("error",Qe)})},Ze=()=>Se=setInterval(()=>{De||(De=new Date),Date.now()-De.getTime()>e+5e3?hA(new $r.Boom("Connection was lost",{statusCode:tr.connectionLost})):R.isOpen?z({tag:"iq",attrs:{id:Q(),to:OA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(Qe=>{i.error({trace:Qe.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),bA=de=>z({tag:"iq",attrs:{to:OA,xmlns:"passive",type:"set"},content:[{tag:de,attrs:{}}]}),Ce=async de=>{let Qe=A.creds.me?.id;Qe&&await L({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:Qe,reason:"user_initiated"}}]}),hA(new $r.Boom(de||"Intentional Logout",{statusCode:tr.loggedOut}))},ke=async(de,Qe)=>{let Me=Qe??$$(bK(5));if(Qe&&Qe?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=Me,A.creds.me={id:Sr(de,"s.whatsapp.net"),name:"~"},k.emit("creds.update",A.creds),await L({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:A.creds.me.id,stage:"companion_hello",should_show_push_notification:"true"},content:[{tag:"link_code_pairing_wrapped_companion_ephemeral_pub",attrs:{},content:await Ue()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:MH(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function Ue(){let de=bK(32),Qe=bK(16),Me=await GD(A.creds.pairingCode,de),oA=P$(A.creds.pairingEphemeralKeyPair.public,Me,Qe);return Buffer.concat([de,Qe,oA])}let MA=de=>z({tag:"iq",attrs:{to:OA,id:Q(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:de}]});R.on("message",EA),R.on("open",async()=>{try{await aA()}catch(de){i.error({err:de},"error in validating connection"),hA(de)}}),R.on("error",MK(hA)),R.on("close",()=>void hA(new $r.Boom("Connection Terminated",{statusCode:tr.connectionClosed}))),R.on("CB:xmlstreamend",()=>void hA(new $r.Boom("Connection Terminated by Server",{statusCode:tr.connectionClosed}))),R.on("CB:iq,type:set,pair-device",async de=>{let Qe={tag:"iq",attrs:{to:OA,type:"result",id:de.attrs.id}};await L(Qe);let Me=le(de,"pair-device"),oA=PA(Me,"ref"),dA=Buffer.from(J.noiseKey.public).toString("base64"),FA=Buffer.from(J.signedIdentityKey.public).toString("base64"),Yt=J.advSecretKey,ct=c||6e4,br=()=>{if(!R.isOpen)return;let or=oA.shift();if(!or){hA(new $r.Boom("QR refs attempts ended",{statusCode:tr.timedOut}));return}let mo=or.content.toString("utf-8"),to=tge(mo,dA,FA,Yt,a);k.emit("connection.update",{qr:to}),Be=setTimeout(br,ct),ct=c||2e4};br()}),R.on("CB:iq,,pair-success",async de=>{i.debug("pair success recv");try{_A(de);let{reply:Qe,creds:Me}=lse(de,J);i.info({me:Me.me,platform:Me.platform},"pairing configured successfully, expect to restart the connection..."),k.emit("creds.update",Me),k.emit("connection.update",{isNewLogin:!0,qr:void 0}),await L(Qe),wA()}catch(Qe){i.info({trace:Qe.stack},"error in pairing"),hA(Qe)}}),R.on("CB:success",async de=>{try{_A(de),await be(),await bA("active");try{await K()}catch(Qe){i.warn({e:Qe},"failed to run digest after login")}}catch(Qe){i.warn({err:Qe},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(Be),k.emit("creds.update",{me:{...A.creds.me,lid:de.attrs.lid}}),k.emit("connection.update",{connection:"open"}),wA(),de.attrs.lid&&A.creds.me?.id){let Qe=de.attrs.lid;process.nextTick(async()=>{try{let Me=A.creds.me.id;await ae.lidMapping.storeLIDPNMappings([{lid:Qe,pn:Me}]);let{user:oA,device:dA}=fA(Me);await A.keys.set({"device-list":{[oA]:[dA?.toString()||"0"]}}),await ae.migrateSession(Me,Qe),i.info({myPN:Me,myLID:Qe},"Own LID session created successfully")}catch(Me){i.error({error:Me,lid:Qe},"Failed to create own LID session")}})}}),R.on("CB:stream:error",de=>{let[Qe]=vs(de);i.error({reasonNode:Qe,fullErrorNode:de},"stream errored out");let{reason:Me,statusCode:oA}=W$(de);hA(new $r.Boom(`Stream Errored (${Me})`,{statusCode:oA,data:Qe||de}))}),R.on("CB:failure",de=>{let Qe=+(de.attrs.reason||500);hA(new $r.Boom("Connection Failure",{statusCode:Qe,data:de.attrs}))}),R.on("CB:ib,,downgrade_webclient",()=>{hA(new $r.Boom("Multi-device beta not joined",{statusCode:tr.multideviceMismatch}))}),R.on("CB:ib,,offline_preview",async de=>{i.info("offline preview received",JSON.stringify(de)),await L({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),R.on("CB:ib,,edge_routing",de=>{let Qe=le(de,"edge_routing"),Me=le(Qe,"routing_info");Me?.content&&(A.creds.routingInfo=Buffer.from(Me?.content),k.emit("creds.update",A.creds))});let Ke=!1;process.nextTick(()=>{J.me?.id&&(k.buffer(),Ke=!0),k.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),R.on("CB:ib,,offline",de=>{let Me=+(le(de,"offline")?.attrs.count||0);i.info(`handled ${Me} offline messages/notifications`),Ke&&(k.flush(),i.trace("flushed events for initial buffer")),k.emit("connection.update",{receivedPendingNotifications:!0})}),k.on("creds.update",de=>{let Qe=de.me?.name;J.me?.name!==Qe&&(i.debug({name:Qe},"updated pushName"),L({tag:"presence",attrs:{name:Qe}}).catch(Me=>{i.warn({trace:Me.stack},"error in sending presence update on name change")})),Object.assign(J,de)});let _A=({attrs:de})=>{let Qe=de?.t;if(!Qe)return;let Me=Number(Qe);if(Number.isNaN(Me)||Me<=0)return;let oA=Date.now();B=Me*1e3-oA,i.debug({offset:B},"calculated server time offset")},ot=()=>{let de=3*yK.Day;return((Date.now()+B+de)%yK.Week).toString()},wA=async()=>{if(!R.isOpen)return;let de={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:ot()}}]};try{await L(de)}catch(Qe){i.debug({error:Qe},"failed to send unified_session telemetry")}},ht=de=>{Ne.push(de)},Br=async()=>{let de=await sQ({},ha.REACHOUT_TIMELOCK,Ra.xwa2_fetch_account_reachout_timelock,z,Q),Qe={isActive:!!de?.is_active,timeEnforcementEnds:de?.time_enforcement_ends&&de?.time_enforcement_ends!=="0"?new Date(parseInt(de.time_enforcement_ends,10)*1e3):void 0,enforcementType:de?.enforcement_type??AI.DEFAULT};return k.emit("connection.update",{reachoutTimeLock:Qe}),Qe},UA=async()=>sQ({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},ha.MESSAGE_CAPPING_INFO,Ra.xwa2_message_capping_info,z,Q);return{type:"md",ws:R,ev:k,authState:{creds:J,keys:X},signalRepository:ae,get user(){return A.creds.me},generateMessageTag:Q,query:z,waitForMessage:q,waitForSocketOpen:iA,sendRawMessage:F,sendNode:L,logout:Ce,end:hA,registerSocketEndHandler:ht,onUnexpectedError:Je,uploadPreKeys:Xe,uploadPreKeysToServerIfRequired:be,digestKeyBundle:K,rotateSignedPreKey:G,requestPairingCode:ke,updateServerTimeOffset:_A,sendUnifiedSession:wA,wamBuffer:d,waitForConnectionUpdate:q$(k),sendWAMBuffer:MA,executeUSyncQuery:V,onWhatsApp:U,fetchAccountReachoutTimelock:Br,fetchNewChatMessageCap:UA}};function MK(n){return t=>{n(new $r.Boom(`WebSocket Error (${t?.message})`,{statusCode:X$(t),data:t}))}}var mXe=(n,t)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return t?.length&&(o.content=t),[o]},KIe=n=>{let{logger:t,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:r}=n,s=HIe(n),{ev:g,ws:c,authState:I,generateMessageTag:d,sendNode:B,query:f,signalRepository:Q,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:T}=s,_=Q.lidMapping.getLIDForPN.bind(Q.lidMapping),R,H={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},F=pa.Connecting,L=gc(),q=gc(),z=gc(),K=gc(),G,V={initialBootstrapComplete:!1,recentSyncComplete:!1},U,N=new Set,k=n.placeholderResendCache||new ac({stdTTL:MI.MSG_RETRY,useClones:!1}),J=async W=>{let{[W]:$}=await I.keys.get("app-state-sync-key",[W]);return $},X=async(W=!1)=>{if(!R||W){let{content:$}=await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"get"},content:[{tag:"privacy",attrs:{}}]});R=QL($?.[0],"category")}return R},ae=async(W,$)=>{await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:W,value:$}}]}]})},De=async W=>{await ae("messages",W)},oe=async W=>{await ae("calladd",W)},Se=async W=>{await ae("last",W)},Be=async W=>{await ae("online",W)},Re=async W=>{await ae("profile",W)},Ne=async W=>{await ae("status",W)},Je=async W=>{await ae("readreceipts",W)},ve=async W=>{await ae("groupadd",W)},aA=async W=>{await f({tag:"iq",attrs:{xmlns:"disappearing_mode",to:OA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:W.toString()}}]})},fe=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"bot",to:OA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),$=le(W,"bot"),re=[];for(let se of PA($,"section"))if(se.attrs.type==="all")for(let we of PA(se,"bot"))re.push({jid:we.attrs.jid,personaId:we.attrs.persona_id});return re},Ie=async(...W)=>{let $=new sg().withStatusProtocol();for(let se of W)$.withUser(new ng().withId(se));let re=await s.executeUSyncQuery($);if(re)return re.list},Xe=async(...W)=>{let $=new sg().withDisappearingModeProtocol();for(let se of W)$.withUser(new ng().withId(se));let re=await s.executeUSyncQuery($);if(re)return re.list},je=async(W,$,re)=>{let se;if(!W)throw new NI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");CA(W)!==CA(I.creds.me.id)?se=CA(W):se=void 0;let{img:we}=await Ub($,re);await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...se?{target:se}:{}},content:[{tag:"picture",attrs:{type:"image"},content:we}]})},be=async W=>{let $;if(!W)throw new NI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");CA(W)!==CA(I.creds.me.id)?$=CA(W):$=void 0,await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...$?{target:$}:{}}})},EA=async W=>{await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(W,"utf-8")}]})},hA=async W=>{await UA({pushNameSetting:W},"")},iA=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"get"}}),$=le(W,"list");return PA($,"item").map(re=>re.attrs.jid)},Ze=async(W,$)=>{let re=CA(W),se,we;if(qA(re)||Ea(re)){if(se=re,$==="block"){let he=await Q.lidMapping.getPNForLID(re);if(!he)throw new NI.Boom(`Unable to resolve PN JID for LID: ${W}`,{statusCode:400});we=CA(he)}}else if(Tt(re)||wr(re)){let he=await Q.lidMapping.getLIDForPN(re);if(!he)throw new NI.Boom(`Unable to resolve LID for PN JID: ${W}`,{statusCode:400});se=he,$==="block"&&(we=CA(re))}else throw new NI.Boom(`Invalid jid: ${W}`,{statusCode:400});let Ee={action:$,jid:se};if($==="block"){if(!we)throw new NI.Boom(`pn_jid required for block: ${W}`,{statusCode:400});Ee.pn_jid=we}await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"set"},content:[{tag:"item",attrs:Ee}]})},bA=async W=>{let $=await f({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:W}}]}]}),re=le($,"business_profile"),se=le(re,"profile");if(se){let we=le(se,"address"),Ee=le(se,"description"),he=le(se,"website"),ye=le(se,"email"),qe=le(le(se,"categories"),"category"),IA=le(se,"business_hours"),yA=IA?PA(IA,"business_hours_config"):void 0,$A=he?.content?.toString();return{wid:se.attrs?.jid,address:we?.content?.toString(),description:Ee?.content?.toString()||"",website:$A?[$A]:[],email:ye?.content?.toString(),category:qe?.content?.toString(),business_hours:{timezone:IA?.attrs?.timezone,business_config:yA?.map(({attrs:vA})=>vA)}}}},Ce=async(W,$)=>{t.info({fromTimestamp:$},"clean dirty bits "+W),await B({tag:"iq",attrs:{to:OA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:d()},content:[{tag:"clean",attrs:{type:W,...$?{timestamp:$.toString()}:null}}]})},ke=W=>({onMutation($){vse($,g,I.creds.me,W?{accountSettings:I.creds.accountSettings}:void 0,t)}}),Ue=g.createBufferedFunction(async(W,$)=>{let re=new Map,se=async ye=>{if(re.has(ye))return re.get(ye)??void 0;let qe=await J(ye);return re.set(ye,qe??null),qe},we={},Ee={};await I.keys.transaction(async()=>{let ye=new Set(W),qe={},IA=new Set;for(;ye.size;){let yA={},$A=[];for(let At of ye){let tA=(await I.keys.get("app-state-sync-version",[At]))[At];tA?(tA=aH(tA),typeof we[At]>"u"&&(we[At]=tA.version)):tA=Jb(),yA[At]=tA;let tt=IA.has(At);tt&&IA.delete(At),t.info(`resyncing ${At} from v${tA.version}${tt?" (forcing snapshot)":""}`),$A.push({tag:"collection",attrs:{name:At,version:tA.version.toString(),return_snapshot:(tt||!tA.version).toString()}})}let vA=await f({tag:"iq",attrs:{to:OA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:$A}]}),YA=await Tse(vA,n?.options);for(let At in YA){let Ge=At,{patches:tA,hasMorePatches:tt,snapshot:ea}=YA[Ge];try{if(ea){let{state:nr,mutationMap:So}=await Rse(Ge,ea,se,we[Ge],e.snapshot,t);yA[Ge]=nr,Object.assign(Ee,So),t.info(`restored state of ${Ge} from snapshot to v${nr.version} with mutations`),await I.keys.set({"app-state-sync-version":{[Ge]:nr}})}if(tA.length){let{state:nr,mutationMap:So}=await oH(Ge,tA,yA[Ge],se,n.options,we[Ge],t,e.patch);await I.keys.set({"app-state-sync-version":{[Ge]:nr}}),t.info(`synced ${Ge} to v${nr.version}`),we[Ge]=nr.version,Object.assign(Ee,So)}tt?t.info(`${Ge} has more patches...`):ye.delete(Ge)}catch(nr){qe[Ge]=(qe[Ge]||0)+1;let So={name:Ge,attempt:qe[Ge],version:yA[Ge].version,statusCode:nr.output?.statusCode,errorType:nr.name,error:nr.stack};zf(nr)&&qe[Ge]>=iH?(t.warn(So,`${Ge} blocked on missing key from v${yA[Ge].version}, parking after ${qe[Ge]} attempts`),N.add(Ge),ye.delete(Ge)):zf(nr)?(t.info(So,`${Ge} blocked on missing key from v${yA[Ge].version}, retrying with snapshot`),IA.add(Ge)):bse(nr,qe[Ge])?(t.warn(So,`failed to sync ${Ge} from v${yA[Ge].version}, giving up`),ye.delete(Ge)):(t.info(So,`failed to sync ${Ge} from v${yA[Ge].version}, forcing snapshot retry`),IA.add(Ge))}}}},I?.creds?.me?.id||"resync-app-state");let{onMutation:he}=ke($);for(let ye in Ee)he(Ee[ye])}),MA=async(W,$="preview",re)=>{let se=CA(W),we=Tt(se)||qA(se),Ee=I.creds.me,he=Ee&&(se===CA(Ee.id)||Ee.lid&&se===CA(Ee.lid)),ye;H.profilePicPrivacyToken&&we&&!he&&(ye=await mH({authState:I,jid:se,getLIDForPN:_})),W=CA(W);let qe=await f({tag:"iq",attrs:{target:W,to:OA,type:"get",xmlns:"w:profile:picture"},content:mXe($,ye)},re);return le(qe,"picture")?.attrs?.url},Ke=async(W,$,re)=>{let se=await f({tag:"call",attrs:{id:d(),to:"@call"},content:[{tag:"link_create",attrs:{media:W},content:$?[{tag:"event",attrs:{start_time:String($.startTime)}}]:void 0}]},re);return le(se,"link_create")?.attrs?.token},_A=async(W,$)=>{let re=I.creds.me,se=W==="available";if(se||W==="unavailable"){if(!re.name){t.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:se}),se&&m(),await B({tag:"presence",attrs:{name:re.name.replace(/@/g,""),type:W}})}else{let{server:we}=fA($);await B({tag:"chatstate",attrs:{from:we==="lid"?re.lid:re.id,to:$},content:[{tag:W==="recording"?"composing":W,attrs:W==="recording"?{media:"audio"}:{}}]})}},ot=async W=>{let $=CA(W),se=Tt($)||qA($)?await mH({authState:I,jid:$,getLIDForPN:_}):void 0;return B({tag:"presence",attrs:{to:W,id:d(),type:"subscribe"},content:se})},wA=({tag:W,attrs:$,content:re})=>{let se,we=$.from,Ee=$.participant||$.from;if(!(a(we)&&we!==OA)){if(W==="presence")se={lastKnownPresence:$.type==="unavailable"?"unavailable":"available",lastSeen:$.last&&$.last!=="deny"?+$.last:void 0,groupOnlineCount:$.count?+$.count:void 0};else if(Array.isArray(re)){let[he]=re,ye=he.tag;ye==="paused"&&(ye="available"),he.attrs?.media==="audio"&&(ye="recording"),se={lastKnownPresence:ye}}else t.error({tag:W,attrs:$,content:re},"recv invalid presence node");se&&g.emit("presence.update",{id:we,presences:{[Ee]:se}})}},ht=async W=>{let $=W.type,re=I.creds.myAppStateKeyId;if(!re)throw new NI.Boom("App state key not present!",{statusCode:400});let se,we;if(await z.mutex(async()=>{await I.keys.transaction(async()=>{t.debug({patch:W},"applying app patch"),await Ue([$],!1);let{[$]:Ee}=await I.keys.get("app-state-sync-version",[$]);se=Ee?aH(Ee):Jb(),we=await Mse(W,re,se,J);let{patch:he,state:ye}=we,qe={tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:$,version:(ye.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:ne.SyncdPatch.encode(he).finish()}]}]}]};await f(qe),await I.keys.set({"app-state-sync-version":{[$]:ye}})},I?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:Ee}=ke(!1),{mutationMap:he}=await oH($,[{...we.patch,version:{version:we.state.version}}],se,J,n.options,void 0,t);for(let ye in he)Ee(he[ye])}},Br=async()=>{let W=await f({tag:"iq",attrs:{to:OA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...I?.creds?.lastPropHash?{hash:I.creds.lastPropHash}:{}}}]}),$=le(W,"props"),re={};$&&($.attrs?.hash&&(I.creds.lastPropHash=$?.attrs?.hash,g.emit("creds.update",I.creds)),re=QL($,"prop"));let se=re[10518]??re.privacy_token_sending_on_all_1_on_1_messages;se!==void 0&&(H.privacyTokenOn1to1=se==="true"||se==="1");let we=re[9666]??re.profile_scraping_privacy_token_in_photo_iq;we!==void 0&&(H.profilePicPrivacyToken=we==="true"||we==="1");let Ee=re[14303]??re.lid_trusted_token_issue_to_lid;return Ee!==void 0&&(H.lidTrustedTokenIssueToLid=Ee==="true"||Ee==="1"),t.debug({serverProps:H},"fetched props"),re},UA=(W,$)=>{let re=kse(W,$);return ht(re)},de=W=>UA({disableLinkPreviews:{isPreviewsDisabled:W}},""),Qe=(W,$,re)=>UA({star:{messages:$,star:re}},W),Me=(W,$)=>UA({contact:$},W),oA=W=>UA({contact:null},W),dA=(W,$)=>UA({addLabel:{...$}},W),FA=(W,$)=>UA({addChatLabel:{labelId:$}},W),Yt=(W,$)=>UA({removeChatLabel:{labelId:$}},W),ct=(W,$,re)=>UA({addMessageLabel:{messageId:$,labelId:re}},W),br=(W,$,re)=>UA({removeMessageLabel:{messageId:$,labelId:re}},W),or=W=>UA({quickReply:W},""),mo=W=>UA({quickReply:{timestamp:W,deleted:!0}},""),to=async()=>{await Promise.all([Br(),iA(),X()])},Ae=g.createBufferedFunction(async(W,$)=>{if(g.emit("messages.upsert",{messages:[W],type:$}),W.pushName){let Ee=W.key.fromMe?I.creds.me.id:W.key.participant||W.key.remoteJid;Ee=CA(Ee),W.key.fromMe||g.emit("contacts.update",[{id:Ee,notify:W.pushName,verifiedName:W.verifiedBizName}]),W.key.fromMe&&W.pushName&&I.creds.me?.name!==W.pushName&&g.emit("creds.update",{me:{...I.creds.me,name:W.pushName}})}let re=jb(W.message),se=re?A(re)&&iQ.includes(re.syncType):!1;if(re&&se){let Ee=re.syncType;Ee===ne.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!V.initialBootstrapComplete&&(V.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===ne.HistorySync.HistorySyncType.RECENT&&re.progress===100&&!V.recentSyncComplete&&(V.recentSyncComplete=!0,clearTimeout(U),U=void 0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===ne.HistorySync.HistorySyncType.RECENT&&!V.recentSyncComplete&&(clearTimeout(U),U=setTimeout(()=>{V.recentSyncComplete||(V.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:ne.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),U=void 0},yIe))}re&&F===pa.AwaitingInitialSync&&(G&&(clearTimeout(G),G=void 0),se?(F=pa.Syncing,t.info("Transitioned to Syncing state")):(F=pa.Online,t.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let we=async()=>{if(F===pa.Syncing){N.clear(),t.info("Doing app state sync"),await Ue(t$,!0),F=pa.Online,t.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let Ee=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:Ee})}};await Promise.all([(async()=>{se&&await we()})(),Xse(W,{signalRepository:Q,shouldProcessHistoryMsg:se,placeholderResendCache:k,ev:g,creds:I.creds,keyStore:I.keys,logger:t,options:n.options,getMessage:r})]),W.message?.protocolMessage?.appStateSyncKeyShare&&F===pa.Syncing&&(t.info("App state sync key arrived, triggering app state sync"),await we())});return c.on("CB:presence",wA),c.on("CB:chatstate",wA),c.on("CB:ib,,dirty",async W=>{let{attrs:$}=le(W,"dirty");switch($.type){case"account_sync":if($.timestamp){let{lastAccountSyncTimestamp:se}=I.creds;se&&await Ce("account_sync",se),se=+$.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:se})}break;case"groups":break;default:t.info({node:W},"received unknown sync");break}}),g.on("connection.update",({connection:W,receivedPendingNotifications:$})=>{if(W==="close"&&(N.clear(),clearTimeout(U),U=void 0),W==="open"&&(i&&to().catch(se=>y(se,"init queries")),_A(o?"available":"unavailable").catch(se=>y(se,"presence update requests"))),!$||F!==pa.Connecting)return;if(V.initialBootstrapComplete=!1,V.recentSyncComplete=!1,clearTimeout(U),U=void 0,F=pa.AwaitingInitialSync,t.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(ne.Message.HistorySyncNotification.create({syncType:ne.HistorySync.HistorySyncType.RECENT}))){t.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),F=pa.Online,setTimeout(()=>g.flush(),0);return}if(I.creds.accountSyncCounter>0){t.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),F=pa.Online,setTimeout(()=>g.flush(),0);return}t.info("First connection, awaiting history sync notification with a 20s timeout."),G&&clearTimeout(G),G=setTimeout(()=>{if(F===pa.AwaitingInitialSync){t.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),F=pa.Online,g.flush();let se=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:se})}},2e4)}),g.on("creds.update",({myAppStateKeyId:W})=>{if(!W||N.size===0)return;if(F===pa.Syncing){N.clear();return}let $=[...N];N.clear(),t.info({collections:$},"app state sync key arrived, re-syncing blocked collections"),Ue($,!1).catch(re=>y(re,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:W,pn:$})=>{try{await Q.lidMapping.storeLIDPNMappings([{lid:W,pn:$}])}catch(re){t.warn({lid:W,pn:$,error:re},"Failed to store LID-PN mapping")}}),T(()=>{G&&(clearTimeout(G),G=void 0),!n.placeholderResendCache&&k.close&&k.close(),F=pa.Connecting,R=void 0}),{...s,serverProps:H,createCallLink:Ke,getBotListV2:fe,messageMutex:L,receiptMutex:q,appStatePatchMutex:z,notificationMutex:K,fetchPrivacySettings:X,upsertMessage:Ae,appPatch:ht,sendPresenceUpdate:_A,presenceSubscribe:ot,profilePictureUrl:MA,fetchBlocklist:iA,fetchStatus:Ie,fetchDisappearingDuration:Xe,updateProfilePicture:je,removeProfilePicture:be,updateProfileStatus:EA,updateProfileName:hA,updateBlockStatus:Ze,updateDisableLinkPreviewsPrivacy:de,updateCallPrivacy:oe,updateMessagesPrivacy:De,updateLastSeenPrivacy:Se,updateOnlinePrivacy:Be,updateProfilePicturePrivacy:Re,updateStatusPrivacy:Ne,updateReadReceiptsPrivacy:Je,updateGroupsAddPrivacy:ve,updateDefaultDisappearingMode:aA,getBusinessProfile:bA,resyncAppState:Ue,chatModify:UA,cleanDirtyBits:Ce,addOrEditContact:Me,removeContact:oA,placeholderResendCache:k,addLabel:dA,addChatLabel:FA,removeChatLabel:Yt,addMessageLabel:ct,removeMessageLabel:br,star:Qe,addOrEditQuickReply:or,removeQuickReply:mo}};var xIe=n=>{let t=KIe(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(g,c,I)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:I}),r=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return GE(c)},s=async()=>{let g=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),c={},I=le(g,"groups");if(I){let d=PA(I,"group");for(let B of d){let f=GE({tag:"result",attrs:{},content:[B]});c[f.id]=f}}return t.ev.emit("groups.update",Object.values(c)),c};return t.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=le(g,"dirty");c.type==="groups"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,groupMetadata:r,groupCreate:async(g,c)=>{let I=zr(),d=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:I},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return GE(d)},groupLeave:async g=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"group",attrs:{id:g}}]}])},groupUpdateSubject:async(g,c)=>{await A(g,"set",[{tag:"subject",attrs:{},content:Buffer.from(c,"utf-8")}])},groupRequestParticipantsList:async g=>{let c=await A(g,"get",[{tag:"membership_approval_requests",attrs:{}}]),I=le(c,"membership_approval_requests");return PA(I,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:I,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=le(d,"membership_requests_action"),f=le(B,I);return PA(f,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:I,attrs:{},content:c.map(Q=>({tag:"participant",attrs:{jid:Q}}))}]),B=le(d,I);return PA(B,"participant").map(Q=>({status:Q.attrs.error||"200",jid:Q.attrs.jid,content:Q}))},groupUpdateDescription:async(g,c)=>{let d=(await r(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:zr()}:{delete:"true"},...d?{prev:d}:{}},content:c?[{tag:"body",attrs:{},content:Buffer.from(c,"utf-8")}]:void 0}])},groupInviteCode:async g=>{let c=await A(g,"get",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return le(c,"group")?.attrs.jid},groupRevokeInviteV4:async(g,c)=>!!await A(g,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:c}}]}]),groupAcceptInviteV4:i.createBufferedFunction(async(g,c)=>{g=typeof g=="string"?{remoteJid:g}:g;let I=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=ne.Message.GroupInviteMessage.fromObject(c),c.inviteExpiration=0,c.inviteCode="",i.emit("messages.update",[{key:g,update:{message:{groupInviteMessage:c}}}])),await a({key:{remoteJid:c.groupJid,id:zr(t.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:va()},"notify"),I.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return GE(c)},groupToggleEphemeral:async(g,c)=>{let I=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[I])},groupSettingUpdate:async(g,c)=>{await A(g,"set",[{tag:c,attrs:{}}])},groupMemberAddMode:async(g,c)=>{await A(g,"set",[{tag:"member_add_mode",attrs:{},content:c}])},groupJoinApprovalMode:async(g,c)=>{await A(g,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"group_join",attrs:{state:c}}]}])},groupFetchAllParticipating:s}},GE=n=>{let t=le(n,"group");if(!t){let B=le(n,"error");if(B){let f=B.attrs.code?+B.attrs.code:500,Q=B.attrs.text||"group metadata query failed";throw new LM.Boom(Q,{statusCode:f,data:B})}throw new LM.Boom("Invalid group metadata response: missing node",{data:n})}if(!t.attrs.id)throw new LM.Boom("Invalid group metadata response: missing group id",{data:t});let o=le(t,"description"),i,e,a,A,r,s;o&&(i=jA(o,"body"),a=o.attrs.participant?CA(o.attrs.participant):void 0,A=o.attrs.participant_pn?CA(o.attrs.participant_pn):void 0,r=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=t.attrs.id.includes("@")?t.attrs.id:Sr(t.attrs.id,"g.us"),c=le(t,"ephemeral")?.attrs.expiration,I=jA(t,"member_add_mode")==="all_member_add";return{id:g,notify:t.attrs.notify,addressingMode:t.attrs.addressing_mode==="lid"?kB.LID:kB.PN,subject:t.attrs.subject,subjectOwner:t.attrs.s_o,subjectOwnerPn:t.attrs.s_o_pn,subjectOwnerUsername:t.attrs.s_o_username,subjectTime:+t.attrs.s_t,size:t.attrs.size?+t.attrs.size:PA(t,"participant").length,creation:+t.attrs.creation,owner:t.attrs.creator?CA(t.attrs.creator):void 0,ownerPn:t.attrs.creator_pn?CA(t.attrs.creator_pn):void 0,ownerUsername:t.attrs.creator_username||void 0,owner_country_code:t.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:r,descTime:s,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_group"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:I,participants:PA(t,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:qA(B.jid)&&Tt(B.phone_number)?B.phone_number:void 0,lid:Tt(B.jid)&&qA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var FE=ze(jr(),1);var SXe=n=>{let{id:t,thread_metadata:o,viewer_metadata:i}=n;return{id:t,owner:void 0,name:o.name.text,creation_time:parseInt(o.creation_time,10),description:o.description.text,invite:o.invite,subscribers:parseInt(o.subscribers_count,10),verification:o.verification,picture:{id:o.picture.id,directPath:o.picture.direct_path},mute_state:i.mute}},wXe=n=>typeof n!="object"||n===null?null:"id"in n&&typeof n.id=="string"?n:"result"in n&&typeof n.result=="object"&&n.result!==null&&"id"in n.result?n.result:null,YIe=n=>{let t=xIe(n),{query:o,generateMessageTag:i}=t,e=(A,r,s)=>sQ(A,r,s,o,i),a=async(A,r)=>{let s={newsletter_id:A,updates:{...r,settings:null}};return e(s,ha.UPDATE_METADATA,"xwa2_newsletter_update")};return{...t,newsletterCreate:async(A,r)=>{let g=await e({input:{name:A,description:r??null}},ha.CREATE,Ra.xwa2_newsletter_create);return SXe(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},ha.SUBSCRIBERS,Ra.xwa2_newsletter_subscribers),newsletterMetadata:async(A,r)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:r,type:A.toUpperCase()}},g=await e(s,ha.METADATA,Ra.xwa2_newsletter_metadata);return wXe(g)},newsletterFollow:A=>e({newsletter_id:A},ha.FOLLOW,Ra.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},ha.UNFOLLOW,Ra.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},ha.MUTE,Ra.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},ha.UNMUTE,Ra.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,r)=>await a(A,{name:r}),newsletterUpdateDescription:async(A,r)=>await a(A,{description:r}),newsletterUpdatePicture:async(A,r)=>{let{img:s}=await Ub(r);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,r,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:r,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,r,s,g)=>{let c={count:r.toString()};return typeof s=="number"&&(c.since=s.toString()),g&&(c.after=g.toString()),await o({tag:"iq",attrs:{id:i(),type:"get",xmlns:"newsletter",to:A},content:[{tag:"message_updates",attrs:c}]})},subscribeNewsletterUpdates:async A=>{let r=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=le(r,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},ha.ADMIN_COUNT,Ra.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,r)=>{await e({newsletter_id:A,user_id:r},ha.CHANGE_OWNER,Ra.xwa2_newsletter_change_owner)},newsletterDemote:async(A,r)=>{await e({newsletter_id:A,user_id:r},ha.DEMOTE,Ra.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},ha.DELETE,Ra.xwa2_newsletter_delete_v2)}}};var jIe=n=>{let{logger:t,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:r,maxMsgRetryCount:s}=n,g=YIe(n),{ev:c,authState:I,messageMutex:d,signalRepository:B,upsertMessage:f,query:Q,fetchPrivacySettings:y,sendNode:m,groupMetadata:T,groupToggleEphemeral:_,registerSocketEndHandler:R}=g,H=B.lidMapping.getLIDForPN.bind(B.lidMapping),F=new Set,L=n.userDevicesCache||new ac({stdTTL:MI.USER_DEVICES,useClones:!1}),q=gc(),z=r?new eM(t,s):null,K=LIe(),G,V=KU,U=async(fe=!1)=>{let Ie=await G;return(!Ie||fe||new Date().getTime()-Ie.fetchDate.getTime()>Ie.ttl*1e3)&&(G=(async()=>{let Xe=await Q({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:OA},content:[{tag:"media_conn",attrs:{}}]}),je=le(Xe,"media_conn"),be={hosts:PA(je,"host").map(({attrs:EA})=>({hostname:EA.hostname,maxContentLengthBytes:+EA.maxContentLengthBytes})),auth:je.attrs.auth,ttl:+je.attrs.ttl,fetchDate:new Date};return t.debug("fetched media conn"),be.hosts[0]&&(V=be.hosts[0].hostname),be})()),G},N=async(fe,Ie,Xe,je)=>{if(!Xe||Xe.length===0)throw new FE.Boom("missing ids in receipt");let be={tag:"receipt",attrs:{id:Xe[0]}};(je==="read"||je==="read-self")&&(be.attrs.t=va().toString()),je==="sender"&&(Tt(fe)||qA(fe))?(be.attrs.recipient=fe,be.attrs.to=Ie):(be.attrs.to=fe,Ie&&(be.attrs.participant=Ie)),je&&(be.attrs.type=je);let hA=Xe.slice(1);hA.length&&(be.content=[{tag:"list",attrs:{},content:hA.map(iA=>({tag:"item",attrs:{id:iA}}))}]),t.debug({attrs:be.attrs,messageIds:Xe},"sending receipt for messages"),await m(be)},k=async(fe,Ie)=>{let Xe=Zne(fe);for(let{jid:je,participant:be,messageIds:EA}of Xe)await N(je,be,EA,Ie)},J=async fe=>{let Xe=(await y()).readreceipts==="all"?"read":"read-self";await k(fe,Xe)},X=async(fe,Ie,Xe)=>{let je=[];Ie||t.debug("not using cache for devices");let be=[],EA=fe.map(Ce=>{let ke=fA(Ce),Ue=ke?.user,MA=ke?.device;return typeof MA=="number"&&MA>=0&&Ue?(je.push({user:Ue,device:MA,jid:Ce}),null):(Ce=CA(Ce),{jid:Ce,user:Ue})}).filter(Ce=>Ce!==null),hA;if(Ie&&L.mget){let Ce=EA.map(ke=>ke?.user).filter(Boolean);hA=await L.mget(Ce)}for(let{jid:Ce,user:ke}of EA)if(Ie){let Ue=hA?.[ke]||(L.mget?void 0:await L.get(ke));if(Ue){let MA=Ue.map(Ke=>({...Ke,jid:Sr(Ke.user,Ke.server,Ke.device)}));je.push(...MA),t.trace({user:ke},"using cache for devices")}else be.push(Ce)}else be.push(Ce);if(!be.length)return je;let iA=new Set;for(let Ce of be)if(qA(Ce)||Ea(Ce)){let ke=fA(Ce)?.user;ke&&iA.add(ke)}let Ze=new sg().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Ce of be)Ze.withUser(new ng().withId(Ce));let bA=await g.executeUSyncQuery(Ze);if(bA){let Ce=bA.list.filter(Ke=>!!Ke.lid);if(Ce.length>0){t.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Ce.map(Ke=>({lid:Ke.lid,pn:Ke.id})));try{let Ke=Ce.map(_A=>_A.lid);Ke.length&&await De(Ke,!0)}catch(Ke){t.warn({e:Ke,count:Ce.length},"failed to assert sessions for newly mapped LIDs")}}let ke=ose(bA?.list,I.creds.me.id,I.creds.me.lid,Xe),Ue={};for(let Ke of ke)Ue[Ke.user]=Ue[Ke.user]||[],Ue[Ke.user]?.push(Ke);for(let[Ke,_A]of Object.entries(Ue)){let ot=iA.has(Ke);for(let wA of _A){let ht=ot?Sr(Ke,wA.server,wA.device):Sr(wA.user,wA.server,wA.device);je.push({...wA,jid:ht}),t.debug({user:wA.user,device:wA.device,finalJid:ht,usedLid:ot},"Processed device with LID priority")}}await q.mutex(async()=>{if(L.mset)await L.mset(Object.entries(Ue).map(([Ke,_A])=>({key:Ke,value:_A})));else for(let Ke in Ue)Ue[Ke]&&await L.set(Ke,Ue[Ke])});let MA={};for(let[Ke,_A]of Object.entries(Ue))_A&&_A.length>0&&(MA[Ke]=_A.map(ot=>ot.device?.toString()||"0"));if(Object.keys(MA).length>0)try{await I.keys.set({"device-list":MA}),t.debug({userCount:Object.keys(MA).length},"stored user device lists for bulk migration")}catch(Ke){t.warn({error:Ke},"failed to store user device lists")}}return je},ae=(fe,Ie)=>Be(fe,{protocolMessage:{type:ne.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:Ie?.slice(0,30),labelTimestamp:va()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),De=async(fe,Ie)=>{let Xe=!1,je=[...new Set(fe)],be=[];t.debug({jids:fe},"assertSessions call with jids");for(let EA of je)!Ie&&(await B.validateSession(EA)).exists||be.push(EA);if(be.length){let EA=[...be.filter(iA=>!!qA(iA)||!!Ea(iA)),...(await B.lidMapping.getLIDsForPNs(be.filter(iA=>!!Tt(iA)||!!wr(iA)))||[]).map(iA=>iA.lid)];t.debug({jidsRequiringFetch:be,wireJids:EA},"fetching sessions");let hA=await Q({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:OA},content:[{tag:"key",attrs:{},content:EA.map(iA=>{let Ze={jid:iA};return Ie&&(Ze.reason="identity"),{tag:"user",attrs:Ze}})}]});await ise(hA,B),Xe=!0}return Xe},oe=async fe=>{if(!I.creds.me?.id)throw new FE.Boom("Not authenticated");let Ie={protocolMessage:{peerDataOperationRequestMessage:fe,type:ne.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},Xe=CA(I.creds.me.id);return await Be(Xe,Ie,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},Se=async(fe,Ie,Xe,je)=>{if(!fe.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let be=await a(Ie,fe),EA=Array.isArray(be)?be:fe.map(Ue=>({recipientJid:Ue,message:be})),hA=!1,iA=I.creds.me.id,Ze=I.creds.me?.lid,bA=Ze?fA(Ze)?.user:null,Ce=EA.map(async({recipientJid:Ue,message:MA})=>{try{if(!Ue)return null;let Ke=MA;if(je){let{user:ht}=fA(Ue),{user:Br}=fA(iA),UA=bA;(ht===Br||UA&&ht===UA)&&!(Ue===iA||Ze&&Ue===Ze)&&(Ke=je,t.debug({jid:Ue,targetUser:ht},"Using DSM for own device"))}let _A=_h(Ke),ot=Ue;return await K.mutex(ot,async()=>{let{type:ht,ciphertext:Br}=await B.encryptMessage({jid:Ue,data:_A});return ht==="pkmsg"&&(hA=!0),{tag:"to",attrs:{jid:Ue},content:[{tag:"enc",attrs:{v:"2",type:ht,...Xe||{}},content:Br}]}})}catch(Ke){return t.error({jid:Ue,err:Ke},"Failed to encrypt for recipient"),null}}),ke=(await Promise.all(Ce)).filter(Ue=>Ue!==null);if(fe.length>0&&ke.length===0)throw new FE.Boom("All encryptions failed",{statusCode:500});return{nodes:ke,shouldIncludeDeviceIdentity:hA}},Be=async(fe,Ie,{messageId:Xe,participant:je,additionalAttributes:be,additionalNodes:EA,useUserDevicesCache:hA,useCachedGroupMetadata:iA,statusJidList:Ze})=>{let bA=jse(I.creds),Ce=I.creds.me?.lid,ke=!!je?.jid,Ue=ke,MA="status@broadcast",{user:Ke,server:_A}=fA(fe),ot=_A==="g.us",wA=fe===MA,ht=_A==="lid",Br=_A==="newsletter",UA=ot||wA,de=fe;Xe=Xe||zr(bA),hA=hA!==!1,iA=iA!==!1&&!wA;let Qe=[],Me=wA?MA:de,oA=[],dA=[],FA,Yt={deviceSentMessage:{destinationJid:Me,message:Ie},messageContextInfo:Ie.messageContextInfo},ct={};if(je){!ot&&!wA&&(be={...be,device_fanout:"false"});let{user:br,device:or}=fA(je.jid);dA.push({user:br,device:or,jid:je.jid})}return await I.keys.transaction(async()=>{let br=Ne(Ie);if(br&&(ct.mediatype=br),Br){let Ee=a?await a(Ie,[]):Ie,he=eee(Ee);oA.push({tag:"plaintext",attrs:{},content:he});let ye={tag:"message",attrs:{to:fe,id:Xe,type:Re(Ie),...be||{}},content:oA};t.debug({msgId:Xe},`sending newsletter message to ${fe}`),await m(ye);return}if((ya(Ie)?.pinInChatMessage||ya(Ie)?.reactionMessage)&&(ct["decrypt-fail"]="hide"),UA&&!ke){let[Ee,he]=await Promise.all([(async()=>{let tA=iA&&A?await A(fe):void 0;return tA&&Array.isArray(tA?.participants)?t.trace({jid:fe,participants:tA.participants.length},"using cached group metadata"):wA||(tA=await T(fe)),tA})(),(async()=>!je&&!wA?(await I.keys.get("sender-key-memory",[fe]))[fe]||{}:{})()]),ye=Ee?Ee.participants.map(tA=>tA.id):[];Ee?.ephemeralDuration&&Ee.ephemeralDuration>0&&(be={...be,expiration:Ee.ephemeralDuration.toString()}),wA&&Ze&&ye.push(...Ze);let qe=await X(ye,!!hA,!1);dA.push(...qe),ot&&(be={...be,addressing_mode:Ee?.addressingMode||"lid"});let IA=await a(Ie);if(Array.isArray(IA))throw new FE.Boom("Per-jid patching is not supported in groups");let yA=_h(IA);FA=IA;let vA=(be?.addressing_mode||Ee?.addressingMode||"lid")==="lid"&&Ce?Ce:bA,{ciphertext:YA,senderKeyDistributionMessage:At}=await B.encryptGroupMessage({group:Me,data:yA,meId:vA}),Ge=[];for(let tA of dA){let tt=tA.jid;(!!!he[tt]||je)&&!Ea(tt)&&!wr(tt)&&tA.device!==99&&(Ge.push(tt),he[tt]=!0)}if(Ge.length){t.debug({senderKeyJids:Ge},"sending new sender key");let tA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:At,groupId:Me}};await De(Ge);let ea=await Se(Ge,tA,ct);Ue=Ue||ea.shouldIncludeDeviceIdentity,Qe.push(...ea.nodes)}oA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...ct},content:YA}),await I.keys.set({"sender-key-memory":{[fe]:he}})}else{let Ee=bA;ht&&Ce?(Ee=Ce,t.debug({to:fe,ownId:Ee},"Using LID identity for @lid conversation")):t.debug({to:fe,ownId:Ee},"Using PN identity for @s.whatsapp.net conversation");let{user:he}=fA(Ee);if(!je){let tA=await a(Ie,[fe]);FA=Array.isArray(tA)?tA.find(tt=>tt.recipientJid===fe)||tA[0]:tA}if(!ke){let tA=ht?"lid":"s.whatsapp.net";if(dA.push({user:Ke,device:0,jid:Sr(Ke,tA,0)}),Ke!==he){let tt=ht?"lid":"s.whatsapp.net",ea=ht&&Ce?fA(Ce).user:fA(bA).user;dA.push({user:ea,device:0,jid:Sr(ea,tt,0)})}if(be?.category!=="peer"){dA.length=0;let tt=ht&&Ce?Sr(fA(Ce)?.user,"lid",void 0):Sr(fA(bA)?.user,"s.whatsapp.net",void 0),ea=await X([tt,fe],!0,!1);dA.push(...ea),t.debug({deviceCount:dA.length,devices:dA.map(nr=>`${nr.user}:${nr.device}@${fA(nr.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let ye=[],qe=[],IA=[],{user:yA}=fA(bA),{user:$A}=Ce?fA(Ce):{user:null};for(let{user:tA,jid:tt}of dA){if(tt===bA||Ce&&tt===Ce){t.debug({jid:tt,meId:bA,meLid:Ce},"Skipping exact sender device (whatsmeow pattern)");continue}tA===yA||tA===$A?qe.push(tt):IA.push(tt),ye.push(tt)}await De(ye);let[{nodes:vA,shouldIncludeDeviceIdentity:YA},{nodes:At,shouldIncludeDeviceIdentity:Ge}]=await Promise.all([Se(qe,Yt||Ie,ct),Se(IA,Ie,ct,Yt)]);Qe.push(...vA),Qe.push(...At),(qe.length>0||IA.length>0)&&(ct.phash=Y$([...qe,...IA])),Ue=Ue||YA||Ge}if(ke){let Ee=qA(je.jid),he=kt(je.jid,Ee?Ce:bA),ye=Ie;if(UA){let $A;if(Ce&&await B.hasSenderKey({group:Me,meId:Ce})?$A=Ce:await B.hasSenderKey({group:Me,meId:bA})&&($A=bA),$A)try{let vA=await B.getSenderKeyDistributionMessage({group:Me,meId:$A});ye={...Ie,senderKeyDistributionMessage:{groupId:Me,axolotlSenderKeyDistributionMessage:vA}}}catch(vA){t.warn({err:vA,jid:Me},"failed to build SKDM for retry, sending without it")}}let qe=he?_h({deviceSentMessage:{destinationJid:Me,message:ye}}):_h(ye),{type:IA,ciphertext:yA}=await B.encryptMessage({data:qe,jid:je.jid});oA.push({tag:"enc",attrs:{v:"2",type:IA,count:je.count.toString()},content:yA})}if(Qe.length)if(be?.category==="peer"){let Ee=Qe[0]?.content?.[0];Ee&&oA.push(Ee)}else oA.push({tag:"participants",attrs:{},content:Qe});let or={tag:"message",attrs:{id:Xe,to:Me,type:Re(Ie),...be||{}},content:oA};if(je?Jr(Me)?(or.attrs.to=Me,or.attrs.participant=je.jid):kt(je.jid,bA)?(or.attrs.to=je.jid,or.attrs.recipient=Me):or.attrs.to=je.jid:or.attrs.to=Me,Ue&&(or.content.push({tag:"device-identity",attrs:{},content:Jf(I.creds.account,!0)}),t.debug({jid:fe},"adding device identity")),!Br&&!ke&&FA?.messageContextInfo?.messageSecret&&xb(FA))try{let Ee=_h(FA),he={id:Xe,fromMe:!0,remoteJid:Me,participant:je?.jid},ye=await Jne(Ee,FA,he);ye&&(or.content.push(ye),t.trace({jid:fe},"added reporting token to message"))}catch(Ee){t.warn({jid:fe,trace:Ee?.stack},"failed to attach reporting token")}let mo=be?.category==="peer",to=!ot&&!ke&&!wA&&!Br&&!mo,Ae=to?await rg(Me,H):Me,$=(to?await I.keys.get("tctoken",[Ae]):{})[Ae],re=$?.token;if(re?.length&&Ed($?.timestamp)){t.debug({jid:Me,timestamp:$?.timestamp},"tctoken expired, clearing"),re=void 0;let Ee=$?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:$.senderTimestamp}:null;try{await I.keys.set({tctoken:{[Ae]:Ee}})}catch(he){t.debug({jid:Me,err:he?.message},"failed to persist tctoken expiry cleanup")}}re?.length&&g.serverProps.privacyTokenOn1to1&&or.content.push({tag:"tctoken",attrs:{},content:re}),EA&&EA.length>0&&or.content.push(...EA),t.debug({msgId:Xe},`sending message to ${Qe.length} devices`),await m(or);let se=!!ya(Ie)?.protocolMessage,we=Me===s$||c$(Me)||mh(Me);if(to&&!se&&!we&&Wse($?.senderTimestamp)&&!F.has(Ae)){F.add(Ae);let Ee=va(),he=B.lidMapping.getPNForLID.bind(B.lidMapping);Zf(Me,g.serverProps.lidTrustedTokenIssueToLid,H,he).then(ye=>Je([ye],Ee)).then(async ye=>{await wE({result:ye,fallbackJid:Ae,keys:I.keys,getLIDForPN:H});let IA=(await I.keys.get("tctoken",[Ae]))[Ae],yA=await SE(I.keys,[Ae]);await I.keys.set({tctoken:{[Ae]:{token:Buffer.alloc(0),...IA,senderTimestamp:Ee},...yA}})}).catch(ye=>{t.debug({jid:Me,err:ye?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{F.delete(Ae)})}z&&!je&&z.addRecentMessage(Me,Xe,Ie)},bA),Xe},Re=fe=>{let Ie=ya(fe);return Ie?Ie.reactionMessage||Ie.encReactionMessage?"reaction":Ie.pollCreationMessage||Ie.pollCreationMessageV2||Ie.pollCreationMessageV3||Ie.pollUpdateMessage?"poll":Ie.eventMessage?"event":Ne(Ie)!==""?"media":"text":"text"},Ne=fe=>fe.imageMessage?"image":fe.videoMessage?fe.videoMessage.gifPlayback?"gif":"video":fe.audioMessage?fe.audioMessage.ptt?"ptt":"audio":fe.contactMessage?"vcard":fe.documentMessage?"document":fe.contactsArrayMessage?"contact_array":fe.liveLocationMessage?"livelocation":fe.stickerMessage?"sticker":fe.listMessage?"list":fe.listResponseMessage?"list_response":fe.buttonsResponseMessage?"buttons_response":fe.orderMessage?"order":fe.productMessage?"product":fe.interactiveResponseMessage?"native_flow_response":fe.groupInviteMessage?"url":"",Je=async(fe,Ie)=>{let Xe=(Ie??va()).toString();return await Q({tag:"iq",attrs:{to:OA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:fe.map(be=>({tag:"token",attrs:{jid:CA(be),t:Xe,type:"trusted_contact"}}))}]})},ve=Gne(n,U),aA=_L(c,"messages.media-update");return R(()=>{!n.userDevicesCache&&L.close&&L.close(),G=void 0,z&&z.clear()}),{...g,userDevicesCache:L,devicesMutex:q,issuePrivacyTokens:Je,assertSessions:De,relayMessage:Be,sendReceipt:N,sendReceipts:k,readMessages:J,refreshMediaConn:U,getMediaHost:()=>V,waUploadToServer:ve,fetchPrivacySettings:y,sendPeerDataOperationMessage:oe,createParticipantNodes:Se,getUSyncDevices:X,messageRetryManager:z,updateMemberLabel:ae,updateMediaMessage:async fe=>{let Ie=Xne(fe.message),Xe=Ie.mediaKey,je=I.creds.me.id,be=Lne(fe.key,Xe,je),EA;if(await Promise.all([m(be),aA(async hA=>{let iA=hA.find(Ze=>Ze.key.id===fe.key.id);if(iA){if(iA.error)EA=iA.error;else try{let Ze=Hne(iA.media,Xe,iA.key.id);if(Ze.result!==ne.MediaRetryNotification.ResultType.SUCCESS){let bA=ne.MediaRetryNotification.ResultType[Ze.result];throw new FE.Boom(`Media re-upload failed by device (${bA})`,{data:Ze,statusCode:xU(Ze.result)||404})}Ie.directPath=Ze.directPath,Ie.url=Uf(Ie.directPath,V),t.debug({directPath:Ze.directPath,key:iA.key},"media update successful")}catch(Ze){EA=Ze}return!0}})]),EA)throw EA;return c.emit("messages.update",[{key:fe.key,update:{message:fe.message}}]),fe},sendMessage:async(fe,Ie,Xe={})=>{let je=I.creds.me.id;if(typeof Ie=="object"&&"disappearingMessagesInChat"in Ie&&typeof Ie.disappearingMessagesInChat<"u"&&Jr(fe)){let{disappearingMessagesInChat:be}=Ie;await _(fe,typeof be=="boolean"?be?Yf:0:be)}else{let be=await Vne(fe,Ie,{logger:t,userJid:je,getUrlInfo:Ue=>Vse(Ue,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:t,uploadImage:i?ve:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:ve,mediaCache:n.mediaCache,options:n.options,messageId:zr(g.user?.id),...Xe}),EA="event"in Ie&&!!Ie.event,hA="delete"in Ie&&!!Ie.delete,iA="edit"in Ie&&!!Ie.edit,Ze="pin"in Ie&&!!Ie.pin,bA="poll"in Ie&&!!Ie.poll,Ce={},ke=[];return hA?Jr(Ie.delete?.remoteJid)&&!Ie.delete?.fromMe?Ce.edit="8":Ce.edit="7":iA?Ce.edit="1":Ze?Ce.edit="2":bA?ke.push({tag:"meta",attrs:{polltype:"creation"}}):EA&&ke.push({tag:"meta",attrs:{event_type:"creation"}}),await Be(fe,be.message,{messageId:be.key.id,useCachedGroupMetadata:Xe.useCachedGroupMetadata,additionalAttributes:Ce,statusJidList:Xe.statusJidList,additionalNodes:ke}),n.emitOwnEvents&&process.nextTick(async()=>{await d.mutex(()=>f(be,"append"))}),be}}}};var DXe=new Set(Object.values(AI));function OXe(n){return typeof n=="string"&&DXe.has(n)}var JIe=n=>{let{logger:t,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,r=jIe(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:I,ws:d,messageMutex:B,notificationMutex:f,receiptMutex:Q,signalRepository:y,query:m,upsertMessage:T,resyncAppState:_,onUnexpectedError:R,assertSessions:H,sendNode:F,relayMessage:L,sendReceipt:q,uploadPreKeys:z,sendPeerDataOperationMessage:K,messageRetryManager:G,registerSocketEndHandler:V,issuePrivacyTokens:U,fetchAccountReachoutTimelock:N,placeholderResendCache:k}=r,J=y.lidMapping.getLIDForPN.bind(y.lidMapping),X=gc(),ae=n.msgRetryCounterCache||new ac({stdTTL:MI.MSG_RETRY,useClones:!1}),De=n.callOfferCache||new ac({stdTTL:MI.CALL_OFFER,useClones:!1}),oe=new ac({stdTTL:5,useClones:!1}),Se=!1,Be=async(Ae,W,$)=>{if(!I.creds.me?.id)throw new gQ.Boom("Not authenticated");let re={historySyncOnDemandRequest:{chatJid:W.remoteJid,oldestMsgFromMe:W.fromMe,oldestMsgId:W.id,oldestMsgTimestampMs:$,onDemandMsgCount:Ae},peerDataOperationRequestType:ne.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return K(re)},Re=async(Ae,W)=>{if(!I.creds.me?.id)throw new gQ.Boom("Not authenticated");if(await k.get(Ae?.id)){t.debug({messageKey:Ae},"already requested resend");return}else await k.set(Ae?.id,W||!0);if(await JB(2e3),!await k.get(Ae?.id))return t.debug({messageKey:Ae},"message received while resend requested"),"RESOLVED";let $={placeholderMessageResendRequest:[{messageKey:Ae}],peerDataOperationRequestType:ne.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await k.get(Ae?.id)&&(t.debug({messageKey:Ae},"PDO message without response after 8 seconds. Phone possibly offline"),await k.del(Ae?.id))},8e3),K($)},Ne=async Ae=>{let W=le(Ae,"update");if(W){let $=W.attrs?.op_name;if(!$){t.warn({node:xn(Ae)},"mex notification missing op_name, fallback to legacy"),await aA(Ae);return}let re;try{re=JSON.parse(W.content.toString())}catch(we){t.error({err:we,opName:$},"failed to parse mex notification JSON");return}if(re.errors?.length){t.warn({errors:re.errors,opName:$},"mex notification has GQL errors");return}let se=re.data;if(!se){t.warn({opName:$},"mex notification has null data");return}switch(t.debug({opName:$},"processing mex notification"),$){case"NotificationUserReachoutTimelockUpdate":Je(se);break;case"MessageCappingInfoNotification":ve(se);break;case"NotificationNewsletterUpdate":case"NotificationLinkedProfilesUpdates":case"NotificationNewsletterAdminPromote":case"NotificationNewsletterAdminDemote":case"NotificationNewsletterUserSettingChange":case"NotificationNewsletterJoin":case"NotificationNewsletterLeave":case"NotificationNewsletterStateChange":case"NotificationNewsletterAdminMetadataUpdate":case"NotificationNewsletterOwnerUpdate":case"NotificationNewsletterAdminInviteRevoke":case"NotificationNewsletterWamoSubStatusChange":case"NotificationNewsletterBlockUser":case"NotificationNewsletterPaidPartnership":case"NotificationNewsletterMilestone":case"NewsletterResponseStateUpdate":await aA(Ae);break;default:t.debug({opName:$},"unhandled mex notification");break}return}await aA(Ae)},Je=Ae=>{let W=Ae.xwa2_notify_account_reachout_timelock;if(!W){t.warn("reachout timelock notification missing payload");return}if(!W.is_active){t.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:AI.DEFAULT}});return}let $=W.time_enforcement_ends?new Date(parseInt(W.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),re=OXe(W.enforcement_type)?W.enforcement_type:AI.DEFAULT;t.info({enforcementType:re,timeEnforcementEnds:$},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:$,enforcementType:re}})},ve=Ae=>{let W=Ae.xwa2_notify_new_chat_messages_capping_info_update;if(!W){t.warn("message capping notification missing payload");return}t.info({payload:W},"received message capping update"),c.emit("message-capping.update",W)},aA=async Ae=>{let W=le(Ae,"mex"),$=W?.content?null:le(Ae,"update")||vs(Ae)[0],re=W?.content?W:$;if(!re?.content){t.warn({node:xn(Ae)},"invalid mex newsletter notification");return}let se;try{let he=re.content;if(Array.isArray(he)){t.warn({payloadNode:re},"invalid mex newsletter notification payload format");return}let ye=typeof he=="string"?Buffer.from(he,"binary"):Buffer.from(he);se=JSON.parse(ye.toString())}catch(he){t.error({err:he,node:xn(Ae)},"failed to parse mex newsletter notification");return}let we=se?.operation??re?.attrs?.op_name,Ee=se?.updates;if(!Ee){let he=se?.data?.xwa2_notify_linked_profiles;he&&(Ee=[he])}if(!Ee||!we){t.warn({data:se},"invalid mex newsletter notification content");return}switch(t.info({operation:we,updates:Ee},"got mex newsletter notification"),we){case"NotificationNewsletterUpdate":for(let he of Ee)he.jid&&he.settings&&Object.keys(he.settings).length>0&&c.emit("newsletter-settings.update",{id:he.jid,update:he.settings});break;case"NotificationNewsletterAdminPromote":for(let he of Ee)he.jid&&he.user&&c.emit("newsletter-participants.update",{id:he.jid,author:Ae.attrs.from,user:he.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let he of Ee){let ye=he?.jid,qe=Array.isArray(he?.added_profiles)?he.added_profiles:[],IA=[];for(let yA of qe){let $A=typeof yA=="string"?yA:yA?.pn??yA?.jid??null;if(ye&&$A){let vA={lid:ye,pn:$A};c.emit("lid-mapping.update",vA),IA.push(vA)}}await y.lidMapping.storeLIDPNMappings(IA)}break;default:t.info({operation:we,data:se},"unhandled mex newsletter notification");break}},fe=async Ae=>{let W=Ae.attrs.from,$=vs(Ae),re=Ae.attrs.participant;for(let se of $)switch(t.debug({from:W,child:se},"got newsletter notification"),se.tag){case"reaction":{let we={id:W,server_id:se.attrs.message_id,reaction:{code:jA(se,"reaction"),count:1}};c.emit("newsletter.reaction",we);break}case"view":{let we={id:W,server_id:se.attrs.message_id,count:parseInt(se.content?.toString()||"0",10)};c.emit("newsletter.view",we);break}case"participant":{let we={id:W,author:re,user:se.attrs.jid,action:se.attrs.action,new_role:se.attrs.role};c.emit("newsletter-participants.update",we);break}case"update":{let we=le(se,"settings");if(we){let Ee={},he=le(we,"name");he?.content&&(Ee.name=he.content.toString());let ye=le(we,"description");ye?.content&&(Ee.description=ye.content.toString()),c.emit("newsletter-settings.update",{id:W,update:Ee})}break}case"message":{let we=le(se,"plaintext");if(we?.content)try{let Ee=typeof we.content=="string"?Buffer.from(we.content,"binary"):Buffer.from(we.content),he=ne.Message.decode(Ee).toJSON(),ye=ne.WebMessageInfo.fromObject({key:{remoteJid:W,id:se.attrs.message_id||se.attrs.server_id,fromMe:!1},message:he,messageTimestamp:+se.attrs.t}).toJSON();await T(ye,"append"),t.debug("Processed plaintext newsletter message")}catch(Ee){t.error({error:Ee},"Failed to decode plaintext newsletter message")}break}default:t.warn({node:Ae,child:se},"Unknown newsletter notification child");break}},Ie=async(Ae,W)=>{let $=age(Ae,W,I.creds.me.id);t.debug({recv:{tag:Ae.tag,attrs:Ae.attrs},sent:$.attrs},"sent ack"),await F($)},Xe=async(Ae,W)=>{let $={tag:"call",attrs:{from:I.creds.me.id,to:W},content:[{tag:"reject",attrs:{"call-id":Ae,"call-creator":W,count:"0"},content:void 0}]};await m($)},je=async(Ae,W=!1)=>{let{fullMessage:$}=NL(Ae,I.creds.me.id,I.creds.me.lid||""),{key:re}=$,se=re.id;if(G){if(G.hasExceededMaxRetries(se)){t.debug({msgId:se},"reached retry limit with new retry manager, clearing"),G.markRetryFailed(se);return}let YA=G.incrementRetryCount(se),At=`${se}:${re?.participant}`;await ae.set(At,YA)}else{let YA=`${se}:${re?.participant}`,At=await ae.get(YA)||0;if(At>=i){t.debug({retryCount:At,msgId:se},"reached retry limit, clearing"),await ae.del(YA);return}At+=1,await ae.set(YA,At)}let we=`${se}:${re?.participant}`,Ee=await ae.get(we)||1,{account:he,signedPreKey:ye,signedIdentityKey:qe}=I.creds,IA=Ae.attrs.from,yA=!1,$A="";if(A&&G&&Ee>1)try{let YA=y.jidToSignalProtocolAddress(IA),At=await y.validateSession(IA),Ge=G.shouldRecreateSession(IA,At.exists);yA=Ge.recreate,$A=Ge.reason,yA&&(t.debug({fromJid:IA,retryCount:Ee,reason:$A},"recreating session for retry"),await I.keys.set({session:{[YA]:null}}),W=!0)}catch(YA){t.warn({error:YA,fromJid:IA},"failed to check session recreation")}if(Ee<=2)if(G)G.schedulePhoneRequest(se,async()=>{try{let YA=await Re(re);t.debug(`sendRetryRequest: requested placeholder resend (${YA}) for message ${se} (scheduled)`)}catch(YA){t.warn({error:YA,msgId:se},"failed to send scheduled phone request")}});else{let YA=await Re(re);t.debug(`sendRetryRequest: requested placeholder resend for message ${YA}`)}let vA=Jf(he,!0);await I.keys.transaction(async()=>{let YA={tag:"receipt",attrs:{id:se,type:"retry",to:Ae.attrs.from},content:[{tag:"retry",attrs:{count:Ee.toString(),id:Ae.attrs.id,t:Ae.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:qg(I.creds.registrationId)}]};if(Ae.attrs.recipient&&(YA.attrs.recipient=Ae.attrs.recipient),Ae.attrs.participant&&(YA.attrs.participant=Ae.attrs.participant),Ee>1||W||yA){let{update:At,preKeys:Ge}=await $U(I,1),[tA]=Object.keys(Ge),tt=Ge[+tA];YA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Jg)},{tag:"identity",attrs:{},content:qe.public},XU(tt,+tA),jf(ye),{tag:"device-identity",attrs:{},content:vA}]}),c.emit("creds.update",At)}await F(YA),t.info({msgAttrs:Ae.attrs,retryCount:Ee},"sent retry receipt")},I?.creds?.me?.id||"sendRetryRequest")},be=new Set,EA=Ae=>{(async()=>{let W=CA(Ae),$=await rg(W,J),se=(await I.keys.get("tctoken",[$]))?.[$]?.senderTimestamp;if(se==null||Ed(se))return;t.debug({jid:W,senderTimestamp:se},"identity changed, re-issuing tctoken");let we=y.lidMapping.getPNForLID.bind(y.lidMapping),Ee=await Zf(W,r.serverProps.lidTrustedTokenIssueToLid,J,we),he=await U([Ee],se);await wE({result:he,fallbackJid:$,keys:I.keys,getLIDForPN:J,onNewJidStored:_A})})().catch(W=>{t.debug({jid:Ae,err:W?.message},"failed to re-issue tctoken after identity change")})},hA=async Ae=>{if(Ae.attrs.from===OA){let $=Ae.attrs.id;if($&&be.has($))return;let se=+le(Ae,"count").attrs.value,we=se{let re=Ae.attrs.participant,se=Ae.attrs.participant_pn,we=Ae.attrs.participant_username,Ee=le(W,"participant")?.attrs?.jid||re,he=le(W,"participant")?.attrs?.phone_number||se;switch(W?.tag){case"create":let ye=GE(W);$.messageStubType=RA.GROUP_CREATE,$.messageStubParameters=[ye.subject],$.key={participant:ye.owner,participantAlt:ye.ownerPn},c.emit("chats.upsert",[{id:ye.id,name:ye.subject,conversationTimestamp:ye.creation}]),c.emit("groups.upsert",[{...ye,author:re,authorPn:se,authorUsername:we}]);break;case"ephemeral":case"not_ephemeral":$.message={protocolMessage:{type:ne.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(W.attrs.expiration||0)}};break;case"modify":let qe=PA(W,"participant").map(Ge=>Ge.attrs.jid);$.messageStubParameters=qe||[],$.messageStubType=RA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let IA=`GROUP_PARTICIPANT_${W.tag.toUpperCase()}`;$.messageStubType=RA[IA];let yA=PA(W,"participant").map(({attrs:Ge})=>({id:Ge.jid,phoneNumber:qA(Ge.jid)&&Tt(Ge.phone_number)?Ge.phone_number:void 0,lid:Tt(Ge.jid)&&qA(Ge.lid)?Ge.lid:void 0,username:Ge.participant_username||Ge.username||void 0,admin:Ge.type||null}));yA.length===1&&(kt(yA[0].id,re)||kt(yA[0].id,se))&&W.tag==="remove"&&($.messageStubType=RA.GROUP_PARTICIPANT_LEAVE),$.messageStubParameters=yA.map(Ge=>JSON.stringify(Ge));break;case"subject":$.messageStubType=RA.GROUP_CHANGE_SUBJECT,$.messageStubParameters=[W.attrs.subject];break;case"description":let $A=le(W,"body")?.content?.toString();$.messageStubType=RA.GROUP_CHANGE_DESCRIPTION,$.messageStubParameters=$A?[$A]:void 0;break;case"announcement":case"not_announcement":$.messageStubType=RA.GROUP_CHANGE_ANNOUNCE,$.messageStubParameters=[W.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":$.messageStubType=RA.GROUP_CHANGE_RESTRICT,$.messageStubParameters=[W.tag==="locked"?"on":"off"];break;case"invite":$.messageStubType=RA.GROUP_CHANGE_INVITE_LINK,$.messageStubParameters=[W.attrs.code];break;case"member_add_mode":let vA=W.content;vA&&($.messageStubType=RA.GROUP_MEMBER_ADD_MODE,$.messageStubParameters=[vA.toString()]);break;case"membership_approval_mode":let YA=le(W,"group_join");YA&&($.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,$.messageStubParameters=[YA.attrs.state]);break;case"created_membership_requests":$.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,$.messageStubParameters=[JSON.stringify({lid:Ee,pn:he}),"created",W.attrs.request_method];break;case"revoked_membership_requests":let At=kt(Ee,re);$.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,$.messageStubParameters=[JSON.stringify({lid:Ee,pn:he}),At?"revoked":"rejected"];break}},Ze=async Ae=>{let[W]=vs(Ae),$=CA(Ae.attrs.from);if(!W){t.debug({from:$},"devices notification missing child, skipping");return}let re=W.tag,se=W.attrs.device_hash,we=PA(W,"device");if(kt($,I.creds.me.id)||kt($,I.creds.me.lid)){let he=we.map(ye=>ye.attrs.jid);t.info({deviceJids:he},"got my own devices")}if(!we.length){t.debug({from:$,tag:re},"no devices in notification, skipping");return}let Ee=[];for(let he of we){let ye=he.attrs.jid;if(!ye)continue;let qe=fA(ye);if(!qe){t.debug({jid:ye},"failed to decode device jid, skipping");continue}Ee.push({jid:ye,user:qe.user,server:qe.server,device:qe.device})}Ee.length&&await g.mutex(async()=>{let he=new Map;for(let ye of Ee){let qe=he.get(ye.user)||[];qe.push(ye),he.set(ye.user,qe)}for(let[ye,qe]of he){if(re==="update"){t.debug({user:ye},`${ye}'s device list updated, dropping cached devices`),await s?.del(ye);continue}re==="remove"&&await y.deleteSession(qe.map(vA=>vA.jid));let IA=await s?.get(ye)||[];if(!IA.length){t.debug({user:ye,tag:re},"device list not cached, deferring to USync refresh");continue}let yA=new Set(qe.map(vA=>vA.device)),$A;switch(re){case"add":t.info({deviceHash:se,count:qe.length},"devices added"),$A=[...IA.filter(vA=>!yA.has(vA.device)),...qe.map(vA=>({user:vA.user,server:vA.server,device:vA.device}))];break;case"remove":t.info({deviceHash:se,count:qe.length},"devices removed"),$A=IA.filter(vA=>!yA.has(vA.device));break;default:t.debug({tag:re},"Unknown device list change tag");continue}$A.length===0?await s?.del(ye):await s?.set(ye,$A)}})},bA=async Ae=>{let W={},[$]=vs(Ae),re=Ae.attrs.type,se=CA(Ae.attrs.from);switch(re){case"newsletter":await fe(Ae);break;case"mex":await Ne(Ae);break;case"w:gp2":iA(Ae,$,W);break;case"mediaretry":let we=Une(Ae);c.emit("messages.media-update",[we]);break;case"encrypt":await hA(Ae);break;case"devices":try{await Ze(Ae)}catch(wo){t.error({error:wo,node:Ae},"failed to handle devices notification")}break;case"server_sync":let Ee=le(Ae,"collection");if(Ee){let wo=Ee.attrs.name;await _([wo],!1)}break;case"picture":let he=le(Ae,"set"),ye=le(Ae,"delete");if(c.emit("contacts.update",[{id:CA(Ae?.attrs?.from)||(he||ye)?.attrs?.hash||"",imgUrl:he?"changed":"removed"}]),Jr(se)){let wo=he||ye;W.messageStubType=RA.GROUP_CHANGE_ICON,he&&(W.messageStubParameters=[he.attrs.id]),W.participant=wo?.attrs.author,W.key={...W.key||{},participant:he?.attrs.author}}break;case"account_sync":if($.tag==="disappearing_mode"){let wo=+$.attrs.duration,Md=+$.attrs.t;t.info({newDuration:wo},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...I.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:wo,ephemeralSettingTimestamp:Md}}})}else if($.tag==="blocklist"){let wo=PA($,"item");for(let{attrs:Md}of wo){let WM=[Md.jid],ZM=Md.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:WM,type:ZM})}}break;case"link_code_companion_reg":let qe=le(Ae,"link_code_companion_reg"),IA=ht(ka(qe,"link_code_pairing_ref")),yA=ht(ka(qe,"primary_identity_pub")),$A=ht(ka(qe,"link_code_pairing_wrapped_primary_ephemeral_pub")),vA=await wA($A),YA=Dr.sharedKey(I.creds.pairingEphemeralKeyPair.private,vA),At=_K(32),Ge=_K(32),tA=Jn(YA,32,{salt:Ge,info:"link_code_pairing_key_bundle_encryption_key"}),tt=Buffer.concat([Buffer.from(I.creds.signedIdentityKey.public),yA,At]),ea=_K(12),nr=xl(tt,tA,ea,Buffer.alloc(0)),So=Buffer.concat([Ge,ea,nr]),zM=Dr.sharedKey(I.creds.signedIdentityKey.private,yA),VM=Buffer.concat([YA,zM,At]);I.creds.advSecretKey=Buffer.from(Jn(VM,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:OA,type:"set",id:r.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:I.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:So},{tag:"companion_identity_public",attrs:{},content:I.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:IA}]}]}),I.creds.registered=!0,c.emit("creds.update",I.creds);break;case"privacy_token":await ot(Ae);break}if(Object.keys(W).length)return W},Ce=new Set,ke=(async()=>{try{let Ae=await Xb(I.keys);for(let W of Ae)Ce.add(W);t.debug({count:Ce.size},"loaded tctoken index")}catch(Ae){t.warn({err:Ae?.message},"failed to load tctoken index")}})(),Ue;async function MA(){Ue&&(clearTimeout(Ue),Ue=void 0);let Ae=await SE(I.keys,Ce);return I.keys.set({tctoken:Ae})}function Ke(){Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{Ue=void 0,MA().catch(Ae=>{t.warn({err:Ae?.message},"failed to save tctoken index")})},5e3)}function _A(Ae){Ae&&Ae!==_I&&!Ce.has(Ae)&&(Ce.add(Ae),Ke())}let ot=async Ae=>{if(!le(Ae,"tokens"))return;let $=CA(Ae.attrs.from),se=(Ae.attrs.sender_lid&&qA(CA(Ae.attrs.sender_lid))?CA(Ae.attrs.sender_lid):void 0)??await rg($,J);t.debug({from:$,storageJid:se},"processing privacy token notification"),await wE({result:Ae,fallbackJid:se,keys:I.keys,getLIDForPN:J,onNewJidStored:_A})};async function wA(Ae){let W=ht(Ae),$=W.slice(0,32),re=await GD(I.creds.pairingCode,$),se=W.slice(32,48),we=W.slice(48,80);return G$(we,re,se)}function ht(Ae){if(Ae===void 0)throw new gQ.Boom("Invalid buffer",{statusCode:400});return Ae instanceof Buffer?Ae:Buffer.from(Ae)}let Br=async(Ae,W)=>{let $=`${Ae}:${W}`;return(await ae.get($)||0){let $=`${Ae}:${W}`,re=(await ae.get($)||0)+1;await ae.set($,re)},de=async(Ae,W,$,re)=>{let se=Ae.remoteJid,we=Ae.participant||se,Ee=+$.attrs.count||1,he=W[0],ye=[];for(let Ge of W){let tA;if(G){let tt=G.getRecentMessage(se,Ge);tt&&(tA=tt.message,t.debug({jid:se,id:Ge},"found message in retry cache"),G.markRetrySuccess(Ge))}tA||(tA=await e({...Ae,id:Ge}),tA&&(t.debug({jid:se,id:Ge},"found message via getMessage"),G&&G.markRetrySuccess(Ge))),ye.push(tA)}let qe=!fA(we)?.device,IA=y.jidToSignalProtocolAddress(we),yA=!1,$A=ase(re);if($A)try{await y.injectE2ESession({jid:we,session:$A}),yA=!0,t.debug({participant:we,retryCount:Ee},"injected session from retry receipt key bundle")}catch(Ge){t.warn({error:Ge,participant:we},"failed to inject session from retry receipt")}if(!yA){let Ge=rI(re,"registration",4);if(typeof Ge=="number"&&Number.isInteger(Ge)){let tA=await y.getSessionInfo(we);tA&&tA.registrationId!==0&&tA.registrationId!==Ge&&(t.info({participant:we,stored:tA.registrationId,received:Ge},"reg id mismatch on retry without bundle, deleting session"),await I.keys.set({session:{[IA]:null}}))}}let vA=2;if(he&&G){let Ge=await y.getSessionInfo(we);Ge&&(Ee===vA?G.saveBaseKey(IA,he,Ge.baseKey):Ee>vA&&(G.hasSameBaseKey(IA,he,Ge.baseKey)&&(t.warn({participant:we,retryCount:Ee},"base key collision on retry, forcing fresh session"),await I.keys.set({session:{[IA]:null}})),G.deleteBaseKey(IA,he)))}let YA=!1,At="";if(A&&G&&Ee>1&&!yA)try{let Ge=await y.validateSession(we),tA=G.shouldRecreateSession(we,Ge.exists);YA=tA.recreate,At=tA.reason,YA&&(t.debug({participant:we,retryCount:Ee,reason:At},"recreating session for outgoing retry"),await I.keys.set({session:{[IA]:null}}))}catch(Ge){t.warn({error:Ge,participant:we},"failed to check session recreation for outgoing retry")}yA||await H([we],!0),Jr(se)&&await I.keys.set({"sender-key-memory":{[se]:null}}),t.debug({participant:we,sendToAll:qe,shouldRecreateSession:YA,recreateReason:At,injectedFromBundle:yA},"prepared session for retry resend");for(let[Ge,tA]of ye.entries())if(W[Ge])if(tA&&await Br(W[Ge],we)){await UA(W[Ge],we);let tt={messageId:W[Ge]};qe?tt.useUserDevicesCache=!1:tt.participant={jid:we,count:+$.attrs.count},await L(Ae.remoteJid,tA,tt)}else t.debug({jid:Ae.remoteJid,id:W[Ge]},"recv retry request, but message not available")},Qe=async Ae=>{let{attrs:W,content:$}=Ae,re=W.from.includes("lid"),se=kt(W.participant||W.from,re?I.creds.me?.lid:I.creds.me?.id),we=!se||Jr(W.from)?W.from:W.recipient,Ee=!W.recipient||(W.type==="retry"||W.type==="sender")&&se,he={remoteJid:we,id:"",fromMe:Ee,participant:W.participant},ye=[W.id];if(Array.isArray($)){let qe=PA($[0],"item");ye.push(...qe.map(IA=>IA.attrs.id))}try{await Promise.all([Q.mutex(async()=>{let qe=V$(W.type);if(typeof qe<"u"&&(qe>=ne.WebMessageInfo.Status.SERVER_ACK||!se))if(Jr(we)||Yg(we)){if(W.participant){let IA=qe===ne.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",ye.map(yA=>({key:{...he,id:yA},receipt:{userJid:CA(W.participant),[IA]:+W.t}})))}}else c.emit("messages.update",ye.map(IA=>({key:{...he,id:IA},update:{status:qe,messageTimestamp:qr(+(W.t??0))}})));if(W.type==="retry"){he.participant=he.participant||W.from;let IA=le(Ae,"retry");if(ye[0]&&he.participant&&await Br(ye[0],he.participant))if(he.fromMe)try{await UA(ye[0],he.participant),t.debug({attrs:W,key:he},"recv retry request"),await de(he,ye,IA,Ae)}catch(yA){t.error({key:he,ids:ye,trace:yA instanceof Error?yA.stack:"Unknown error"},"error in sending message again")}else t.info({attrs:W,key:he},"recv retry for not fromMe message");else t.info({attrs:W,key:he},"will not send message again, as sent too many times")}})])}finally{await Ie(Ae).catch(qe=>t.error({ackErr:qe},"failed to ack receipt"))}},Me=async Ae=>{let W=Ae.attrs.from;try{await Promise.all([f.mutex(async()=>{let $=await bA(Ae);if($){let re=kt(Ae.attrs.participant||W,I.creds.me.id),{senderAlt:se,addressingMode:we}=HD(Ae);$.key={remoteJid:W,fromMe:re,participant:Ae.attrs.participant,participantAlt:se,participantUsername:Ae.attrs.participant_username,addressingMode:we,id:Ae.attrs.id,...$.key||{}},$.participant??($.participant=Ae.attrs.participant),$.messageTimestamp=+Ae.attrs.t;let Ee=ne.WebMessageInfo.fromObject($);await T(Ee,"append")}})])}finally{await Ie(Ae).catch($=>t.error({ackErr:$},"failed to ack notification"))}},oA=async Ae=>{if(le(Ae,"enc")?.attrs.type==="msmsg"){t.debug({key:Ae.attrs.key},"ignored msmsg"),await Ie(Ae,Jl.MissingMessageSecret);return}let $=!1;try{let{fullMessage:re,category:se,author:we,decrypt:Ee}=ree(Ae,I.creds.me.id,I.creds.me.lid||"",y,t),he=re.key.participantAlt||re.key.remoteJidAlt;if(he){let ye=fA(he)?.server,qe=re.key.participant||re.key.remoteJid;ye==="lid"?await y.lidMapping.getPNForLID(he)||(await y.lidMapping.storeLIDPNMappings([{lid:he,pn:qe}]),await y.migrateSession(qe,he)):(await y.lidMapping.storeLIDPNMappings([{lid:qe,pn:he}]),await y.migrateSession(he,qe))}await B.mutex(async()=>{if(await Ee(),re.key?.remoteJid&&re.key?.id&&re.message&&G&&G.addRecentMessage(re.key.remoteJid,re.key.id,re.message),re.messageStubType===ne.WebMessageInfo.StubType.CIPHERTEXT&&re.category!=="peer"){if(re?.messageStubParameters?.[0]===Aee)return $=!0,Ie(Ae,Jl.ParsingError);if(re.messageStubParameters?.[0]===UD){let qe=le(Ae,"unavailable")?.attrs?.type;if(qe==="bot_unavailable_fanout"||qe==="hosted_unavailable_fanout"||qe==="view_once_unavailable_fanout")return t.debug({msgId:re.key.id,unavailableType:qe},"skipping placeholder resend for excluded unavailable type"),$=!0,Ie(Ae);let IA=va()-qr(re.messageTimestamp);if(IA>BIe)return t.debug({msgId:re.key.id,messageAge:IA},"skipping placeholder resend for old message"),$=!0,Ie(Ae);let yA={remoteJid:re.key.remoteJid,fromMe:re.key.fromMe,id:re.key.id,participant:re.key.participant},$A={key:re.key,messageTimestamp:re.messageTimestamp,pushName:re.pushName,participant:re.participant,verifiedBizName:re.verifiedBizName};Re(yA,$A).then(vA=>{vA&&vA!=="RESOLVED"&&(t.debug({msgId:re.key.id,requestId:vA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:re.key,update:{messageStubParameters:[UD,vA]}}]))}).catch(vA=>{t.warn({err:vA,msgId:re.key.id},"failed to request placeholder resend for unavailable message")}),$=!0,await Ie(Ae)}else{if(Yg(re.key.remoteJid)){let ye=va()-qr(re.messageTimestamp);if(ye>CIe)return t.debug({msgId:re.key.id,messageAge:ye,remoteJid:re.key.remoteJid},"skipping retry for expired status message"),$=!0,Ie(Ae)}t.debug("[handleMessage] Attempting retry request for failed decryption"),await X.mutex(async()=>{try{if(!d.isOpen){t.debug({node:Ae},"Connection closed, skipping retry");return}let ye=le(Ae,"enc");await je(Ae,!ye),o&&await JB(o)}catch(ye){t.error({err:ye},"Failed to send retry")}$=!0,await Ie(Ae,Jl.UnhandledError)})}}else if(G&&re.key.id&&G.cancelPendingPhoneRequest(re.key.id),tI(re.key.remoteJid))$=!0,await Ie(Ae),t.debug({key:re.key},"processed newsletter message without receipts");else{let qe,IA=re.key.participant;if(se==="peer"?qe="peer_msg":re.key.fromMe?(qe="sender",(qA(re.key.remoteJid)||qA(re.key.remoteJidAlt))&&(IA=we)):Se||(qe="inactive"),$=!0,await q(re.key.remoteJid,IA,[re.key.id],qe),jb(re.message)){let $A=CA(re.key.remoteJid);await q($A,void 0,[re.key.id],"hist_sync")}}Zse(re,I.creds.me.id,I.creds.me.lid),await T(re,Ae.attrs.offline?"append":"notify")})}catch(re){t.error({error:re,node:xn(Ae)},"error in handling message"),$||await Ie(Ae,Jl.UnhandledError).catch(se=>t.error({ackErr:se},"failed to ack message after error"))}},dA=async Ae=>{try{let{attrs:W}=Ae,[$]=vs(Ae);if(!$)throw new gQ.Boom("Missing call info in call node");let re=Z$($),se=$.attrs["call-id"],we=$.attrs.from||$.attrs["call-creator"],Ee={chatId:W.from,from:we,callerPn:$.attrs.caller_pn,id:se,date:new Date(+W.t*1e3),offline:!!W.offline,status:re};if(re==="relaylatency"){let ye=$.attrs.latency||$.attrs.latency_ms||$.attrs["latency-ms"],qe=ye?Number(ye):void 0;Number.isFinite(qe)&&(Ee.latencyMs=qe)}re==="offer"&&(Ee.isVideo=!!le($,"video"),Ee.isGroup=$.attrs.type==="group"||!!$.attrs["group-jid"],Ee.groupJid=$.attrs["group-jid"],await De.set(Ee.id,Ee));let he=await De.get(Ee.id);he&&(Ee.isVideo=he.isVideo,Ee.isGroup=he.isGroup,Ee.callerPn=Ee.callerPn||he.callerPn),(re==="reject"||re==="accept"||re==="timeout"||re==="terminate")&&await De.del(Ee.id),c.emit("call",[Ee])}catch(W){t.error({error:W,node:xn(Ae)},"error in handling call")}finally{await Ie(Ae).catch(W=>t.error({ackErr:W},"failed to ack call"))}},FA=async({attrs:Ae})=>{let W={remoteJid:Ae.from,fromMe:!0,id:Ae.id};if(Ae.error){let $=Ae.error===String(Jl.SenderReachoutTimelocked);if(Ae.error===TL.MessageAccountRestriction){t.warn({msgId:Ae.id,from:Ae.from},"error 463: account restricted or missing tctoken for contact");let re=Ae.from;re&&!mo.has(re)&&(mo.add(re),(async()=>{try{let se=y.lidMapping.getPNForLID.bind(y.lidMapping),we=await rg(re,J),Ee=await Zf(re,r.serverProps.lidTrustedTokenIssueToLid,J,se),he=await U([Ee],va());await wE({result:he,fallbackJid:we,keys:I.keys,getLIDForPN:J,onNewJidStored:_A}),t.debug({from:re},"completed 463 token recovery issuance")}catch(se){t.debug({from:re,err:se?.message},"failed 463 token recovery issuance")}finally{mo.delete(re)}})())}else Ae.error===TL.SmaxInvalid?t.warn({msgId:Ae.id,from:Ae.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):$?(await N().catch(re=>t.warn({err:re},"failed to fetch reachout timelock")),t.warn({attrs:Ae},"received error in ack")):t.warn({attrs:Ae},"received error in ack");c.emit("messages.update",[{key:W,update:{status:yh.ERROR,messageStubParameters:$?[Ae.error,tee]:[Ae.error]}}])}},Yt=async(Ae,W,$)=>{c.buffer(),await re(),c.flush();function re(){return $(Ae,!1).catch(se=>R(se,W))}},ct=UIe(new Map([["message",oA],["call",dA],["receipt",Qe],["notification",Me]]),{isWsOpen:()=>d.isOpen,onUnexpectedError:R,yieldToEventLoop:()=>new Promise(Ae=>setImmediate(Ae))}),br=async(Ae,W,$,re)=>{let se=W.attrs.from,we=se;if(Ae==="receipt"&&se){let he=W.attrs,ye=he.from.includes("lid");we=!kt(he.participant||he.from,ye?I.creds.me?.lid:I.creds.me?.id)||Jr(he.from)?he.from:he.recipient}if(we&&we!==OA&&a(we)){await Ie(W,Ae==="message"?Jl.UnhandledError:void 0);return}!!W.attrs.offline?ct.enqueue(Ae,W):await Yt(W,$,re)};d.on("CB:message",async Ae=>{await br("message",Ae,"processing message",oA)}),d.on("CB:call",async Ae=>{await br("call",Ae,"handling call",dA)}),d.on("CB:receipt",async Ae=>{await br("receipt",Ae,"handling receipt",Qe)}),d.on("CB:notification",async Ae=>{await br("notification",Ae,"handling notification",Me)}),d.on("CB:ack,class:message",Ae=>{FA(Ae).catch(W=>R(W,"handling bad ack"))}),c.on("call",async([Ae])=>{if(Ae&&(Ae.status==="timeout"||Ae.status==="offer"&&Ae.isGroup)){let W={key:{remoteJid:Ae.chatId,id:Ae.id,fromMe:!1},messageTimestamp:va(Ae.date)};Ae.status==="timeout"?Ae.isGroup?W.messageStubType=Ae.isVideo?RA.CALL_MISSED_GROUP_VIDEO:RA.CALL_MISSED_GROUP_VOICE:W.messageStubType=Ae.isVideo?RA.CALL_MISSED_VIDEO:RA.CALL_MISSED_VOICE:W.message={call:{callKey:Buffer.from(Ae.id)}};let $=ne.WebMessageInfo.fromObject(W);await T($,Ae.offline?"append":"notify")}});let or=0,mo=new Set;c.on("connection.update",({isOnline:Ae,connection:W})=>{if(typeof Ae<"u"&&(Se=Ae,t.trace(`sendActiveReceipts set to "${Se}"`)),W==="close"&&Ue){clearTimeout(Ue),Ue=void 0;try{Promise.resolve(MA()).catch(()=>{})}catch{}}if(Ae){let $=Date.now(),re=1440*60*1e3;$-or>=re&&(or=$,to())}}),V(()=>{!n.msgRetryCounterCache&&ae.close&&ae.close(),!n.callOfferCache&&De.close&&De.close(),oe.close(),Se=!1});async function to(){try{await ke;let Ae=await Xb(I.keys),W=new Set(Ce);for(let he of Ae)W.add(he);if(!W.size)return;let $=[...W],re=await I.keys.get("tctoken",$),se={},we=new Set,Ee=0;for(let he of $){let ye=re[he];if(!ye){Ee++;continue}let qe=!!ye.token?.length,IA=qe&&Ed(ye.timestamp),yA=ye.senderTimestamp!==void 0,$A=yA&&Ed(ye.senderTimestamp),vA=qe&&!IA,YA=yA&&!$A;!vA&&!YA?(se[he]=null,Ee++):IA&&YA?(se[he]={token:Buffer.alloc(0),senderTimestamp:ye.senderTimestamp},we.add(he),Ee++):we.add(he)}if(Ee===0)return;await I.keys.set({tctoken:{...se,[_I]:{token:Buffer.from(JSON.stringify([...we]))}}}),Ce.clear();for(let he of we)Ce.add(he);t.debug({mutated:Ee,remaining:we.size},"pruned expired tctokens")}catch(Ae){t.warn({err:Ae?.message},"failed to prune expired tctokens")}}return{...r,sendMessageAck:Ie,sendRetryRequest:je,rejectCall:Xe,fetchMessageHistory:Be,requestPlaceholderResend:Re,messageRetryManager:G}};var qIe=n=>{let t=JIe(n),{authState:o,query:i,waUploadToServer:e}=t,a=async f=>{let Q=[],y=["address","email","description"];return Q.push(...y.filter(T=>f[T]!==void 0&&f[T]!==null).map(T=>({tag:T,attrs:{},content:f[T]}))),f.websites!==void 0&&Q.push(...f.websites.map(T=>({tag:"website",attrs:{},content:T}))),f.hours!==void 0&&Q.push({tag:"business_hours",attrs:{timezone:f.hours.timezone},content:f.hours.days.map(T=>{let _={tag:"business_hours_config",attrs:{day_of_week:T.day,mode:T.mode}};return T.mode==="specific_hours"?{..._,attrs:{..._.attrs,open_time:T.openTimeInMinutes,close_time:T.closeTimeInMinutes}}:_})}),await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:Q}]})},A=async f=>{let{fileSha256:Q,filePath:y}=await Lb(f,"biz-cover-photo"),m=Q.toString("base64"),{meta_hmac:T,fbid:_,ts:R}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(_),op:"update",token:T,ts:String(R)}}]}]}),_},r=async f=>await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:f}}]}]}),s=async({jid:f,limit:Q,cursor:y})=>{f=f||o.creds.me?.id,f=CA(f);let m=[{tag:"limit",attrs:{},content:Buffer.from((Q||10).toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}];y&&m.push({tag:"after",attrs:{},content:y});let T=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:f,allow_shop_source:"true"},content:m}]});return DIe(T)},g=async(f,Q=51)=>{f=f||o.creds.me?.id,f=CA(f);let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:f},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return OIe(y)},c=async(f,Q)=>{let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:f},content:[{tag:"image_dimensions",attrs:{},content:[{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]},{tag:"token",attrs:{},content:Buffer.from(Q)}]}]});return bIe(y)},I=async(f,Q)=>{Q=await SK(Q,e);let y=mK(f,Q),m=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_edit",attrs:{v:"1"},content:[y,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),T=le(m,"product_catalog_edit"),_=le(T,"product");return nQ(_)},d=async f=>{f.isHidden=!!f.isHidden,f=await SK(f,e);let Q=mK(void 0,f),y=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[Q,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=le(y,"product_catalog_add"),T=le(m,"product");return nQ(T)},B=async f=>{let Q=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:f.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(le(Q,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...t,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:d,productDelete:B,productUpdate:I,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:r}};var zIe=n=>{let t=qIe(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(I,d,B)=>e({tag:"iq",attrs:{type:d,xmlns:"w:g2",to:I},content:B}),r=async I=>{let d=await A(I,"get",[{tag:"query",attrs:{request:"interactive"}}]);return TK(d)},s=async()=>{let I=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),d={},B=le(I,"communities");if(B){let f=PA(B,"community");for(let Q of f){let y=TK({tag:"result",attrs:{},content:[Q]});d[y.id]=y}}return t.ev.emit("groups.update",Object.values(d)),d};async function g(I){aQ.info({node:I},"parseGroupResult");let d=le(I,"group");if(d)try{aQ.info({groupNode:d},"groupNode");let B=await t.groupMetadata(`${d.attrs.id}@g.us`);return B||c.empty()}catch(B){return console.error("Error parsing group metadata:",B),c.empty()}return c.empty()}let c={empty:()=>null,of:I=>I!==null?{value:I}:null};return t.ws.on("CB:ib,,dirty",async I=>{let{attrs:d}=le(I,"dirty");d.type==="communities"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,communityMetadata:r,communityCreate:async(I,d)=>{let B=ML().substring(0,12),f=await A("@g.us","set",[{tag:"create",attrs:{subject:I},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(d||"","utf-8")}]},{tag:"parent",attrs:{default_membership_approval_mode:"request_required"}},{tag:"allow_non_admin_sub_group_creation",attrs:{}},{tag:"create_general_chat",attrs:{}}]}]);return await g(f)},communityCreateGroup:async(I,d,B)=>{let f=zr(),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:I,key:f},content:[...d.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(Q)},communityLeave:async I=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:I}}]}])},communityUpdateSubject:async(I,d)=>{await A(I,"set",[{tag:"subject",attrs:{},content:Buffer.from(d,"utf-8")}])},communityLinkGroup:async(I,d)=>{await A(d,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}]}])},communityUnlinkGroup:async(I,d)=>{await A(d,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}])},communityFetchLinkedGroups:async I=>{let d=I,B=!1,f=await t.groupMetadata(I);f.linkedParent?d=f.linkedParent:B=!0;let Q=await A(d,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=le(Q,"sub_groups");if(m){let T=PA(m,"group");for(let _ of T)y.push({id:_.attrs.id?Sr(_.attrs.id,"g.us"):void 0,subject:_.attrs.subject||"",creation:_.attrs.creation?Number(_.attrs.creation):void 0,owner:_.attrs.creator?CA(_.attrs.creator):void 0,size:_.attrs.size?Number(_.attrs.size):void 0})}return{communityJid:d,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async I=>{let d=await A(I,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=le(d,"membership_approval_requests");return PA(B,"membership_approval_request").map(Q=>Q.attrs)},communityRequestParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:d.map(T=>({tag:"participant",attrs:{jid:T}}))}]}]),Q=le(f,"membership_requests_action"),y=le(Q,B);return PA(y,"participant").map(T=>({status:T.attrs.error||"200",jid:T.attrs.jid}))},communityParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:d.map(m=>({tag:"participant",attrs:{jid:m}}))}]),Q=le(f,B);return PA(Q,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(I,d)=>{let f=(await r(I)).descId??null;await A(I,"set",[{tag:"description",attrs:{...d?{id:ML()}:{delete:"true"},...f?{prev:f}:{}},content:d?[{tag:"body",attrs:{},content:Buffer.from(d,"utf-8")}]:void 0}])},communityInviteCode:async I=>{let d=await A(I,"get",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityRevokeInvite:async I=>{let d=await A(I,"set",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityAcceptInvite:async I=>{let d=await A("@g.us","set",[{tag:"invite",attrs:{code:I}}]);return le(d,"community")?.attrs.jid},communityRevokeInviteV4:async(I,d)=>!!await A(I,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:d}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(I,d)=>{I=typeof I=="string"?{remoteJid:I}:I;let B=await A(d.groupJid,"set",[{tag:"accept",attrs:{code:d.inviteCode,expiration:d.inviteExpiration.toString(),admin:I.remoteJid}}]);return I.id&&(d=ne.Message.GroupInviteMessage.fromObject(d),d.inviteExpiration=0,d.inviteCode="",i.emit("messages.update",[{key:I,update:{message:{groupInviteMessage:d}}}])),await a({key:{remoteJid:d.groupJid,id:zr(t.user?.id),fromMe:!1,participant:I.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:I.remoteJid,messageTimestamp:va()},"notify"),B.attrs.from}),communityGetInviteInfo:async I=>{let d=await A("@g.us","get",[{tag:"invite",attrs:{code:I}}]);return TK(d)},communityToggleEphemeral:async(I,d)=>{let B=d?{tag:"ephemeral",attrs:{expiration:d.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(I,"set",[B])},communitySettingUpdate:async(I,d)=>{await A(I,"set",[{tag:d,attrs:{}}])},communityMemberAddMode:async(I,d)=>{await A(I,"set",[{tag:"member_add_mode",attrs:{},content:d}])},communityJoinApprovalMode:async(I,d)=>{await A(I,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:d}}]}])},communityFetchAllParticipating:s}},TK=n=>{let t=le(n,"community"),o=le(t,"description"),i,e;o&&(i=jA(o,"body"),e=o.attrs.id);let a=t.attrs.id?.includes("@")?t.attrs.id:Sr(t.attrs.id||"","g.us"),A=le(t,"ephemeral")?.attrs.expiration,r=jA(t,"member_add_mode")==="all_member_add";return{id:a,subject:t.attrs.subject||"",subjectOwner:t.attrs.s_o,subjectTime:Number(t.attrs.s_t||0),size:PA(t,"participant").length,creation:Number(t.attrs.creation||0),owner:t.attrs.creator?CA(t.attrs.creator):void 0,desc:i,descId:e,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_community"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:r,participants:PA(t,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:jA(t,"addressing_mode")}};var bXe=n=>{let t={...QIe,...n};return zIe(t)},VIe=bXe;var WIe=VIe;var MXe=Object.freeze({key:"whatsapp",label:"WhatsApp",get connectionLabel(){return w(" Web \u5173\u8054\u8BBE\u5907")},reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),UM=class extends ps{constructor(t){super({...t,descriptor:MXe})}};import{chmod as ZIe,mkdir as _Xe,readdir as TXe}from"node:fs/promises";var NXe=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),RXe=6e4;function XIe(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function kXe(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function vXe(n){let t=n;if(typeof t=="string"){if(!/^\d+$/.test(t))return null;t=Number(t)}else typeof t=="bigint"?t=Number(t):t&&typeof t=="object"&&(t=Number(t.valueOf()));return Number.isFinite(t)&&t>=0?t*1e3:null}async function NK(n){await _Xe(n,{recursive:!0,mode:448}),await ZIe(n,448);let t=await TXe(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(t.filter(o=>o.isFile()).map(o=>ZIe(`${n}/${o.name}`,384).catch(()=>{})))}function PXe(n,t){let o=n.user??t.creds.me,i=CA(o?.id);if(!/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i??""))throw new Error("WhatsApp did not return a valid linked account");return{accountJid:i,name:typeof o?.name=="string"&&o.name.trim()?o.name.trim().slice(0,100):w("WhatsApp\u673A\u5668\u4EBA")}}async function HM({authDir:n,onQr:t,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=WIe,loadAuthState:r=zse}={}){if(!n||typeof t!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await NK(n);let s=Date.now(),{state:g,saveCreds:c}=await r(n),I=g.keys.set.bind(g.keys);g.keys.set=async z=>{await I(z),await NK(n)};let d=!1,B=!1,f,Q,y=Promise.resolve(),m=null,T=0,_=null,R=new Promise((z,K)=>{f=z,Q=K}),H=z=>{B||(B=!0,Q(z))},F=async()=>{d||(d=!0,T+=1,H(XIe()),await _?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},L=async()=>{d||(d=!0,T+=1,H(XIe()),await _?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let z=++T,K=!1,G=A({auth:g,browser:AM.macOS("DeepSeek Harness"),logger:NXe,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=G;let V=()=>{!K||!g.creds.me||B||y.then(()=>{d||B||z!==T||!K||!g.creds.me||(B=!0,f(PXe(G,g)))}).catch(U=>H(U))};G.ev.on("creds.update",()=>{d||z!==T||(y=y.then(async()=>{await c(),await NK(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),V())}),G.ev.on("connection.update",U=>{if(!(d||z!==T)&&(typeof U.qr=="string"&&U.qr&&t(U.qr),U.connection==="open"&&(K=!0,V()),U.connection==="close")){let N=kXe(U.lastDisconnect?.error);if(N===tr.restartRequired){_??=y.then(async()=>{d||z!==T||(await G.end(void 0).catch(()=>{}),!(d||z!==T)&&q())}).catch(X=>H(X)).finally(()=>{_=null});return}let k=N===tr.loggedOut,J=Object.assign(new Error(k?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:k?"logged-out":"connection-closed"});B?i?.({error:J,loggedOut:k}):H(J)}}),G.ev.on("messages.upsert",({messages:U,type:N})=>{if(!(d||z!==T||N!=="notify"&&N!=="append"||typeof o!="function"))for(let k of Array.isArray(U)?U:[]){if(N==="append"){let J=vXe(k?.messageTimestamp);if(J===null||J{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await F():e.addEventListener("abort",()=>void F(),{once:!0})),Object.freeze({get socket(){return m},ready:R,close:F,logout:L})}var kK=new Set(["image/jpeg","image/png","image/webp","image/gif"]),FXe=5*1024*1024,RK=15e3,vK=12e4,LXe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],UXe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]),HXe=new Set(["s.whatsapp.net","c.us","lid","hosted","hosted.lid"]);function ele(n){if(typeof n!="string")return null;let t=n.trim();if(/^\+?\d+$/.test(t))return`${t.replace(/^\+/,"")}@s.whatsapp.net`;let o=fA(t);return!o||!/^\d+$/.test(o.user)||!HXe.has(o.server)?null:t}function FK(n,t){let o=ele(n),i=ele(t);if(!o||!i)return!1;try{return kt(o,i)===!0}catch{return!1}}function KXe(n){let t=n;for(let o=0;o<5&&t&&typeof t=="object";o+=1){let i=LXe.find(e=>t[e]?.message);if(!i)return!1;if(UXe.has(i))return!0;t=t[i].message}return!1}function xXe(n){return n?.extendedTextMessage?.contextInfo??n?.imageMessage?.contextInfo??n?.videoMessage?.contextInfo??n?.documentMessage?.contextInfo??null}function tle(n){return n?.conversation??n?.extendedTextMessage?.text??n?.imageMessage?.caption??n?.videoMessage?.caption??n?.documentMessage?.caption??""}function cQ(n,t,o){if(!t||typeof t!="object")return null;let i=typeof t.fileName=="string"&&t.fileName?t.fileName:typeof o=="string"&&o?o:void 0;return{kind:n,...i?{name:i}:{}}}function YXe(n){let t=[];if(n?.imageMessage&&t.push(cQ("image",n.imageMessage)),n?.documentMessage){let o=typeof n.documentMessage.mimetype=="string"?n.documentMessage.mimetype.toLowerCase():"";t.push(cQ(o.startsWith("image/")?"image":"file",n.documentMessage))}if(n?.audioMessage&&t.push(cQ("audio",n.audioMessage)),n?.videoMessage&&t.push(cQ("video",n.videoMessage)),n?.stickerMessage){let o=typeof n.stickerMessage.mimetype=="string"?n.stickerMessage.mimetype.toLowerCase():"";t.push(cQ(o.startsWith("video/")||n.stickerMessage.isAnimated===!0?"video":"image",n.stickerMessage))}return t.filter(Boolean)}function jXe(n){if(!n?.quotedMessage||typeof n.quotedMessage!="object")return;let t=ya(n.quotedMessage),o=typeof n.stanzaId=="string"&&n.stanzaId?n.stanzaId:void 0,i=typeof n.participant=="string"&&n.participant?n.participant:void 0;return{...o?{messageId:o}:{},...i?{authorId:i}:{},content:tle(t),attachments:YXe(t)}}function rle(n){if(Number.isSafeInteger(n)&&n>=0)return n;let t;try{t=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(t)&&t>=0?t:void 0}async function JXe(n,t,{signal:o,maxBytes:i=FXe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(RK),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>t(n,"stream",{options:{signal:a}})),r=await new Promise((I,d)=>{let B=!1,f=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",Q),y(m),!0),Q=()=>f(d,a.reason);a.addEventListener("abort",Q,{once:!0}),A.then(y=>{f(I,y)||y?.destroy?.()},y=>f(d,y)),a.aborted&&Q()}).catch(I=>{throw o?.aborted?o.reason??I:e.aborted?new ft("image-download-failed",`WhatsApp image download timed out after ${RK} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}),s=[],g=0,c=()=>r?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let I of r){a.throwIfAborted();let d=Buffer.from(I);if(g+=d.length,g>i)throw r.destroy?.(),new ft("image-too-large",`WhatsApp image exceeded ${i} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));s.push(d)}}catch(I){throw o?.aborted?o.reason??I:e.aborted?new ft("image-download-failed",`WhatsApp image stream timed out after ${RK} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function qXe(n,t,o,{viewOnce:i=!1}={}){let e,a;if(!i&&t?.imageMessage&&t.imageMessage.viewOnce!==!0)e=t.imageMessage;else if(t?.documentMessage){let r=typeof t.documentMessage.mimetype=="string"?t.documentMessage.mimetype.toLowerCase():"";if(!kK.has(r))return null;e=t.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return kK.has(A)?{name:a,mediaType:A,size:rle(e.fileLength),load:r=>JXe(n,o,r)}:null}function zXe(n,t,o){let i=t?.documentMessage;if(!i)return null;let e=typeof i.mimetype=="string"&&i.mimetype?i.mimetype.toLowerCase():void 0;return kK.has(e)?null:{name:typeof i.fileName=="string"&&i.fileName?i.fileName:"whatsapp-file",...e?{mediaType:e}:{},size:rle(i.fileLength),async load({signal:a}={}){a?.throwIfAborted();let A=await o(n,"stream",{options:{signal:a}});return a?.throwIfAborted(),{stream:A}}}}function VXe({socket:n,logger:t=console,download:o=WU}={}){if(typeof o!="function")throw new TypeError("WhatsApp media downloader is required");return typeof n?.updateMediaMessage!="function"?o:(i,e,a)=>o(i,e,a,{logger:t,reuploadRequest:A=>n.updateMediaMessage(A)})}function WXe(n,t,{download:o=WU}={}){let i=typeof n?.key?.remoteJid=="string"?n.key.remoteJid:"",e=typeof n?.key?.remoteJidAlt=="string"?n.key.remoteJidAlt:"",a=typeof n?.key?.id=="string"?n.key.id:"";if(!i||!a||i==="status@broadcast"||i.endsWith("@newsletter"))return null;let A=i.endsWith("@g.us"),r=n.key.fromMe===!0,s=r&&!A&&[i,e].some(_=>_&&kt(_,t));if(r&&!s&&!A)return null;let g=r?t:A?n.key.participant:i,c=A&&!r?n.key.participantAlt:e;if(typeof g!="string"||!g)return null;let I=KXe(n.message),d=ya(n.message),B=xXe(d),f=Array.isArray(B?.mentionedJid)&&B.mentionedJid.some(_=>kt(_,t)),Q=typeof B?.participant=="string"&&kt(B.participant,t),y=qXe(n,d,o,{viewOnce:I}),m=zXe(n,d,o),T=jXe(B);return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,contextSource:()=>({senderName:n.pushName}),senderAlternateId:typeof c=="string"?c:"",senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:tle(d),plainText:typeof d?.conversation=="string"||typeof d?.extendedTextMessage?.text=="string",images:y?[y]:[],files:m?[m]:[],...T?{replyTo:T}:{},addressed:!A||r||f||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s},reactionTarget:{jid:i,key:n.key}}}var PK=class{#e=new Map;has(t){return this.#t(),this.#e.has(t)}remember(t){this.#A(t)}reserve(t){this.#A(t)}#A(t){if(!(typeof t!="string"||!t))for(this.#t(),this.#e.set(t,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#t(){let t=Date.now();for(let[o,i]of this.#e)i>t||this.#e.delete(o)}};function ale(n){return n?.reason??new DOMException("The operation was aborted.","AbortError")}function Ale(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,ale(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function ZXe(n){if(n?.code==="artifact-delivery-uncertain")return n;let t=new Error("WhatsApp could not confirm artifact delivery.");return t.code="artifact-delivery-uncertain",t.cause=n,t}function XXe(n){if(n?.code?.startsWith?.("artifact-"))return n;let t=n?.output?.statusCode??n?.data?.statusCode??n?.statusCode,o;if(t===401||t===403?o="artifact-permission-required":t===413?o="artifact-too-large":t===429?o="artifact-rate-limited":[400,404,405,406,410,415,422].includes(t)&&(o="artifact-provider-rejected"),!o)return ZXe(n);let i=new Error("WhatsApp rejected artifact delivery.");return i.code=o,i.cause=n,i}var GK=class{#e;#A;#t;#r;#l=new Map;constructor(t,o,{signal:i,mediaUploadTimeoutMs:e=vK}={}){this.#e=t,this.#A=o,this.#t=i,this.#r=e}async sendText(t,o){await this.#a(t.jid);let i=[];for(let[e,a]of hs(o,4e3).entries()){let A=$Ie(10).toString("hex").toUpperCase(),r={...e===0&&t.quoted?{quoted:t.quoted}:{},messageId:A};typeof this.#A.reserve=="function"?this.#A.reserve(A):this.#A.remember(A);let s=await this.#e.sendMessage(t.jid,{text:a},r);this.#A.remember(s?.key?.id),typeof s?.key?.id=="string"&&s.key.id&&i.push(s.key.id)}return{providerMessageIds:i}}async sendFile(t,o){return this.#i(t,o,{document:o.bytes,mimetype:o.mediaType??"application/octet-stream",fileName:o.fileName},"file")}async sendImage(t,o){return this.#i(t,o,{image:o.bytes,mimetype:o.mediaType??"image/jpeg"},"image")}async addReaction(t,o,{signal:i}={}){if(typeof o!="string"||!o.trim())throw new TypeError("A WhatsApp reaction emoji is required");let e=o.trim();return await this.#o(t,e,i),e}removeReaction(t,o,{signal:i}={}){return this.#o(t,"",i)}async#o(t,o,i){if(typeof t?.jid!="string"||!t.jid||!t.key?.id)throw new TypeError("A WhatsApp reaction target is required");let e=i??this.#t;e?.throwIfAborted();let a=$Ie(10).toString("hex").toUpperCase();typeof this.#A.reserve=="function"?this.#A.reserve(a):this.#A.remember(a);let A=this.#e.sendMessage(t.jid,{react:{text:o,key:t.key}},{messageId:a}),r=await Ale(A,e);return this.#A.remember(r?.key?.id),r}async#i(t,o,i,e){this.#t?.throwIfAborted(),await this.#a(t.jid),this.#t?.throwIfAborted();let a=typeof o.deliveryKey=="string"&&o.deliveryKey?o.deliveryKey:o.artifactId,A=e==="image"?`${a}:image`:a,r=typeof A=="string"&&A?GXe("sha256").update(A).digest("hex").slice(0,20).toUpperCase():void 0,s={...t.quoted?{quoted:t.quoted}:{},...r?{messageId:r}:{},mediaUploadTimeoutMs:this.#r};this.#A.remember(r);let g;try{let c=this.#e.sendMessage(t.jid,i,s);mn(o,c);let I=AbortSignal.timeout(this.#r),d=this.#t?AbortSignal.any([this.#t,I]):I;g=await Ale(c,d)}catch(c){throw this.#t?.aborted?ale(this.#t):XXe(c)}return this.#t?.throwIfAborted(),this.#A.remember(g?.key?.id),g}async sendTyping(t){!t.selfChat&&t.quoted?.key&&await this.#e.readMessages([t.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",t.jid),await this.#a(t.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",t.jid).catch(()=>{this.#a(t.jid)})},2e4);o.unref?.(),this.#l.set(t.jid,o)}async close(){let t=[...this.#l.keys()];await Promise.allSettled(t.map(o=>this.#a(o)))}async#a(t,o=!0){let i=this.#l.get(t);i&&clearInterval(i),this.#l.delete(t),o&&await this.#e.sendPresenceUpdate("paused",t).catch(()=>{})}};function $Xe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...so()}}var IQ=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c=$Xe();#g=null;#I=null;#p=null;#E=null;#u=null;constructor({config:t,authDir:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,logger:r=console,replyTimeoutMs:s=6e5,connectTimeoutMs:g=3e4,mediaUploadTimeoutMs:c=vK,createSession:I=HM}){if(!t||!o||!i||!e||typeof I!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");if(this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,!Number.isSafeInteger(c)||c<=0)throw new TypeError("mediaUploadTimeoutMs must be a positive safe integer");this.#s=Math.min(c,vK),this.#d=I}get status(){return structuredClone(this.#c)}async start(){return this.#c.ready&&this.#I?this.status:this.#u?this.#u:(this.#u=this.#C().finally(()=>{this.#u=null}),this.#u)}async#C(){await this.stop(),this.#c.startedAt=new Date().toISOString(),this.#c.connectionState="connecting",this.#c.lastError=null,await this.#t.ensureRunning(),this.#c.harnessReachable=!0;let t=new AbortController;this.#g=t;let o=new PK,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#d({authDir:this.#A,signal:t.signal,logger:this.#i,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async(c,I)=>{let d=WXe(c,this.#e.accountJid,{download:VXe({socket:I?.socket,logger:this.#i})});!d||o.has(d.providerMessageId)||!this.#E||(this.#c.lastCheckedAt=Date.now(),await this.#E.accept(d))},onDisconnect:({error:c})=>{t.signal.aborted||(this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=c?.message??"WhatsApp Web connection closed")}});this.#I=a;let A,r=await Promise.race([a.ready,e,new Promise((c,I)=>{A=setTimeout(()=>I(new Error("WhatsApp Web did not connect in time")),this.#n)})]).finally(()=>clearTimeout(A));if(!kt(r.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new GK(a.socket,o,{signal:t.signal,mediaUploadTimeoutMs:this.#s});this.#p=s,this.#E=new UM({bot:s,harness:this.#t,state:this.#r,contextEnhancement:this.#l,accessPolicy:this.#o?{botId:this.#o.botId,getSettings:(...c)=>this.#o.getSettings(...c),...typeof this.#o.isPrivileged=="function"?{isPrivileged:(...c)=>this.#o.isPrivileged(...c)}:{},equals:FK}:void 0,status:this.#c,logger:this.#i,replyTimeoutMs:this.#a,signal:t.signal});let g=Date.now();return this.#c.ready=!0,this.#c.connectionState="connected",this.#c.lastCheckedAt=g,this.#c.lastConnectedAt=g,this.status}catch(a){throw this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#I?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(t){if(!this.#c.ready||!this.#p){let o=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw o.code="test-target-unavailable",o}if(typeof t!="string"||!t.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#p.sendText({jid:this.#e.accountJid,selfChat:!0},t),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.jid=="string"?t.route.jid.trim():"",a=t?.kind==="user"&&/^[^@\s]+@(s\.whatsapp\.net|lid)$/.test(e),A=t?.kind==="group"&&/^[^@\s]+@g\.us$/.test(e);if(!a&&!A){let r=new TypeError("Invalid WhatsApp proactive delivery target");throw r.code="invalid-target",r}if(!this.#c.ready||!this.#p){let r=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return i?.throwIfAborted(),this.#p.sendText({jid:e},o)}async stop(){let t=this.#I,o=this.#p,i=this.#E;return this.#g?.abort(),this.#g=null,this.#I=null,this.#p=null,this.#E=null,await o?.close().catch(()=>{}),await t?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#c.ready=!1,this.#c.connectionState="idle",this.status}};var r7e=/^[a-f0-9-]{36}$/;function a7e(n){let t=cc(n.dshHome??process.env.DSH_HOME??LE(t7e(),".dsh")),o=cc(n.dataDir??LE(t,"integrations","dsh-whatsapp")),i=cc(n.authDir??LE(o,"auth")),e=a=>{if(!r7e.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return cc(i,a)};return{config:cc(n.configPath??LE(o,"config.json")),bots:cc(n.botsDir??LE(o,"bots")),workspaces:cc(n.workspacesPath??LE(o,"workspaces.json")),authPath:e}}async function LK(n,t={},o={}){let i=na(n,t),e=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,a=()=>xa(n),A=o.ConfigStore??AD,r=o.StateStore??aD,s=o.HarnessClient??rD,g=o.Controller??DB,c=o.Runtime??IQ,I=o.createSession??HM,d=o.createConnectionSupervisor??ep,B=a7e(t),f=await new A(B.config).load(),Q=cc(t.workspace??process.cwd()),y=o.WorkspaceStore??oa,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),T=f.list();await m.reconcile(T.map(k=>k.botId)),await Promise.all(T.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("whatsapp",k)})));let _=typeof f.remove=="function"?Ya(f,{workspaces:m}):f,R=new Map,H=k=>cc(B.bots,k,"state.json"),F=async k=>{let J=R.get(k);return J||(J=await new r(H(k)).load(),R.set(k,J)),J},L=za(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:z,fileIngressExecutor:K}=Va(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),G=new s({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...L?{commandExecutor:L}:{},...q?{controlExecutor:q}:{},...z?{sessionMaintenanceExecutor:z}:{},...K?{fileIngressExecutor:K}:{}}),V=new g({configStore:_,authPath:B.authPath,createSession:I,logger:e,createRuntime:async({botId:k,config:J,authDir:X})=>{let ae=await F(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("whatsapp",J)});let De=ja(G,{botId:k,workspaces:m,state:ae,agentPresetCatalog:a});return new c({config:J,authDir:X,harness:De.harness,state:De.state,contextEnhancement:{botId:k,getSettings:()=>m.contextEnhancementFor(k)},accessPolicy:Wa(m,k,{channel:"whatsapp",config:J,equals:FK}),replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??3e4,createSession:I,logger:{error:(...oe)=>e.error?.(`[${k}]`,...oe),warn:(...oe)=>e.warn?.(`[${k}]`,...oe),info:(...oe)=>e.info?.(`[${k}]`,...oe),debug:(...oe)=>e.debug?.(`[${k}]`,...oe)}})},deleteAuth:k=>e7e(B.authPath(k),{recursive:!0,force:!0}),deleteState:async({botId:k})=>{let J=R.get(k);if(R.delete(k),J&&typeof J.remove=="function")await J.remove();else try{await A7e(H(k))}catch(X){if(X?.code!=="ENOENT")throw X}}}),U=Ja(V,{workspaces:m,stateFor:F,agentPresetCatalog:a}),N=d({channel:"whatsapp",controller:U,harness:G,logger:e,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:U,deliveryAdapter:qa({channel:"whatsapp",workspaces:m,coreController:V,stateFor:F}),ready:N.ready,async close(){await N.close(),await U.close(),G.stopManagedProcess()}}}import i7e from"qrcode";var ile="/whatsapp",_r=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setAccessPolicy:Xa,setWorkspace:Gi,setAgentPreset:Fi,setContextEnhancement:Pi}),ole=Object.freeze(Object.values(_r)),o7e=new Set(["qrValue","accountJid","authDirectory"]);function KK(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function KM(n,t){return KK(n)&&Object.keys(n).every(o=>t.includes(o))}function UK(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function n7e(n,t){return KK(t)?[_r.status,_r.beginProvisioning].includes(n)?KM(t,[])?null:`${n} does not accept fields.`:[_r.pollProvisioning,_r.cancelProvisioning].includes(n)?KM(t,["attemptId"])&&UK(t.attemptId)?null:`${n} requires an attemptId.`:n===_r.reconnectBot?KM(t,["botId","sendTest"])&&UK(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.":n===_r.deleteBot?KM(t,["botId","confirm"])&&UK(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===_r.setAccessPolicy?$a(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u8BBF\u95EE\u8BBE\u7F6E\u3002":n===_r.setWorkspace?ei(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===_r.setAgentPreset?ti(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===_r.setContextEnhancement?Za(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown WhatsApp endpoint.":"Payload must be an object."}function UE(n){if(Array.isArray(n))return n.map(UE);if(!KK(n))return n;let t={};for(let[o,i]of Object.entries(n))o7e.has(o)||(t[o]=UE(i));return t}async function s7e(n){return i7e.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function HK(n,t){return!n||typeof n.qrValue!="string"?UE(n):UE({...n,qrCodeDataUrl:await t(n.qrValue)})}async function Dd(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await HK(o.provisioning,t)),UE(o)}function nle(n,{encodeQr:t=s7e}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete WhatsApp controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!ole.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let r=n7e(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===_r.status)s=await Dd(await n.status(),i);else if(e===_r.beginProvisioning)s=await HK(await n.startProvisioning(),i);else if(e===_r.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await HK(g,i)}else if(e===_r.cancelProvisioning)s=UE(await n.cancelProvisioning(a.attemptId));else if(e===_r.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(s=await Dd(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(d=>d?.botId===a.botId&&d.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let d=new Error("Connection test is unavailable");throw d.code="test-target-unavailable",d}await n.sendConnectionTest(a.botId)}catch(d){c=d}s={...s,testMessage:gr(c)}}}else if(e===_r.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Dd(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===_r.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>Dd(g,i))}else if(e===_r.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Dd(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else if(e===_r.setAccessPolicy){if(typeof n.updateAccessPolicy!="function")throw new Error("Access policy update is unavailable");s=await n.updateAccessPolicy(a.botId,a.policy,g=>Dd(g,i))}else s=await Dd(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ai(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"whatsapp-operation-failed",message:"WhatsApp \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function xM(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(ile,nle(t,o),{authority:yr(i)})}async function sle(n,t={}){if(t?.controller)return xM(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await LK(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=xM(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close WhatsApp Web connections"),e}var g7e="/dsh-im-delivery",c7e="DSH-IM \u4E3B\u52A8\u6295\u9012\u6D4B\u8BD5\u6210\u529F\u3002",wi=Object.freeze({send:"message.send",listTargets:"target.list",listSuggestions:"target.suggestion.list",createTarget:"target.create",updateTarget:"target.update",deleteTarget:"target.delete",testTarget:"target.test"}),I7e=new Set(Object.values(wi)),l7e=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function dQ(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function RI(n,t){return dQ(n)&&Object.keys(n).length===t.length&&Object.keys(n).every(o=>t.includes(o))}function Od(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function lQ(n){return typeof n=="string"&&/^[A-Za-z0-9._:@-]{1,128}$/.test(n)}function gle(n,{targetId:t}){let o=t?["targetId","name","kind","route"]:["name","kind","route"];return!dQ(n)||Object.keys(n).some(i=>!o.includes(i))||t&&!lQ(n.targetId)||n.name!==void 0&&(typeof n.name!="string"||!n.name.trim()||n.name.trim().length>80)?!1:typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&dQ(n.route)}function d7e(n){return RI(n,["kind","route"])&&typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&dQ(n.route)}function p7e(n,t){return!I7e.has(n)||!dQ(t)?!1:n===wi.send?RI(t,["botId","targetId","text"])&&Od(t.botId)&&lQ(t.targetId)&&typeof t.text=="string"&&!!t.text.trim():n===wi.listTargets||n===wi.listSuggestions?RI(t,["botId"])&&Od(t.botId):n===wi.createTarget?RI(t,["botId","target"])&&Od(t.botId)&&gle(t.target,{targetId:!0}):n===wi.updateTarget?RI(t,["botId","targetId","target"])&&Od(t.botId)&&lQ(t.targetId)&&gle(t.target,{targetId:!1}):n===wi.testTarget?RI(t,["botId","targetId"])&&Od(t.botId)&&lQ(t.targetId)||RI(t,["botId","target"])&&Od(t.botId)&&d7e(t.target):RI(t,["botId","targetId"])&&Od(t.botId)&&lQ(t.targetId)}function h7e(n){let t=l7e.has(n?.code)?n.code:"delivery-failed";return{code:t,message:t,details:{}}}function xK(n){for(let t of["send","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget"])if(typeof n?.[t]!="function")throw new TypeError(`A complete delivery service is required (${t})`);return async(t,o,i)=>{if(!p7e(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid delivery request.",details:{}}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"cancelled",details:{}}};try{let e;return t===wi.send?e=await n.send(o.botId,o.targetId,o.text,{signal:i}):t===wi.listTargets?e=await n.listTargets(o.botId):t===wi.listSuggestions?e=await n.listSuggestions(o.botId):t===wi.createTarget?e=await n.createTarget(o.botId,o.target):t===wi.updateTarget?e=await n.updateTarget(o.botId,o.targetId,o.target):t===wi.deleteTarget?e=await n.deleteTarget(o.botId,o.targetId):e=await n.send(o.botId,Object.hasOwn(o,"target")?o.target:o.targetId,c7e,{signal:i}),{ok:!0,value:e}}catch(e){return{ok:!1,error:h7e(e)}}}}function cle(n,t,{authority:o}={}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(g7e,xK(t),{authority:yr(o)})}var Ile="/api/dsh-im/delivery/messages",lle=1024*1024,E7e=Object.freeze({"bad-request":400,"unknown-bot":404,"unknown-target":404,"target-conflict":409,"invalid-target":422,"bot-not-connected":503,"target-rejected":422,"delivery-failed":502,cancelled:408}),KE=class extends Error{constructor(t,o){super(o),this.status=t,this.code=o}};function HE(n,t,o,i={}){if(n.destroyed||n.writableEnded)return;let e=JSON.stringify(o);n.writeHead(t,{"cache-control":"no-store","content-type":"application/json; charset=utf-8","content-length":String(Buffer.byteLength(e)),...i}),n.end(e)}function u7e(n){return typeof n=="string"&&n.split(";",1)[0].trim().toLowerCase()==="application/json"}async function C7e(n){let t=Number(n.headers["content-length"]);if(Number.isFinite(t)&&t>lle)throw new KE(413,"payload-too-large");let o=[],i=0;for await(let e of n){let a=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=a.length,i>lle)throw new KE(413,"payload-too-large");o.push(a)}try{return JSON.parse(Buffer.concat(o,i).toString("utf8"))}catch{throw new KE(400,"bad-request")}}function B7e(n){let t=xK(n);return async(o,i)=>{if(o.method!=="POST"){HE(i,405,{error:{code:"method-not-allowed",message:"method-not-allowed",details:{}}},{allow:"POST"});return}if(!u7e(o.headers["content-type"])){HE(i,415,{error:{code:"unsupported-media-type",message:"unsupported-media-type",details:{}}});return}let e=new AbortController,a=()=>e.abort(),A=()=>{i.writableEnded||a()};o.once("aborted",a),i.once("close",A);try{let r=await C7e(o),s=await t(wi.send,r,e.signal);if(s.ok){HE(i,200,s.value);return}HE(i,E7e[s.error.code]??500,{error:s.error})}catch(r){if(r instanceof KE){HE(i,r.status,{error:{code:r.code,message:r.code,details:{}}});return}HE(i,500,{error:{code:"delivery-failed",message:"delivery-failed",details:{}}})}finally{o.off("aborted",a),i.off("close",A)}}}function dle(n,t){if(!n?.webServer||typeof n.webServer.register!="function"||typeof n.effect!="function")throw new TypeError("DSH Host WebServer is required");let o={kind:"exact",path:Ile,handler:B7e(t)};return n.effect(()=>n.webServer.register(o),`dsh-im: ${Ile}`)}var f7e=/^[A-Za-z0-9_-]{1,128}$/,Q7e=/^[A-Za-z0-9._:@-]{1,128}$/,y7e=/^[a-z][a-z0-9-]{0,31}$/,m7e="__test__",S7e=Object.freeze(["ownsBot","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget","sendText"]),w7e=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function un(n,t=n,o){let i=new Error(t,o);return i.code=n,i}function xE(n){if(typeof n!="string"||!f7e.test(n))throw un("bad-request","Invalid bot id");return n}function YM(n){if(typeof n!="string"||!Q7e.test(n))throw un("bad-request","Invalid target id");return n}function YK(n,{includesTargetId:t}={}){if(!n||typeof n!="object"||Array.isArray(n))throw un("bad-request","Invalid target");if(t)YM(n.targetId);else if(Object.hasOwn(n,"targetId"))throw un("bad-request","A target id cannot be changed");return n}function D7e(n){YK(n);let t=Object.keys(n);if(t.length!==2||!t.includes("kind")||!t.includes("route"))throw un("bad-request","Invalid draft target");return n}function ple(n){if(n?.aborted)throw un("cancelled","Request cancelled")}function bd(n,t="delivery-failed"){return n?.code==="workspace-bot-not-found"?un("unknown-bot","Unknown bot",{cause:n}):w7e.has(n?.code)?n:un(t,t,{cause:n})}function O7e(n){if(!n||typeof n!="object"||typeof n.channel!="string"||!y7e.test(n.channel))throw new TypeError("A delivery adapter with a valid channel is required");for(let t of S7e)if(typeof n[t]!="function")throw new TypeError(`A complete delivery adapter is required (${t})`);return n}var jK=class{#e=new Map;registerAdapter(t){let o=O7e(t),i=Object.freeze({adapter:o});return this.#e.set(o.channel,i),()=>this.#e.get(o.channel)!==i?!1:(this.#e.delete(o.channel),!0)}async listTargets(t){let o=xE(t),i=await this.#A(o);try{let e=await i.listTargets(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid targets");return{botId:o,channel:i.channel,targets:e}}catch(e){throw bd(e)}}async listSuggestions(t){let o=xE(t),i=await this.#A(o);try{let e=await i.listSuggestions(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid suggestions");return{botId:o,channel:i.channel,suggestions:e.map(a=>Vd(i.channel,a,{targetIdRequired:!1}))}}catch(e){throw bd(e)}}async createTarget(t,o){let i=xE(t);YK(o,{includesTargetId:!0});let e=await this.#A(i);try{return await e.createTarget(i,o)}catch(a){throw bd(a)}}async updateTarget(t,o,i){let e=xE(t),a=YM(o);YK(i);let A=await this.#A(e);try{return await A.updateTarget(e,a,i)}catch(r){throw bd(r)}}async deleteTarget(t,o){let i=xE(t),e=YM(o),a=await this.#A(i);try{return await a.deleteTarget(i,e),{deleted:!0}}catch(A){throw bd(A)}}async send(t,o,i,{signal:e}={}){let a=xE(t),A=typeof o=="string"?YM(o):null,r=A===null?D7e(o):null;if(typeof i!="string"||!i.trim())throw un("bad-request","Message text is required");ple(e);let s=await this.#A(a);try{let g;if(r)g={targetId:m7e,...r};else{let c=await s.listTargets(a);if(!Array.isArray(c))throw new TypeError("Adapter returned invalid targets");if(g=c.find(I=>I?.targetId===A),!g)throw un("unknown-target","Unknown target")}return ple(e),await s.sendText(a,g,i,{signal:e}),{sent:!0}}catch(g){throw e?.aborted||g?.name==="AbortError"||g?.code==="ABORT_ERR"?un("cancelled","Request cancelled",{cause:g}):bd(g)}}async#A(t){for(let{adapter:o}of this.#e.values()){let i;try{i=await o.ownsBot(t)}catch(e){throw bd(e)}if(i)return o}throw un("unknown-bot","Unknown bot")}};function hle(){return new jK}var pQ=ze(aO(),1);import{createHash as b7e}from"node:crypto";import{readFile as Cle,realpath as As,stat as M7e}from"node:fs/promises";import{homedir as _7e}from"node:os";import{basename as T7e,dirname as qK,isAbsolute as WK,join as Ic,relative as N7e,resolve as JM,sep as R7e}from"node:path";import{fileURLToPath as k7e}from"node:url";var kI="dsh-im-ops",hQ="https://registry.npmjs.org/",v7e=15*6e4,P7e=1e4,Ele=16*1024;function ts(n,t={}){return Object.assign(new Error(n),{code:n,...t})}function jM(n,t){return typeof n?.get=="function"?n.get(t):n?.[t]}function zK(n,t){let o=N7e(n,t);return o!==".."&&!o.startsWith(`..${R7e}`)&&!WK(o)}async function G7e(n){try{return await Cle(n,"utf8")}catch(t){if(t.code==="ENOENT")return"";throw t}}async function VK(n){let t=await Cle(Ic(n,"package.json"),"utf8");return{directory:await As(n),manifest:JSON.parse(t),contents:t}}async function JK(n,t){let o=qK(await As(n));for(;;){try{let e=await VK(o);return e.manifest?.name===t?e:null}catch(e){if(e.code!=="ENOENT")throw e}let i=qK(o);if(i===o)return null;o=i}}function F7e(n){return typeof n=="string"&&n.length>0&&Buffer.byteLength(n)<=255&&!n.startsWith("-")&&![".","..","node_modules"].includes(n)&&!/[\\/\x00-\x1f\x7f<>:"|?*]/u.test(n)}function L7e(n){if(n[0]==="web")return"web";let t;for(let o=0;o0&&(pQ.default.validRange(n)!==null||/^[A-Za-z][A-Za-z0-9._-]*$/u.test(n))}async function K7e(n){if(n.manifest?.name!==kI||pQ.default.valid(n.manifest.version)===null)return!1;let t=[n.manifest.main,n.manifest.exports?.["./client"],n.manifest.dsh?.bundle?.patch];for(let o of t){if(typeof o!="string"||!o||WK(o)||o.includes("\0"))return!1;let i=JM(n.directory,o);if(!zK(n.directory,i)||!zK(n.directory,await As(i))||!(await M7e(i)).isFile())return!1}return!0}function x7e(n){if(n==null||n==="")return!0;if(typeof n!="string")return!1;try{return new URL(n).href===hQ}catch{return!1}}async function ule(n,{signal:t,timeoutMs:o,errorCode:i,capture:e=!1}){if(t?.aborted)throw ts("install-interrupted");let a=new AbortController,A,r,s=B=>{A??=B,a.abort(),r?.cancel?.()},g=()=>s("install-interrupted");t?.addEventListener("abort",g,{once:!0});let c=setTimeout(()=>s("install-timeout"),o),I="",d="";try{r=n(a.signal),r.stdout?.on("data",f=>{e&&(I=(I+f.toString()).slice(-Ele))}),r.stderr?.on("data",f=>{d=(d+f.toString()).slice(-Ele)}),r.stdout?.on("error",()=>s(i)),r.stderr?.on("error",()=>s(i));let B=await r.done;if(A)throw ts(A);if(B.exitCode!==0||B.signal)throw ts(i,{exitCode:B.exitCode,diagnosticCode:d.match(/\bERR_PNPM_[A-Z0-9_]+\b/u)?.[0]});return{exitCode:0,signal:null,...e?{stdout:I}:{}}}catch(B){throw A?ts(A):B.code===i?B:ts(i)}finally{clearTimeout(c),t?.removeEventListener("abort",g)}}function Ble(n={}){let t=n.ctx,o=n.env??process.env,i=n.argv??process.argv,e=n.execArgv??process.execArgv,a=n.execPath??process.execPath,A=n.cwd??process.cwd(),r=n.platform??process.platform,s=n.osHome??_7e(),g=n.electron??process.versions.electron,c=n.moduleUrl??import.meta.url,I=JK(k7e(c),kI).catch(()=>null),d;async function B(){let T=jM(t,"desktopProfiles"),_=jM(t,"desktopPnpm"),R=jM(t,"desktopPnpmBootstrap"),H=!!(g||T||_||R),F=T?.current,L=H?F?.name:L7e(i.slice(2)),q=H&&R?.homeDir?JM(R.homeDir):U7e(o,s),z={environmentKind:H?"desktop":"cli",homeDir:q,profileName:L};if(!F7e(L))return{...z,blockedReason:"unknown-profile"};let K=await As(Ic(q,"profiles",L)),G=await As(q),V={...z,homeDir:G,profileDir:K};if(H)try{if(typeof _?.runPlugin!="function"||typeof _?.run!="function"||!R||!F?.dir||R.activeProfileName!==L||await As(F.dir)!==K||await As(R.activeProfileDir)!==K||await As(R.appExecutable)!==await As(a))return{...V,blockedReason:"executor-unavailable"};let N=await JK(R.dshBootstrapPath,"dsh-plugin-desktop");return!N||T7e(R.dshBootstrapPath)!=="desktop-cli.js"||qK(await As(R.dshBootstrapPath))!==Ic(N.directory,"lib")?{...V,blockedReason:"executor-unavailable"}:{...V,desktop:_,executable:a,cliEntry:R.dshBootstrapPath}}catch{return{...V,blockedReason:"executor-unavailable"}}let U=jM(t,"subprocess");if(typeof U?.spawn!="function"||typeof i[1]!="string"||!WK(i[1])||r==="win32")return{...V,blockedReason:"executor-unavailable"};try{let N=await JK(i[1],"@deepseek-ai/dsh");if(!N)return{...V,blockedReason:"executor-unavailable"};let k=await As(i[1]),J=typeof N.manifest.bin=="string"?N.manifest.bin:N.manifest.bin?.dsh,X=typeof J=="string"?JM(N.directory,J):"";return k!==X&&k!==Ic(N.directory,"src","bin.ts")?{...V,blockedReason:"executor-unavailable"}:{...V,subprocess:U,executable:a,cliEntry:k}}catch{return{...V,blockedReason:"executor-unavailable"}}}function f(T,_,R,H=!1){let F=T.subprocess.spawn({argv:H?["pnpm",..._]:[a,...e,T.cliEntry,..._],cwd:H?T.profileDir:A,env:{DSH_HOME:T.homeDir,CI:"true"},stdio:{stdin:"ignore",stdout:"pipe",stderr:"pipe"},graceMs:3e3,signal:R});return{stdout:F.stdout,stderr:F.stderr,cancel:()=>F.terminate(),done:(async()=>{try{return await F.done}finally{await F.waitForExit()}})()}}async function Q(T,_){let R=["config","get","@xmanrui:registry","--json"],F=(await ule(q=>T.desktop?T.desktop.run(R,q):f(T,R,q,!0),{signal:_,timeoutMs:n.configTimeoutMs??P7e,errorCode:"registry-check-failed",capture:!0})).stdout.trim(),L;try{L=F===""||F==="undefined"?void 0:JSON.parse(F)}catch{throw ts("registry-check-failed")}if(!x7e(L))throw ts("registry-conflict")}async function y({preflight:T=!1}={}){let _,R={installedVersion:null,packageValid:!1,eligible:!1,installationKey:null};try{_=await B();for(let G of["homeDir","profileDir","profileName","environmentKind","executable","cliEntry"])R[G]=_[G]??null;if(!_.profileDir)return{...R,blockedReason:_.blockedReason??"unknown-profile"};let H=await VK(_.profileDir),F=await VK(Ic(_.profileDir,"node_modules",kI));R.sourceInstall=!H7e(H.manifest.dependencies?.[kI])||!zK(Ic(_.profileDir,"node_modules"),F.directory),R.installedVersion=typeof F.manifest.version=="string"?F.manifest.version:null,R.packageValid=await K7e(F);let L=await I,q=`${_.homeDir}\0${_.profileDir}\0${_.profileName}`,z=L?.directory===F.directory&&L?.manifest.version===F.manifest.version;d===void 0&&z&&R.packageValid&&(d=q);let K=await Promise.all(["pnpm-lock.yaml","pnpm-workspace.yaml","package-lock.json"].map(G=>G7e(Ic(_.profileDir,G))));return R.installationKey=b7e("sha256").update(JSON.stringify([q,H.contents,F.directory,F.contents,_.cliEntry,_.executable,...K])).digest("hex"),d!==void 0&&d!==q||!z&&d===void 0?R.blockedReason="installation-changed":R.packageValid?R.sourceInstall?R.blockedReason="source-install":_.blockedReason?R.blockedReason=_.blockedReason:z?T&&await Q(_):R.blockedReason="pending-restart":R.blockedReason="invalid-installation",R.eligible=!R.blockedReason,{...R,blockedReason:R.blockedReason??null}}catch(H){return{...R,blockedReason:["registry-conflict","registry-check-failed","install-timeout","install-interrupted"].includes(H.code)?H.code:_?.profileDir?"invalid-installation":"unknown-profile"}}}async function m(T,{signal:_,expectedInstallationKey:R}={}){if(pQ.default.valid(T)!==T||pQ.default.prerelease(T))throw ts("invalid-version");let H=await y();if(R!==void 0&&H.installationKey!==R)throw ts("installation-changed");if(!H.eligible)throw ts(H.blockedReason);let F=await B();await Q(F,_);let L=await y();if(!L.eligible||L.installationKey!==H.installationKey)throw ts("installation-changed");let q=["add","-w","--save-exact",`${kI}@${T}`,`--registry=${hQ}`];return ule(z=>F.desktop?F.desktop.runPlugin(q,F.profileDir,z):f(F,["plugin","--profile",F.profileName,...q],z),{signal:_,timeoutMs:n.installTimeoutMs??v7e,errorCode:"install-failed"})}return Object.freeze({inspect:y,install:m})}var vI=ze(aO(),1);import{createHash as Y7e,randomUUID as XK}from"node:crypto";import{mkdir as j7e,open as J7e,readFile as Sle,rename as q7e,stat as wle,unlink as Dle,writeFile as z7e}from"node:fs/promises";import{isAbsolute as fle,join as uQ}from"node:path";var CQ=new Set(["installing","verifying"]),V7e=new Set([...CQ,"restart-required","completed","failed","interrupted"]),Qle=256*1024,W7e=["package.json","pnpm-lock.yaml","pnpm-workspace.yaml"],qM=Symbol("no update lock");function Mt(n){return Object.assign(new Error(n),{code:n})}async function yle(n=globalThis.fetch,t=1e4){let o;try{if(o=await n(`${hQ}${encodeURIComponent(kI)}/latest`,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(t)}),!o.ok)throw Mt("check-failed");if(Number(o.headers.get("content-length"))>Qle)throw Mt("invalid-release");let i=[],e=0;for await(let c of o.body){if(e+=c.byteLength,e>Qle)throw Mt("invalid-release");i.push(Buffer.from(c))}let a=JSON.parse(Buffer.concat(i).toString("utf8")),A=a.version;if(a.name!==kI||typeof A!="string"||vI.default.valid(A)!==A||vI.default.prerelease(A))throw Mt("invalid-release");let r=a.engines?.node;if(r!==void 0&&(typeof r!="string"||!vI.default.validRange(r)))throw Mt("invalid-release");let s=new URL(a.dist?.tarball),g=a.dist?.integrity;if(s.origin!==new URL(hQ).origin||s.username||s.password||s.search||s.hash||s.pathname!==`/dsh-im-ops/-/dsh-im-${A}.tgz`||typeof g!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(g))throw Mt("invalid-release");return{version:A,nodeRange:r??"*",integrity:g,tarball:s.href}}catch(i){throw i?.code==="invalid-release"||i instanceof SyntaxError||i instanceof TypeError&&o?.ok?Mt("invalid-release"):Mt("check-failed")}}function mle(n){if(!fle(n.homeDir??"")||!fle(n.profileDir??""))return null;let t=Y7e("sha256").update(n.profileDir).digest("hex").slice(0,24),o=uQ(n.homeDir,"updates","dsh-im",t);return{directory:o,state:uQ(o,"state.json"),lock:uQ(o,"install.lock"),backup:uQ(o,"before.json")}}async function ZK(n,t=null){try{if((await wle(n)).size>10*1024*1024)throw Mt("state-unavailable");return JSON.parse(await Sle(n,"utf8"))}catch(o){if(o.code==="ENOENT")return t;throw Mt("state-unavailable")}}async function EQ(n,t){let o=`${n}.${XK()}.tmp`;try{await z7e(o,`${JSON.stringify(t,null,2)} `,{mode:384,flag:"wx"}),await q7e(o,n)}catch{throw Mt("state-unavailable")}finally{await Dle(o).catch(i=>{if(i.code!=="ENOENT")throw Mt("state-unavailable")})}}function Z7e(n){if(!Number.isSafeInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return t.code!=="ESRCH"}}function X7e(n){if(!n)return null;let{id:t,state:o,targetVersion:i,message:e}=n;return{id:t,state:o,targetVersion:i,message:e}}function Ole({runtime:n,runningVersion:t=PQ.version,nodeVersion:o=process.versions.node,fetchImpl:i=globalThis.fetch,now:e=Date.now,checkTimeoutMs:a=1e4,confirmationTtlMs:A=10*6e4,installTimeoutMs:r=15*6e4}={}){let s={},g=null,c=null,I=-1/0,d=null,B=null,f=null,Q=null,y=!1;function m(){if(y)throw Mt("disposed")}async function T(V){let U=mle(V);if(!U)return null;if(Q?.statePath===U.state)return Q.job;let N=await ZK(U.state),k=await ZK(U.lock,qM);if(!N)return k!==qM?{id:"locked",state:"interrupted",message:"recovery-required",targetVersion:null}:null;if(!V7e.has(N.state)||typeof N.id!="string"||!vI.default.valid(N.targetVersion))throw Mt("state-unavailable");if(CQ.has(N.state)&&N.id!==d?.id&&(k===qM||k?.id!==N.id||!Z7e(k?.pid))&&(N={...N,state:"interrupted",message:"recovery-required"}),N.id!==d?.id&&!CQ.has(N.state)){if(k!==qM)return{...N,state:"interrupted",message:"recovery-required"};if(["failed","interrupted"].includes(N.state)&&V.packageValid===!0&&V.installedVersion===t&&!V.blockedReason)return N.targetVersion===t?{...N,state:"completed",message:"recovered"}:{...N,recoverable:!0}}return N.state==="restart-required"||N.state==="completed"?V.installedVersion!==N.targetVersion||V.packageValid!==!0?{...N,state:"interrupted",message:"installation-changed"}:{...N,state:t===N.targetVersion?"completed":"restart-required"}:N}function _(V,U){let N=V.blockedReason??g?.blockedReason??null;U?.state==="interrupted"&&!U.recoverable||U?.state==="failed"&&V.installedVersion!==t?N="recovery-required":(U?.state==="restart-required"||V.installedVersion&&V.installedVersion!==t)&&(N="pending-restart");let k=CQ.has(U?.state),J=!!(V.eligible&&!N&&!k&&g?.checkId&&e(){try{let V=await n.inspect({preflight:!0}),U=await yle(i,a);return m(),g={release:U,checkId:XK(),checkedAt:e(),expiresAt:e()+A,installationKey:V.installationKey,profileDir:V.profileDir,blockedReason:V.blockedReason??(vI.default.satisfies(o,U.nodeRange)?null:"incompatible-node")},_(V,await T(V))}catch(V){throw g&&(g={...g,checkId:null,expiresAt:0}),V}finally{c=null}})(),c))}async function F(V,U){(await ZK(V.lock))?.id===U&&await Dle(V.lock)}async function L(V,U,N){let k={};for(let J of W7e)try{let X=uQ(V.profileDir,J);if((await wle(X)).size>3*1024*1024)throw Mt("state-unavailable");k[J]=await Sle(X,"utf8")}catch(X){if(X.code!=="ENOENT")throw Mt("state-unavailable")}await EQ(U.backup,{jobId:N.id,previousVersion:N.previousVersion,files:k})}function q(V){d={...d,state:"interrupted",message:"state-unavailable"},Q={statePath:V.state,job:d}}async function z(V,U,N){let k=AbortSignal.timeout(r);try{if(await n.install(U.targetVersion,{signal:AbortSignal.any([f.signal,k]),expectedInstallationKey:N.installationKey}),y)throw Mt("interrupted");d={...d,state:"verifying",updatedAt:e()},await EQ(V.state,d);let J=await n.inspect();if(J.homeDir!==N.homeDir||J.profileDir!==N.profileDir||J.profileName!==N.profileName||J.blockedReason==="installation-changed")throw Mt("installation-changed");if(J.installedVersion!==U.targetVersion||J.packageValid!==!0||J.blockedReason&&J.blockedReason!=="pending-restart")throw Mt("verify-failed");d={...d,state:"restart-required",message:null,updatedAt:e()},await EQ(V.state,d)}catch(J){let X=k.aborted||J.code==="install-timeout",ae=y||f.signal.aborted||!X&&["interrupted","install-interrupted"].includes(J.code);d={...d,state:ae?"interrupted":"failed",message:ae?"interrupted":X?"install-timeout":["verify-failed","state-unavailable","installation-changed","registry-conflict"].includes(J.code)?J.code:"install-failed",updatedAt:e()};try{await EQ(V.state,d)}catch{q(V);return}}await F(V,U.id)}function K({checkId:V,requestId:U}){return gg(s,"install",async()=>{m();let N=await n.inspect({preflight:!0}),k=await T(N);if(k?.requestId===U)return _(N,k);if(CQ.has(k?.state)||k?.state==="restart-required")throw Mt("update-busy");let J=g;if(!J||!V||J.checkId!==V||e()>=J.expiresAt)throw Mt("check-expired");if(N.profileDir!==J.profileDir||N.installationKey!==J.installationKey)throw Mt("installation-changed");if(!_(N,k).canInstall)throw Mt(N.blockedReason??"update-busy");let X=mle(N);if(!X)throw Mt("state-unavailable");let ae={id:XK(),requestId:U,state:"installing",message:null,targetVersion:J.release.version,previousVersion:N.installedVersion,startedAt:e(),updatedAt:e()},De=!1;try{await j7e(X.directory,{recursive:!0,mode:448});let oe=await J7e(X.lock,"wx",384);De=!0;try{await oe.writeFile(JSON.stringify({id:ae.id,pid:process.pid,startedAt:e()}))}finally{await oe.close()}let Se=await yle(i,a);if(JSON.stringify(Se)!==JSON.stringify(J.release))throw Mt("check-expired");if(N=await n.inspect({preflight:!0}),N.profileDir!==J.profileDir||N.installationKey!==J.installationKey)throw Mt("installation-changed");if(!N.eligible||N.blockedReason)throw Mt(N.blockedReason??"update-busy");m(),await L(N,X,ae),await EQ(X.state,ae),m()}catch(oe){throw De&&await F(X,ae.id),oe.code==="EEXIST"?Mt("update-busy"):oe.code?.startsWith("E")?Mt("state-unavailable"):oe}return d=ae,f=new AbortController,B=z(X,ae,N).catch(()=>{q(X)}),_(N,ae)})}async function G(){y=!0,f?.abort(),B&&await B}return Object.freeze({status:R,check:H,install:K,close:G})}var $7e="/dsh-im",e$e=Object.freeze(["update.status","update.check","update.install"]);function A$e(n,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let o=Object.keys(t);return n!=="update.install"?o.length===0:o.length===2&&o.every(i=>i==="checkId"||i==="requestId")&&["checkId","requestId"].every(i=>typeof t[i]=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t[i]))}var t$e=new Set(["check-failed","invalid-release","check-expired","installation-changed","update-busy","install-failed","verify-failed","state-unavailable","interrupted","disposed","source-install","unknown-profile","unsupported-runtime","registry-conflict","incompatible-node","pending-restart","recovery-required","executor-unavailable","invalid-installation","registry-check-failed","install-timeout","install-interrupted","invalid-version"]);function r$e(n){return async(t,o,i)=>{if(!e$e.includes(t)||!A$e(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid update request."}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"Request cancelled."}};try{return{ok:!0,value:t==="update.install"?await n.install(o):t==="update.check"?await n.check():await n.status()}}catch(e){let a=t$e.has(e?.code)?e.code:"update-failed";return{ok:!1,error:{code:a,message:a}}}}}function ble(n,t={}){let o=t.runtime??Ble({ctx:n,moduleUrl:import.meta.url}),i=t.service??Ole({runtime:o}),e=n.connection.rpc.handle($7e,r$e(i),{authority:"loopback"});return n.effect(()=>()=>i.close(),"dsh-im: close update installer"),e}var Mle="dsh-im-host",a$e=["connection","credentials","typertGateway"];function i$e(n,t,o){let i=n[t]??{},e=n.rpcAuthority===void 0?i:{...i,rpcAuthority:n.rpcAuthority};return t==="office"?e:{...e,deliveryService:o}}function o$e(n={}){let t=n.installUpdateRpc??ble,o=n.installDeliveryRpc??cle,i=n.installDeliveryHttp??dle,e=n.createDeliveryService??hle,a=n.applyFeishu??QZ,A=n.applyWeixin??EX,r=n.applyDingtalk??D3,s=n.applyWecom??F9,g=n.applyQq??HZ,c=n.applySlack??i9,I=n.applyTelegram??Q9,d=n.applyDiscord??$3,B=n.applyOffice??ij,f=n.applyWhatsapp??sle,Q=[["feishu",a],["weixin",A],["dingtalk",r],["wecom",s],["qq",g],["slack",c],["telegram",I],["discord",d],["whatsapp",f],["office",B]];return Object.freeze({name:Mle,inject:a$e,async apply(m,T={}){let _=e();typeof m?.provide=="function"&&m.provide("dshIm",Object.freeze({send:(H,F,L,q)=>_.send(H,F,L,q),listTargets:async H=>(await _.listTargets(H)).targets}));let R=async H=>{await y(H,T,_)};if(typeof m?.inject=="function"){let H=typeof m?.typertGateway?.stream=="function";await m.inject(H?["sessionController","workspaceController"]:["apiProxy"],R),m.inject(["webServer"],F=>{i(F,_)});return}await R(m),m?.webServer?.register&&typeof m?.effect=="function"&&i(m,_)}});async function y(m,T,_){Fx(T.language??process.env.DSH_IM_LANGUAGE),typeof m?.inject=="function"?m.inject(["tools","systemPrompt"],F=>{Z_(F)}):Z_(m);let R=typeof m?.logger=="function"?m.logger(Mle):m?.logger??console;if(m?.connection?.rpc){try{t(m)}catch(F){R.error?.("[dsh-im] failed to activate update management; continuing with channels",F)}try{o(m,_,{authority:T.rpcAuthority})}catch(F){R.error?.("[dsh-im] failed to activate delivery management; continuing with channels",F)}}let H=[];for(let[F,L]of Q)try{await L(m,i$e(T,F,_))}catch(q){H.push(q),R.error?.(`[dsh-im] failed to activate ${F}; continuing with the remaining channels`,q)}if(H.length===Q.length)throw new AggregateError(H,"dsh-im failed to activate every channel")}}async function AKA(n,t={}){return o$e().apply(n,t)}export{AKA as apply,o$e as createImHostPlugin,a$e as inject,Mle as name}; /*! Bundled license information: