diff --git a/README.en.md b/README.en.md index e396c4c..8d9d0ab 100644 --- a/README.en.md +++ b/README.en.md @@ -74,6 +74,8 @@ Feishu QR binding records the scanner as an allowed user. Manual credentials can Each bot maintains an independent Harness workspace. A newly connected bot records the Harness Host process's current working directory (`process.cwd()`) as its default; the path is persisted and does not change when the Host is later restarted from another directory. Every bot card shows the current path and lets it be edited. +When a channel does not explicitly configure `agentPreset`, each new IM session inherits the Harness-wide `agent-presets.default`. Harness reads that default whenever it creates a session, so changing the setting affects only sessions created afterwards; existing sessions and sessions bound with `/session` keep their own preset. An explicit channel `agentPreset` always takes precedence for newly created sessions. + ## Bot commands | Command | Description | diff --git a/README.md b/README.md index 9b930f5..593ae54 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,8 @@ QQ 扫码接入使用腾讯 QQBot v2 官方流程。默认腾讯授权页会把 每个机器人维护独立的 Harness 工作区。新接入机器人会把 Harness Host 进程当时的工作目录(`process.cwd()`)记录为默认值;该路径会持久化,不会因为以后从其他目录重启 Host 而改变。设置页的机器人卡片会显示当前路径,并可直接修改。 +渠道没有显式配置 `agentPreset` 时,新建的 IM 会话继承 Harness 的 `agent-presets.default` 全局默认值。Harness 会在每次创建会话时读取该默认值,因此修改设置只影响之后创建的新会话;已有会话以及通过 `/session` 绑定的会话保持自身 preset。渠道显式配置的 `agentPreset` 始终优先。 + ## 机器人命令 | 命令 | 作用 | diff --git a/lib/index.js b/lib/index.js index 3ac63c9..7ceda50 100644 --- a/lib/index.js +++ b/lib/index.js @@ -82,13 +82,13 @@ ${eG}`:["session-not-registered","session-not-found"].includes(n?.code)?"\u672A\ `);function vt(n){return typeof n=="string"&&n.trim()?n.trim():null}function DAe(n){let r=[],o=new Set,i=n;for(;i&&typeof i=="object"&&r.length<3&&!o.has(i);){o.add(i);let e=vt(i.name)?.slice(0,80),a=vt(i.code)?.slice(0,80),A=vt(i.providerCode)?.slice(0,160),t=Number.isInteger(i.status)?i.status:void 0;r.push({...e?{name:e}:{},...a?{code:a}:{},...A?{providerCode:A}:{},...t?{status:t}:{}}),i=i.cause}return r}function wAe(n){let r=n,o=new Set;for(;r&&typeof r=="object"&&!o.has(r);){if(o.add(r),r.code==="image-download-address-failed")return"\u9489\u9489\u672A\u80FD\u6362\u53D6\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\uFF1B\u82E5\u6301\u7EED\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u7684\u201C\u4F01\u4E1A\u5185\u673A\u5668\u4EBA\u53D1\u9001\u6D88\u606F\u6743\u9650\u201D\u3002";if(r.code==="invalid-image-download")return"\u9489\u9489\u6CA1\u6709\u8FD4\u56DE\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002";if(r.code==="image-content-download-failed")return"\u9489\u9489\u8FD4\u56DE\u7684\u56FE\u7247\u4E34\u65F6\u5730\u5740\u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002";r=r.cause}return Za(n)}function OAe(n){return vt(n?.senderStaffId)??vt(n?.senderId)}function MAe(n){if(n?.content&&typeof n.content=="object")return n.content;if(typeof n?.content!="string")return null;try{let r=JSON.parse(n.content);return r&&typeof r=="object"?r:null}catch{return null}}function bAe(n){let r=n?.richText??n?.rich_text;return Array.isArray(r)?r:[]}function _Ae(n){return typeof n?.text=="string"?vt(n.text):typeof n?.text?.content=="string"?vt(n.text.content):String(n?.type).toLowerCase()==="text"&&typeof n?.content=="string"?vt(n.content):null}function tG(n){return vt(n?.downloadCode)??vt(n?.pictureDownloadCode)}function NAe(n,{api:r,clientId:o,clientSecret:i}={}){let e=String(n?.msgtype??"").toLowerCase(),a=MAe(n),A=e==="richtext"?bAe(a):[],t=e==="text"?vt(n?.text?.content)??"":A.map(_Ae).filter(Boolean).join(` `),s=[];if(e==="picture"){let g=tG(a);g&&s.push(g)}else if(e==="richtext")for(let g of A){if(String(g?.type??"").toLowerCase()!=="picture")continue;let c=tG(g);c&&s.push(c)}return{content:t,images:s.map((g,c)=>({name:c===0?"image":`image-${c+1}`,load:({signal:l,maxBytes:p})=>{if(typeof r?.downloadImage!="function")throw new Error("DingTalk API does not support image downloads");return r.downloadImage({clientId:o,clientSecret:i,robotCode:n?.robotCode,downloadCode:g,signal:l,maxBytes:p})}}))}}function TAe(n,r){if(String(n?.conversationType)==="2"){let o=vt(n?.conversationId);if(!o)throw new Error("DingTalk group message has no conversation id");return`group:${o}`}return`p2p:${r}`}function RAe(n,r){return String(n?.conversationType)==="2"?{type:"group",openConversationId:vt(n?.conversationId)}:{type:"user",userId:r}}function kAe(n){return n?.type==="text"&&vt(n.text)?n.text:n?.type==="tool"?n.name==="web_search"?"_\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\u5E76\u6574\u7406\u4FE1\u606F\u2026_":`_\u6B63\u5728\u4F7F\u7528 ${vt(n.name)??"\u5DE5\u5177"}\u2026_`:`_${vt(n?.text)??"\u6B63\u5728\u5904\u7406\u2026"}_`}function vAe(n,r,o){if(r.needsPresentation||!r.questions[r.index]||r.actor!==o||String(n?.conversationType)==="2"&&n?.isInAtList!==!0||n?.msgtype!=="text"||!vt(n?.text?.content))return!1;try{return lg(n.sessionWebhook),!0}catch{return!1}}function PAe(n){n.stats??={};for(let r of["messagesReceived","messagesReplied","messagesRejected","messagesIgnored"])n[r]??=0,n.stats[r]=n[r];n.pendingSenders??=[]}function ri(n,r){n[r]=(n[r]??0)+1,n.stats??={},n.stats[r]=n[r]}function cD({pendingSenders:n=[]}={}){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,pendingSenders:structuredClone(n),stats:{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0}}}var Sd=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i=new Map;#o=new Map;#c=new Map;#l=new Set;#p=new Set;#h;constructor({api:r,clientId:o,clientSecret:i,harness:e,state:a,status:A=cD(),logger:t=console,replyTimeoutMs:s=6e5,maxMessageChars:g=4e3,signal:c}){if(!r||typeof r.sendText!="function")throw new TypeError("DingTalk API is required");if(!vt(o)||!vt(i))throw new TypeError("DingTalk app credentials are required");if(!e||!a)throw new TypeError("Harness client and state store are required");this.#e=r,this.#A=o.trim(),this.#t=i.trim(),this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#h=new Ca({label:"DingTalk",logger:t}),this.#s=s,this.#I=g,this.#a=c,PAe(this.#n),this.#N()}get status(){return this.#N(),structuredClone(this.#n)}accept(r){if(this.#a?.aborted)return Promise.resolve();let o=vt(r?.msgId),i=OAe(r);if(!o||!i||this.#g.hasSeen(o)||this.#p.has(o))return Promise.resolve();this.#p.add(o);let e;try{e=TAe(r,i)}catch{return this.#p.delete(o),ri(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),Promise.resolve()}let a=null;try{a=lg(r.sessionWebhook)}catch{}a&&String(r.conversationType)!=="2"&&Va(this.#g,{sessionWebhook:a});let A=this.#o.get(e),t=this.#h.claimReply({key:e,actor:i,messageId:o,text:a&&r?.msgtype==="text"?vt(r?.text?.content)??"":"",addressed:String(r?.conversationType)!=="2"||r?.isInAtList===!0,hasPendingQuestion:!!A,questionCompletion:A?.submitting||A?.claimedReplyMessageId?A.queue:null,isQuestionPending:()=>this.#o.has(e),send:a?s=>this.#S(a,s):async()=>{}});if(t){let s;return s=t.process(async()=>this.#g.hasSeen(o)?!1:(await this.#g.markSeen(o),ri(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),a||(ri(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError="\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002"),!0)).catch(g=>{this.#a?.aborted||(this.#n.lastError="\u9489\u9489\u5BA1\u6279\u5904\u7406\u5931\u8D25\u3002",this.#E.error?.("[dsh-dingtalk] failed to process an approval reply",g))}).finally(()=>{this.#p.delete(o),this.#l.delete(s)}),this.#l.add(s),s}if(A&&A.actor!==i)return this.#C(r,o,i,e);if(A?.submitting||A?.claimedReplyMessageId)return this.#C(r,o,i,e);if(A){vAe(r,A,i)&&(A.claimedReplyMessageId=o);let g=(A.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,o,i,e,A)).finally(()=>{this.#p.delete(o),A.claimedReplyMessageId===o&&(A.claimedReplyMessageId=null),A.queue===g&&(A.queue=null)});return A.queue=g,g}return this.#C(r,o,i,e)}#C(r,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#i.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#d(r,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&this.#p.delete(o),this.#i.get(e)===s&&this.#i.delete(e)});return this.#i.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#i.values(),...[...this.#o.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#l])}async#d(r,o,i,e,{alreadyRecorded:a=!1}={}){if(this.#a?.throwIfAborted(),!a){if(this.#g.hasSeen(o))return;await this.#g.markSeen(o),ri(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString()}if(String(r.conversationType)==="2"&&r.isInAtList!==!0){ri(this.#n,"messagesIgnored");return}let A;try{A=lg(r.sessionWebhook)}catch{ri(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError="\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002";return}let t=NAe(r,{api:this.#e,clientId:this.#A,clientSecret:this.#t}),s=t.content,g=Mr(t),c=String(r?.msgtype).toLowerCase()==="text",l=null,p=!1;try{if(!s&&!g){await this.#S(A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002");return}let B=s.toLowerCase();if(c&&!g&&B==="/help"){await this.#S(A,SAe);return}if(c&&!g&&B==="/status"){await this.#r.ensureRunning({signal:this.#a}),await this.#S(A,"\u9489\u9489\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002");return}if(c&&!g&&B==="/new"){await this.#g.clearSession(e),await this.#S(A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002");return}let Q=c&&!g?await ti(s,this.#r,e):null;if(Q){for(let k of Q.messages??[Q.message])await this.#S(A,k);return}let f=c&&!g?await Ai(s,this.#r,this.#g,e,{signal:this.#a}):null;if(f){await this.#S(A,f.message);return}let y=g?await Wa(t,{signal:this.#a}):void 0;typeof this.#e.createAiCard=="function"&&typeof this.#e.updateAiCard=="function"&&typeof this.#e.finishAiCard=="function"&&(l=KP({api:this.#e,clientId:this.#A,clientSecret:this.#t,target:RAe(r,i),signal:this.#a,logger:this.#E}),p=await l.start(yAe));let{answer:m}=await ha({harness:this.#r,state:this.#g,key:e,...g?{content:y}:{text:s},createOptions:{signal:this.#a},existsOptions:{signal:this.#a},askOptions:{timeoutMs:this.#s,signal:this.#a,onUpdate:p?k=>l.push(kAe(k)):void 0,onInteraction:k=>this.#u(k,{key:e,actor:i,sessionWebhook:A,requiresMention:String(r.conversationType)==="2"}),onInteractionResolved:k=>this.#B(k)}});p&&await l.finish(m)||await this.#S(A,m),ri(this.#n,"messagesReplied"),this.#n.lastReplyAt=new Date().toISOString(),this.#n.lastError=null}catch(B){if(this.#a?.aborted)return;this.#n.lastError="\u9489\u9489\u6D88\u606F\u5904\u7406\u5931\u8D25\u3002",this.#E.error?.("[dsh-dingtalk] failed to process an inbound message",DAe(B));try{let Q=wAe(B)??mAe;p&&await l.finish(Q)||await this.#S(A,Q)}catch{this.#E.error?.("[dsh-dingtalk] failed to send the safe error reply")}}finally{await this.#w(e),await this.#h.closeRoute(e)}}async#Q(r,o,i,e,a){this.#a?.throwIfAborted();let A=this.#o.get(e),t=a.claimedReplyMessageId===o;if(!A||A!==a||A.submitting)return t&&(!A||A!==a)?this.#f(r,o):this.#C(r,o,i,e,{releaseMessageId:!1});if(this.#g.hasSeen(o))return;if(await this.#g.markSeen(o),ri(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),String(r.conversationType)==="2"&&r.isInAtList!==!0){ri(this.#n,"messagesIgnored");return}let s;try{s=lg(r.sessionWebhook)}catch{ri(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError="\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002";return}let g=r?.msgtype==="text"?vt(r?.text?.content):null;if(!g){try{await this.#S(s,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")}catch{this.#E.error?.("[dsh-dingtalk] failed to reject a non-text interaction reply")}return}let c=this.#o.get(e);if(!c||c!==a||c.submitting){if(t&&(!c||c!==a)){try{await this.#S(s,gD)}catch{this.#E.error?.("[dsh-dingtalk] failed to send an expired interaction notice")}return}return this.#C(r,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.sessionWebhook=s,c.needsPresentation){try{await this.#y(c)}catch{this.#n.lastError="\u9489\u9489\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#E.error?.("[dsh-dingtalk] failed to retry an interaction question"),c.interaction.reconnect?.()}return}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,g)),c.index+=1,c.indexthis.#S(e,c)})||r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#E.warn?.("[dsh-dingtalk] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.respond({ok:!1,error:{code:"cancelled",message:"DingTalk safely cancelled an interaction left by an earlier client.",details:{}}});try{await this.#S(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")}catch{this.#E.error?.("[dsh-dingtalk] failed to send an interaction recovery notice")}return}let s=this.#o.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#y(s);return}if(this.#c.has(t))return;if(s){this.#E.warn?.("[dsh-dingtalk] cancelled a second pending Harness question"),await r.respond({ok:!1,error:{code:"cancelled",message:"DingTalk is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,sessionWebhook:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0};this.#o.set(o,g),this.#c.set(g.interactionId,o),await this.#y(g)}async#B(r){if(await this.#h.handleResolved(r))return;let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#c.get(o);i&&this.#m(i,o)}async#y(r){let o=r.questions[r.index];o&&(await this.#S(r.sessionWebhook,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})),r.needsPresentation=!1)}async#f(r,o){if(this.#g.hasSeen(o))return;await this.#g.markSeen(o),ri(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString();let i;try{i=lg(r.sessionWebhook)}catch{ri(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString();return}try{await this.#S(i,gD)}catch{this.#E.error?.("[dsh-dingtalk] failed to send an expired interaction notice")}}#D(r,o){let i=this.#o.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#o.delete(r),this.#c.delete(i.interactionId),i)}#m(r,o){return this.#D(r,o)!==null}async#w(r){let o=this.#D(r);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The DingTalk interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#E.warn?.("[dsh-dingtalk] failed to cancel a pending Harness interaction")}}#N(){typeof this.#g.pendingSenders=="function"&&(this.#n.pendingSenders=this.#g.pendingSenders())}async#S(r,o){for(let i of LP(o,this.#I))this.#a?.throwIfAborted(),await this.#e.sendText({clientId:this.#A,clientSecret:this.#t,sessionWebhook:r,text:i,signal:this.#a})}};function Dd(n){return typeof n=="string"&&n.trim()?n.trim():null}function rG(n){let r=Array.isArray(n?.approvedSenders)?n.approvedSenders:n?.approvedSenders instanceof Set?[...n.approvedSenders]:[];return new Set(r.map(o=>Dd(typeof o=="string"?o:o?.staffId)).filter(Boolean))}function GAe(n){return rG(n).size}function aG(n){return n?.connected===!0||n?.socket?.readyState===1}function FAe(n,r){return new Promise((o,i)=>{if(r.aborted){i(r.reason);return}let e=()=>i(r.reason);r.addEventListener("abort",e,{once:!0}),Promise.resolve(n).then(a=>{r.removeEventListener("abort",e),o(a)},a=>{r.removeEventListener("abort",e),i(a)})})}async function LAe(n,r,o){for(;;){if(o?.throwIfAborted(),aG(n))return;await new Promise((i,e)=>{let a=setTimeout(()=>{o?.removeEventListener("abort",A),i()},r),A=()=>{clearTimeout(a),e(o.reason??new DOMException("Aborted","AbortError"))};o?.addEventListener("abort",A,{once:!0})})}}async function UAe(n,r,o,i){let e=AbortSignal.timeout(r),a=AbortSignal.any([i,e]),A=!1,t=Promise.resolve().then(()=>n.connect()).finally(()=>{A=!0});try{await FAe(t,a),await LAe(n,o,a)}catch(s){throw a.aborted?(A||t.then(()=>n.disconnect()).catch(()=>{}),i.aborted?i.reason:new Error(`DingTalk Stream handshake timed out after ${r}ms`)):s}}async function HAe({clientId:n,clientSecret:r}){let{DWClient:o,TOPIC_ROBOT:i}=await import("dingtalk-stream");return{client:new o({clientId:n,clientSecret:r,endpoint:"https://api.dingtalk.com",autoReconnect:!1,keepAlive:!0,debug:!1}),topic:i}}function KAe({pendingSenders:n=[],approvedSenders:r=0}={}){return{startedAt:null,ready:!1,dingtalkStreamState:"idle",harnessReachable:!1,lastConnectedAt:null,lastCheckedAt:null,lastCallbackAt:null,authorizationMode:"sender-staff-id-approval",approvedSenderCount:r,...cD({pendingSenders:n})}}var NE=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i;#o;#c=null;#l=null;#p=null;#h=null;#C=null;#d=null;#Q=new Set;constructor({config:r,clientSecret:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,maxMessageChars:t=4e3,connectTimeoutMs:s=15e3,connectPollIntervalMs:g=25,api:c=UP(),streamFactory:l=HAe}){if(!r||!Dd(r.clientId)||!Dd(o))throw new TypeError("DingtalkRuntime requires app credentials");if(!i||!e)throw new TypeError("DingtalkRuntime requires Harness and state");if(typeof l!="function")throw new TypeError("streamFactory must be a function");this.#e=r,this.#A=o.trim(),this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#a=c,this.#i=l,this.#o=KAe({pendingSenders:this.#B(),approvedSenders:GAe(r)})}get status(){if(this.#l){let r=this.#l.status;Object.assign(this.#o,r)}else this.#o.pendingSenders=this.#B();return structuredClone(this.#o)}pendingSender(r){return typeof this.#r.pendingSender=="function"?this.#r.pendingSender(r):null}pendingSenders(){return this.#B()}async start(){return this.#c&&this.#o.ready?this.status:this.#h?this.#h:(this.#h=this.#u().finally(()=>{this.#h=null}),this.#h)}async#u(){await this.stop();let r=new AbortController;this.#d=r;let{signal:o}=r;this.#o.startedAt=new Date().toISOString(),this.#o.dingtalkStreamState="connecting",this.#o.lastError=null;try{if(await this.#t.ensureRunning({signal:o}),this.#o.harnessReachable=!0,typeof this.#r.removePendingSenderByStaffId=="function"){for(let A of rG(this.#e))await this.#r.removePendingSenderByStaffId(A);this.#o.pendingSenders=this.#B()}this.#l=new Sd({api:this.#a,clientId:this.#e.clientId,clientSecret:this.#A,approvedSenders:this.#e.approvedSenders,harness:this.#t,state:this.#r,status:this.#o,logger:this.#g,replyTimeoutMs:this.#n,maxMessageChars:this.#E,signal:o});let i=await this.#i({clientId:this.#e.clientId,clientSecret:this.#A});if(o.throwIfAborted(),this.#c=i?.client??i,this.#p=i?.topic??i?.TOPIC_ROBOT??"/v1.0/im/bot/messages/get",!this.#c||typeof this.#c.registerCallbackListener!="function"||typeof this.#c.connect!="function"||typeof this.#c.disconnect!="function"||typeof this.#c.socketCallBackResponse!="function")throw new TypeError("streamFactory returned an invalid DingTalk Stream client");let e=this.#c,a=this.#l;return e.registerCallbackListener(this.#p,A=>{if(this.#c!==e||this.#l!==a)return;let t=Dd(A?.headers?.messageId);if(t)try{e.socketCallBackResponse(t,{success:!0})}catch{this.#g.warn?.("[dsh-dingtalk] unable to acknowledge an inbound callback")}let s=Promise.resolve().then(async()=>{if(this.#l!==a)return;let g;try{g=typeof A?.data=="string"?JSON.parse(A.data):A?.data}catch{this.#o.lastError="\u9489\u9489\u6D88\u606F\u683C\u5F0F\u65E0\u6548\u3002",this.#g.warn?.("[dsh-dingtalk] ignored an invalid callback payload");return}!g||typeof g!="object"||(this.#o.lastCallbackAt=Date.now(),await a.accept(g))}).catch(()=>{o.aborted||this.#l!==a||(this.#o.lastError="\u9489\u9489\u6D88\u606F\u5904\u7406\u5931\u8D25\u3002",this.#g.error?.("[dsh-dingtalk] callback processing failed"))}).finally(()=>this.#Q.delete(s));this.#Q.add(s)}),await UAe(e,this.#s,this.#I,o),this.#o.ready=!0,this.#o.dingtalkStreamState="connected",this.#o.lastConnectedAt=Date.now(),this.#o.lastCheckedAt=Date.now(),this.#o.lastError=null,this.#C=setInterval(()=>{let A=aG(e);this.#o.ready=A,this.#o.dingtalkStreamState=A?"connected":"reconnecting",this.#o.lastCheckedAt=Date.now(),A&&(this.#o.lastError=null)},1e3),this.#C.unref?.(),this.status}catch(i){let e=o.aborted;throw this.#o.ready=!1,this.#o.dingtalkStreamState=e?"idle":"failed",this.#o.lastError=e?null:i?.message??String(i),await this.stop({preserveError:!e}),i}}async stop({preserveError:r=!1}={}){let o=r?this.#o.lastError:null,i=this.#d;this.#d=null,i?.abort(new DOMException("DingTalk runtime stopped","AbortError")),this.#C&&clearInterval(this.#C),this.#C=null,this.#o.ready=!1;let e=this.#c;if(this.#c=null,this.#p=null,e)try{await e.disconnect()}catch{this.#g.warn?.("[dsh-dingtalk] DingTalk Stream disconnect failed")}return await Promise.allSettled([...this.#Q]),this.#Q.clear(),this.#l&&await this.#l.waitForIdle(),this.#l=null,this.#o.dingtalkStreamState=r?"failed":"idle",this.#o.lastError=o,this.status}async sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:"\u9489\u9489\u673A\u5668\u4EBA",send:async({sessionWebhook:o},i)=>{if(!this.#o.ready||!this.#d)throw new Error("DingTalk runtime is not connected");await this.#a.sendText({clientId:this.#e.clientId,clientSecret:this.#A,sessionWebhook:o,text:i,signal:this.#d.signal})}})}#B(){return typeof this.#r.pendingSenders=="function"?this.#r.pendingSenders():[]}};import{spawn as WAe}from"node:child_process";import{randomUUID as oG}from"node:crypto";import{isAbsolute as ZAe}from"node:path";import{isAbsolute as YAe}from"node:path";var xAe=256,jAe=/[\p{White_Space}\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u,JAe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;function TE(n,r){let o=new Error(r);return o.code=n,o}function qAe(n){if(typeof n!="string"||!n||n.length>xAe||jAe.test(n))throw TE("session-id-invalid","A non-empty, safe session id is required");return n}function VAe(n,r){if(!Array.isArray(r?.items)||!Array.isArray(r?.archivedSessionIds)||r.archivedSessionIds.some(i=>typeof i!="string"||!i))throw new Error("Harness returned an invalid response for workspace.list");let o=[];for(let i of r.items){if(typeof i?.workspaceId!="string"||!i.workspaceId||typeof i.path!="string"||!YAe(i.path)||!Array.isArray(i.sessionIds)||i.sessionIds.some(e=>typeof e!="string"||!e))throw new Error("Harness returned an invalid response for workspace.list");for(let e of i.sessionIds)e===n&&o.push(i)}if(o.length===0)throw TE("session-not-registered","The session is not registered to a Harness workspace");if(o.length!==1)throw TE("session-workspace-ambiguous","The session is registered to more than one Harness workspace");if(JAe.test(o[0].path))throw new Error("Harness returned an unsafe workspace path for the session");return{workspace:o[0],archived:r.archivedSessionIds.includes(n)}}function zAe(n,r){if(!Array.isArray(r?.items)||r.items.some(a=>typeof a?.sessionId!="string"||!a.sessionId))throw new Error("Harness returned an invalid response for session.list");let o=r.items.filter(a=>a.sessionId===n);if(o.length===0)throw TE("session-summary-unavailable","The session is no longer available from Harness");if(o.length!==1)throw new Error("Harness returned duplicate session summaries for session.list");let[i]=o;if(i.origin==="subagent")throw TE("session-subagent-unsupported","Subagent sessions cannot be adopted as a bot conversation");if(i.origin!==void 0)throw new Error("Harness returned an invalid session origin for session.list");let e=i.projections?.values?.title;if(e!=null&&typeof e!="string")throw new Error("Harness returned an invalid session title for session.list");return{title:typeof e=="string"?e:null}}async function iG(n,r,o={},i=3e4){let e=qAe(r);await n.ensureRunning(o);let a=await n.rpc("workspace.list",{},i,o),{workspace:A,archived:t}=VAe(e,a),s=zAe(e,await n.rpc("session.list",{},i,o)),g=await n.rpc("session.create",{workspaceId:A.workspaceId,sessionId:e},i,o);if(!g||g.sessionId!==e)throw new Error("Harness returned an invalid response for session.create");return{sessionId:e,workspace:A.path,title:s.title,archived:t}}var nG=new Map;function XAe(n){let r=nG.get(n);return r||(r={ownerships:new Map,claims:new Map,nextOrder:0},nG.set(n,r)),r}function $Ae(n){return Array.isArray(n?.items)?n.items.flatMap(r=>typeof r?.path=="string"&&ZAe(r.path)?[r.path]:[]):[]}function ete(n,r){if(!Array.isArray(r?.items)||!Array.isArray(r?.archivedSessionIds))throw new Error("Harness returned an invalid response for workspace.list");let o=r.items.find(i=>i?.path===n);if(!o)return null;if(!Array.isArray(o.sessionIds)||o.sessionIds.some(i=>typeof i!="string"))throw new Error("Harness returned invalid session IDs for workspace.list");return o}function Ate(n){if(typeof n=="number"&&Number.isFinite(n))return n<1e12?n*1e3:n;if(typeof n=="string"&&n){let r=Date.parse(n);if(!Number.isNaN(r))return r}return null}function tte(n){if(!n||typeof n!="object")return null;let r=[n?.header?.lastActivityAt,n?.header?.updatedAt,n?.header?.createdAt,n?.projections?.values?.lastActivityAt,n?.projections?.values?.updatedAt,n?.projections?.values?.createdAt,n?.lastActivityAt,n?.updatedAt,n?.createdAt];for(let o of r){let i=Ate(o);if(i!==null)return i}return null}function rte(n,r,o){if(!Array.isArray(o?.items))throw new Error("Harness returned an invalid response for session.list");let i=new Set(r),e=new Map(o.items.flatMap(a=>typeof a?.sessionId=="string"?[[a.sessionId,a]]:[]));return{workspace:n.path,sessions:n.sessionIds.map(a=>{let A=e.get(a),t=A?.projections?.values?.title,s={sessionId:a,title:typeof t=="string"?t:null,archived:i.has(a),blank:A?.blank===!0,origin:A?.origin==="subagent"?"subagent":null,summaryAvailable:A!==void 0},g=tte(A);return g!==null&&(s.time=g),s})}}function wd(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(()=>{r?.removeEventListener("abort",a),o()},n),a=()=>{clearTimeout(e),i(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",a,{once:!0})})}function ate(n){return(n?.data?.message?.content??[]).filter(r=>r.type==="text"&&typeof r.text=="string").map(r=>r.text).join(` `).trim()}function ite(n,r){let o=[...r].map(i=>i?.event??i).filter(Boolean).sort((i,e)=>(i.seq??-1)-(e.seq??-1));for(let i of o){let e=i.seq??-1;if(e<=n.lastSeq)continue;if(n.lastSeq=e,i.type==="turn/start"){let A=i.data?.turn??null;n.active&&A!==n.turn&&(n.active=!1),n.turn!==null&&A!==n.turn&&(n.completed=!0),n.openTurn=A;continue}if(i.type==="user/message"&&i.data?.source?.rpcId===n.promptRpcId){n.active=!0,n.started=!0,n.completed=!1,n.turn=i.data?.turn??n.openTurn;continue}if(i.type==="turn/end"&&i.data?.turn===n.turn){n.active=!1,n.completed=!0;continue}let a=null;if(i.type==="tool/call"&&n.active&&i.data?.turn===n.turn&&typeof i.data?.callId=="string"&&i.data.callId)a={callId:i.data.callId,name:i.data?.name,arguments:i.data?.arguments};else if(i.type==="tool/code-dispatch-start"&&n.active&&typeof i.data?.subCallId=="string"&&i.data.subCallId){let A;try{A=JSON.stringify(i.data?.arguments)}catch{A=void 0}a={callId:i.data.subCallId,name:i.data?.name,arguments:A}}a&&n.toolCalls.set(a.callId,Object.freeze(a))}}var Vc=class{#e;#A;#t=null;#r=null;#g=new Map;#n="";#E=!1;#s=null;constructor({promptRpcId:r,afterSeq:o=-1}){this.#e=r,this.#A=o}get finished(){return this.#E}get answer(){return this.#n.trim()}get reason(){return this.#s}get tracking(){return this.#r!==null&&!this.#E}get turn(){return this.#r}consume(r){let o=null,i=[...r].map(e=>e?.event??e).filter(Boolean).sort((e,a)=>(e.seq??-1)-(a.seq??-1));for(let e of i){let a=e.seq??-1;if(!(a<=this.#A)){if(this.#A=a,e.type==="turn/start"&&(this.#t=e.data?.turn??null),e.type==="user/message"&&e.data?.source?.rpcId===this.#e){this.#r=this.#t;continue}if(this.#r!==null){if(e.type==="turn/end"){if(e.data?.turn!==this.#r)continue;this.#E=!0,this.#s=e.data?.reason??null,this.#t=null;continue}if(e.data?.turn===this.#r){if(e.type==="assistant/chunk"&&e.data?.chunk?.type==="text-delta"){let A=e.data?.step??0,t=e.data.chunk.index??0,s=`${A}:${t}`;this.#g.set(s,(this.#g.get(s)??"")+e.data.chunk.text);let g=`${A}:`,c=[...this.#g.entries()].filter(([l])=>l.startsWith(g)).sort(([l],[p])=>Number(l.split(":")[1])-Number(p.split(":")[1])).map(([,l])=>l).join(` -`).trim();c&&c!==this.#n&&(this.#n=c,o={type:"text",text:c});continue}if(e.type==="assistant/message"){let A=ate(e);A&&A!==this.#n&&(this.#n=A,o={type:"text",text:A});continue}e.type==="tool/call"?o={type:"tool",name:e.data?.name??"\u5DE5\u5177"}:e.type==="tool/result"&&(o={type:"status",text:"\u6B63\u5728\u6574\u7406\u7ED3\u679C\u2026"})}}}}return o}},As=class extends Error{constructor(r,o){super(`${r}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=r,this.code=o?.code??"internal",this.details=o?.details??{}}},zc=class extends Error{constructor(r,o){super(o),this.name="HarnessInteractionError",this.code=r}},qt=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i;#o=null;#c;#l;#p;constructor({baseUrl:r,workspace:o,agentPreset:i="standard",autostart:e=!1,dshBin:a="dsh",fetchImpl:A=fetch,createWebSocket:t=p=>new WebSocket(p),interactionReconnectDelayMs:s=500,rpcIdPrefix:g="im",logPrefix:c="dsh-im",commandExecutor:l}){if(typeof t!="function")throw new TypeError("createWebSocket must be a function");if(!Number.isFinite(s)||s<0)throw new TypeError("interactionReconnectDelayMs must be a non-negative number");if(typeof g!="string"||!g.trim())throw new TypeError("rpcIdPrefix must be a non-empty string");if(typeof c!="string"||!c.trim())throw new TypeError("logPrefix must be a non-empty string");if(l!==void 0&&typeof l!="function")throw new TypeError("commandExecutor must be a function");this.#e=new URL(r),this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g.trim(),this.#a=c.trim(),this.#i=l,this.#c=XAe(this.#e.origin),this.#l=this.#c.ownerships,this.#p=this.#c.claims}async rpc(r,o={},i=3e4,e={}){let a=e.rpcId??`${this.#I}-${oG()}`,A=AbortSignal.timeout(i),t=e.signal?AbortSignal.any([e.signal,A]):A,s=await this.#n(new URL(`/api/${r}`,this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:a,method:r,payload:o}),signal:t});if(!s.ok)throw new Error(`Harness transport ${r} failed: HTTP ${s.status}`);let g=await s.json();if(g?.type!=="server-response"||g?.rpcId!==a)throw new Error(`Harness returned an invalid response for ${r}`);if(!g.result?.ok)throw new As(r,g.result?.error);return g.result.value}async health(r={}){return await this.rpc("host.describe",{},5e3,r),!0}async ensureRunning(r={}){try{return await this.health(r)}catch(e){if(!this.#r)throw e}if(!this.#o||this.#o.exitCode!==null){let e=this.#e.port||(this.#e.protocol==="https:"?"443":"80");this.#o=WAe(this.#g,["web","--host",this.#e.hostname,"--port",e],{cwd:this.#A,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#o.on("error",a=>{console.error(`[${this.#a}] failed to start Harness:`,a.message)})}let o=Date.now()+6e4,i;for(;Date.now()t.path===o);return a?a.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(r={}){await this.ensureRunning(r);let o=await this.workspaceId(r);return(await this.rpc("session.create",{workspaceId:o,agentPreset:this.#t},3e4,r)).sessionId}async executeCommand(r,o,i={}){if(typeof r!="string"||!r)throw new TypeError("sessionId is required");if(typeof o!="string"||!o)throw new TypeError("command line is required");if(!this.#i){let e=new Error("Harness command execution is unavailable");throw e.code="commands-unavailable",e}try{return await this.#i(r,o,i)}catch(e){throw e?.failure&&typeof e.failure=="object"?new As("commands.execute",e.failure):e}}async sessionExists(r,o={}){try{return await this.rpc("session.history",{sessionId:r,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof As&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(r,o,i={}){if(typeof r!="string"||!r)throw new TypeError("rpcId is required");if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new TypeError("A Harness RPC result is required");let e=AbortSignal.timeout(i.timeoutMs??3e4),a=i.signal?AbortSignal.any([i.signal,e]):e,A=await this.#n(new URL("/api/respond",this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-response",rpcId:r,result:o}),signal:a});if(!A.ok)throw new Error(`Harness transport respond failed: HTTP ${A.status}`);let t=await A.json();if(t?.accepted===!0)return t;if(t?.accepted!==!1||t.reason!=="bad-response"&&t.reason!=="not-pending")throw new Error("Harness returned an invalid interaction response receipt");let s=t.reason;throw new zc(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}={}){if(typeof r!="string"||!r)throw new TypeError("sessionId is required");if(!o||typeof o.addEventListener!="function")throw new TypeError("watchInteractions requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onInteraction must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("onResolved must be a function");if(a!==void 0&&typeof a!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#B(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A})}catch(t){if(o.aborted)return;console.warn(`[${this.#a}] Harness interaction stream disconnected:`,t.message)}if(o.aborted)return;try{await wd(this.#s,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#h(r,o){let i=this.#l.get(r)??new Set;o.order=this.#c.nextOrder,this.#c.nextOrder+=1,i.add(o),this.#l.set(r,i)}#C(r,o){let i=this.#l.get(r);i?.delete(o),i?.size===0&&this.#l.delete(r);for(let[e,a]of this.#p)a.ownership===o&&this.#p.delete(e)}#d(r,o){for(let i of this.#l.get(r)??[])ite(i,o)}async#Q(r,o){let i=await this.rpc("session.history",{sessionId:r,maxMessages:50},3e4,{signal:o});this.#d(r,i.events??[])}#u(r,o,i){let e=this.#p.get(o);if(e&&this.#l.get(r)?.has(e.ownership))return e;let a=[...this.#l.get(r)??[]],A=a.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};let t=a.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return t?{ownership:t,recovered:!0}:null}async ask(r,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,a=i.signal,A=typeof i.onUpdate=="function"?i.onUpdate:null,t=typeof i.onInteraction=="function"?i.onInteraction:void 0,s=typeof i.onInteractionResolved=="function"?i.onInteractionResolved:void 0;await this.ensureRunning({signal:a});let g=await this.rpc("session.history",{sessionId:r,maxMessages:1},3e4,{signal:a}),c=Math.max(-1,...(g.events??[]).map(({event:m})=>m.seq??-1)),l=`${this.#I}-${oG()}`,p=new Vc({promptRpcId:l,afterSeq:c}),B=t||s?new AbortController:null,Q=B?a?AbortSignal.any([a,B.signal]):B.signal:null,f=B?{promptRpcId:l,active:!1,started:!1,completed:!1,turn:null,openTurn:null,lastSeq:c,reconnect:null,order:-1,toolCalls:new Map}:null,y=null;f&&this.#h(r,f);try{if(Q){let k,G=new Promise(K=>{k=K});y=this.watchInteractions(r,{signal:Q,onInteraction:t,onResolved:s,onOpen:k,ownership:f}),y.catch(()=>{}),await Promise.race([G,wd(3e4,Q).then(()=>{throw new Error("Harness interaction stream did not open within 30 seconds")})])}let m=typeof o=="string"?[{type:"text",text:o}]:o;if(!Array.isArray(m)||m.length===0)throw new TypeError("Harness prompt content is required");await this.rpc("session.prompt",{sessionId:r,mode:"queue",content:m,clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:l,signal:a});let R=Date.now()+e;for(;Date.now(){}),f&&this.#C(r,f)}}#B(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}){let t=new URL("/api/events.mux",this.#e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",new Promise((s,g)=>{let c;try{c=this.#E(t.toString())}catch(F){g(F);return}let l=!1,p=!1,B=null,Q=Promise.resolve(),f=A==null,y=[],m=F=>{p||(p=!0,c.removeEventListener("open",k),c.removeEventListener("message",x),c.removeEventListener("close",H),c.removeEventListener("error",q),o.removeEventListener("abort",j),A?.reconnect===R&&(A.reconnect=null),Q.then(()=>{let T=F??B;T?g(T):s()},g))},R=()=>{try{(c.readyState===0||c.readyState===1)&&c.close()}catch{}},k=()=>{l=!0,A&&(A.reconnect=R);try{a?.()}catch(F){console.warn(`[${this.#a}] ignored an interaction open callback failure:`,F.message)}A&&this.#Q(r,o).then(()=>{if(!p){f=!0;for(let F of y.splice(0))K(F)}}).catch(F=>{B??=F,R(),m(F)})},G=(F,T)=>{F&&(Q=Q.then(()=>F(T)).catch(V=>{B??=V,R(),m(B)}))},K=F=>{let T=F.payload;if(A&&T.type==="session/event"){this.#d(r,[T.event]);return}if(T.type==="question/requested"||T.type==="approval/requested"){let V=T.type==="question/requested"?"question":"approval",U=V==="question"?F.rpcId:T.approvalId,b=`${V}:${U}`;if(A){let X=this.#u(r,b,V);if(X?.ownership!==A)return;this.#p.set(b,X)}let L=V==="approval"&&A&&typeof T.callId=="string"?this.#p.get(b)?.ownership.toolCalls.get(T.callId):void 0;G(i,Object.freeze({kind:V,interactionId:U,rpcId:F.rpcId,sessionId:r,payload:T,recovered:A?this.#p.get(b)?.recovered===!0:!1,...L?{toolCall:L}:{},reconnect:R,respond:(X,pe={})=>this.respondInteraction(F.rpcId,X,{...pe,signal:pe.signal??o})}));return}if(T.type==="question/resolved"||T.type==="approval/resolved"){let V=T.type==="question/resolved"?"question":"approval",U=V==="question"?T.questionRpcId:T.approvalId,b=`${V}:${U}`;if(A){if(this.#p.get(b)?.ownership!==A)return;this.#p.delete(b)}G(e,Object.freeze({kind:V,interactionId:U,sessionId:r,outcome:T.outcome,payload:T}))}},x=F=>{try{if(typeof F.data!="string")throw new Error("binary WebSocket frame");let T=JSON.parse(F.data),V=T?.payload;if(T?.type!=="server-request"||typeof T.rpcId!="string"||!V||typeof V!="object"||T.method!==V.type)throw new Error("invalid server-request envelope");if(V.sessionId!==r)return;f?K(T):y.push(T)}catch(T){console.warn(`[${this.#a}] ignored a malformed Harness interaction frame:`,T.message)}},H=()=>m(l?null:new Error("Harness interaction WebSocket closed before opening")),q=()=>{m(new Error(l?"Harness interaction WebSocket failed":"Harness interaction WebSocket failed before opening")),R()},j=()=>{R(),m()};c.addEventListener("open",k),c.addEventListener("message",x),c.addEventListener("close",H,{once:!0}),c.addEventListener("error",q,{once:!0}),o.addEventListener("abort",j,{once:!0}),o.aborted&&j()})}stopManagedProcess(){this.#o?.exitCode===null&&this.#o.kill("SIGTERM")}};var Od=class extends qt{constructor(r){super({...r,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{randomUUID as ote}from"node:crypto";import{mkdir as nte,readFile as ste,rename as gte,unlink as cte,writeFile as Ite}from"node:fs/promises";import{dirname as lte}from"node:path";var Md=Object.freeze({version:1,sessions:{},seenMessageIds:[],pendingSenders:{}});function Pt(n){return typeof n=="string"&&n.trim()?n.trim():null}function sG(n){return(Pt(n)??"\u9489\u9489\u7528\u6237").slice(0,100)}function Ete(n,r){if(!n||typeof n!="object")return null;let o=Pt(n.requestId)??Pt(r),i=Pt(n.staffId),e=Pt(n.requestedAt)??Pt(n.lastSeenAt),a=Pt(n.lastSeenAt)??e;return!o||!i||!e||!a?null:{requestId:o,staffId:i,displayName:sG(n.displayName??n.nick),requestedAt:e,lastSeenAt:a}}function pte(n){if(!n||typeof n!="object")return structuredClone(Md);let r={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,a]of Object.entries(n.sessions)){let A=Pt(e),t=Pt(a);A&&t&&(r[A]=t)}let o={},i=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,a]of i){let A=Ete(a,e);if(!A)continue;let t=Object.values(o).find(s=>s.staffId===A.staffId);(!t||t.lastSeenAtnew Date().toISOString()}={}){if(!Pt(r))throw new TypeError("state path is required");if(typeof o!="function"||typeof i!="function")throw new TypeError("idFactory and now must be functions");this.#e=r,this.#r=o,this.#g=i}async load(){try{this.#A=pte(JSON.parse(await ste(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(Md),await this.#n()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){let i=Pt(r),e=Pt(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[i]=e,await this.#n()}async clearSession(r){let o=Pt(r);!o||!(o in this.#A.sessions)||(delete this.#A.sessions[o],await this.#n())}async clearSessions(){this.#A.sessions={},await this.#n()}hasSeen(r){let o=Pt(r);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(r){let o=Pt(r);if(!o)throw new TypeError("messageId is required");this.hasSeen(o)||(this.#A.seenMessageIds.push(o),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#n())}pendingSenders(){return Object.values(this.#A.pendingSenders).sort((r,o)=>r.requestedAt.localeCompare(o.requestedAt)).map(r=>structuredClone(r))}pendingSender(r){let o=Pt(r),i=o?this.#A.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(r,o,i){let e=r&&typeof r=="object"?r:{staffId:r,displayName:o,lastSeenAt:i},a=Pt(e.staffId);if(!a)throw new TypeError("staffId is required");let A=Pt(e.lastSeenAt)??Pt(e.requestedAt)??this.#g(),t=Object.values(this.#A.pendingSenders).find(g=>g.staffId===a),s={requestId:t?.requestId??`ding_sender_${this.#r()}`,staffId:a,displayName:sG(e.displayName??e.nick??o),requestedAt:t?.requestedAt??A,lastSeenAt:A};return this.#A.pendingSenders[s.requestId]=s,await this.#n(),structuredClone(s)}async removePendingSender(r){let o=Pt(r);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#n(),!0)}async removePendingSenderByStaffId(r){let o=Pt(r),i=o?Object.values(this.#A.pendingSenders).find(e=>e.staffId===o):null;return i?this.removePendingSender(i.requestId):!1}snapshot(){return structuredClone(this.#A)}async remove(){await this.#t;try{await cte(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(Md)}async#n(){let r=`${JSON.stringify(this.#A,null,2)} +`).trim();c&&c!==this.#n&&(this.#n=c,o={type:"text",text:c});continue}if(e.type==="assistant/message"){let A=ate(e);A&&A!==this.#n&&(this.#n=A,o={type:"text",text:A});continue}e.type==="tool/call"?o={type:"tool",name:e.data?.name??"\u5DE5\u5177"}:e.type==="tool/result"&&(o={type:"status",text:"\u6B63\u5728\u6574\u7406\u7ED3\u679C\u2026"})}}}}return o}},As=class extends Error{constructor(r,o){super(`${r}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=r,this.code=o?.code??"internal",this.details=o?.details??{}}},zc=class extends Error{constructor(r,o){super(o),this.name="HarnessInteractionError",this.code=r}},qt=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i;#o=null;#c;#l;#p;constructor({baseUrl:r,workspace:o,agentPreset:i,autostart:e=!1,dshBin:a="dsh",fetchImpl:A=fetch,createWebSocket:t=p=>new WebSocket(p),interactionReconnectDelayMs:s=500,rpcIdPrefix:g="im",logPrefix:c="dsh-im",commandExecutor:l}){if(typeof t!="function")throw new TypeError("createWebSocket must be a function");if(!Number.isFinite(s)||s<0)throw new TypeError("interactionReconnectDelayMs must be a non-negative number");if(typeof g!="string"||!g.trim())throw new TypeError("rpcIdPrefix must be a non-empty string");if(typeof c!="string"||!c.trim())throw new TypeError("logPrefix must be a non-empty string");if(l!==void 0&&typeof l!="function")throw new TypeError("commandExecutor must be a function");this.#e=new URL(r),this.#A=o,this.#t=i??void 0,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g.trim(),this.#a=c.trim(),this.#i=l,this.#c=XAe(this.#e.origin),this.#l=this.#c.ownerships,this.#p=this.#c.claims}async rpc(r,o={},i=3e4,e={}){let a=e.rpcId??`${this.#I}-${oG()}`,A=AbortSignal.timeout(i),t=e.signal?AbortSignal.any([e.signal,A]):A,s=await this.#n(new URL(`/api/${r}`,this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:a,method:r,payload:o}),signal:t});if(!s.ok)throw new Error(`Harness transport ${r} failed: HTTP ${s.status}`);let g=await s.json();if(g?.type!=="server-response"||g?.rpcId!==a)throw new Error(`Harness returned an invalid response for ${r}`);if(!g.result?.ok)throw new As(r,g.result?.error);return g.result.value}async health(r={}){return await this.rpc("host.describe",{},5e3,r),!0}async ensureRunning(r={}){try{return await this.health(r)}catch(e){if(!this.#r)throw e}if(!this.#o||this.#o.exitCode!==null){let e=this.#e.port||(this.#e.protocol==="https:"?"443":"80");this.#o=WAe(this.#g,["web","--host",this.#e.hostname,"--port",e],{cwd:this.#A,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#o.on("error",a=>{console.error(`[${this.#a}] failed to start Harness:`,a.message)})}let o=Date.now()+6e4,i;for(;Date.now()t.path===o);return a?a.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(r={}){await this.ensureRunning(r);let i={workspaceId:await this.workspaceId(r)};return this.#t!==void 0&&(i.agentPreset=this.#t),(await this.rpc("session.create",i,3e4,r)).sessionId}async executeCommand(r,o,i={}){if(typeof r!="string"||!r)throw new TypeError("sessionId is required");if(typeof o!="string"||!o)throw new TypeError("command line is required");if(!this.#i){let e=new Error("Harness command execution is unavailable");throw e.code="commands-unavailable",e}try{return await this.#i(r,o,i)}catch(e){throw e?.failure&&typeof e.failure=="object"?new As("commands.execute",e.failure):e}}async sessionExists(r,o={}){try{return await this.rpc("session.history",{sessionId:r,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof As&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(r,o,i={}){if(typeof r!="string"||!r)throw new TypeError("rpcId is required");if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new TypeError("A Harness RPC result is required");let e=AbortSignal.timeout(i.timeoutMs??3e4),a=i.signal?AbortSignal.any([i.signal,e]):e,A=await this.#n(new URL("/api/respond",this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-response",rpcId:r,result:o}),signal:a});if(!A.ok)throw new Error(`Harness transport respond failed: HTTP ${A.status}`);let t=await A.json();if(t?.accepted===!0)return t;if(t?.accepted!==!1||t.reason!=="bad-response"&&t.reason!=="not-pending")throw new Error("Harness returned an invalid interaction response receipt");let s=t.reason;throw new zc(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}={}){if(typeof r!="string"||!r)throw new TypeError("sessionId is required");if(!o||typeof o.addEventListener!="function")throw new TypeError("watchInteractions requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onInteraction must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("onResolved must be a function");if(a!==void 0&&typeof a!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#B(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A})}catch(t){if(o.aborted)return;console.warn(`[${this.#a}] Harness interaction stream disconnected:`,t.message)}if(o.aborted)return;try{await wd(this.#s,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#h(r,o){let i=this.#l.get(r)??new Set;o.order=this.#c.nextOrder,this.#c.nextOrder+=1,i.add(o),this.#l.set(r,i)}#C(r,o){let i=this.#l.get(r);i?.delete(o),i?.size===0&&this.#l.delete(r);for(let[e,a]of this.#p)a.ownership===o&&this.#p.delete(e)}#d(r,o){for(let i of this.#l.get(r)??[])ite(i,o)}async#Q(r,o){let i=await this.rpc("session.history",{sessionId:r,maxMessages:50},3e4,{signal:o});this.#d(r,i.events??[])}#u(r,o,i){let e=this.#p.get(o);if(e&&this.#l.get(r)?.has(e.ownership))return e;let a=[...this.#l.get(r)??[]],A=a.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};let t=a.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return t?{ownership:t,recovered:!0}:null}async ask(r,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,a=i.signal,A=typeof i.onUpdate=="function"?i.onUpdate:null,t=typeof i.onInteraction=="function"?i.onInteraction:void 0,s=typeof i.onInteractionResolved=="function"?i.onInteractionResolved:void 0;await this.ensureRunning({signal:a});let g=await this.rpc("session.history",{sessionId:r,maxMessages:1},3e4,{signal:a}),c=Math.max(-1,...(g.events??[]).map(({event:m})=>m.seq??-1)),l=`${this.#I}-${oG()}`,p=new Vc({promptRpcId:l,afterSeq:c}),B=t||s?new AbortController:null,Q=B?a?AbortSignal.any([a,B.signal]):B.signal:null,f=B?{promptRpcId:l,active:!1,started:!1,completed:!1,turn:null,openTurn:null,lastSeq:c,reconnect:null,order:-1,toolCalls:new Map}:null,y=null;f&&this.#h(r,f);try{if(Q){let k,G=new Promise(K=>{k=K});y=this.watchInteractions(r,{signal:Q,onInteraction:t,onResolved:s,onOpen:k,ownership:f}),y.catch(()=>{}),await Promise.race([G,wd(3e4,Q).then(()=>{throw new Error("Harness interaction stream did not open within 30 seconds")})])}let m=typeof o=="string"?[{type:"text",text:o}]:o;if(!Array.isArray(m)||m.length===0)throw new TypeError("Harness prompt content is required");await this.rpc("session.prompt",{sessionId:r,mode:"queue",content:m,clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:l,signal:a});let R=Date.now()+e;for(;Date.now(){}),f&&this.#C(r,f)}}#B(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}){let t=new URL("/api/events.mux",this.#e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",new Promise((s,g)=>{let c;try{c=this.#E(t.toString())}catch(F){g(F);return}let l=!1,p=!1,B=null,Q=Promise.resolve(),f=A==null,y=[],m=F=>{p||(p=!0,c.removeEventListener("open",k),c.removeEventListener("message",x),c.removeEventListener("close",H),c.removeEventListener("error",q),o.removeEventListener("abort",j),A?.reconnect===R&&(A.reconnect=null),Q.then(()=>{let T=F??B;T?g(T):s()},g))},R=()=>{try{(c.readyState===0||c.readyState===1)&&c.close()}catch{}},k=()=>{l=!0,A&&(A.reconnect=R);try{a?.()}catch(F){console.warn(`[${this.#a}] ignored an interaction open callback failure:`,F.message)}A&&this.#Q(r,o).then(()=>{if(!p){f=!0;for(let F of y.splice(0))K(F)}}).catch(F=>{B??=F,R(),m(F)})},G=(F,T)=>{F&&(Q=Q.then(()=>F(T)).catch(V=>{B??=V,R(),m(B)}))},K=F=>{let T=F.payload;if(A&&T.type==="session/event"){this.#d(r,[T.event]);return}if(T.type==="question/requested"||T.type==="approval/requested"){let V=T.type==="question/requested"?"question":"approval",U=V==="question"?F.rpcId:T.approvalId,b=`${V}:${U}`;if(A){let X=this.#u(r,b,V);if(X?.ownership!==A)return;this.#p.set(b,X)}let L=V==="approval"&&A&&typeof T.callId=="string"?this.#p.get(b)?.ownership.toolCalls.get(T.callId):void 0;G(i,Object.freeze({kind:V,interactionId:U,rpcId:F.rpcId,sessionId:r,payload:T,recovered:A?this.#p.get(b)?.recovered===!0:!1,...L?{toolCall:L}:{},reconnect:R,respond:(X,pe={})=>this.respondInteraction(F.rpcId,X,{...pe,signal:pe.signal??o})}));return}if(T.type==="question/resolved"||T.type==="approval/resolved"){let V=T.type==="question/resolved"?"question":"approval",U=V==="question"?T.questionRpcId:T.approvalId,b=`${V}:${U}`;if(A){if(this.#p.get(b)?.ownership!==A)return;this.#p.delete(b)}G(e,Object.freeze({kind:V,interactionId:U,sessionId:r,outcome:T.outcome,payload:T}))}},x=F=>{try{if(typeof F.data!="string")throw new Error("binary WebSocket frame");let T=JSON.parse(F.data),V=T?.payload;if(T?.type!=="server-request"||typeof T.rpcId!="string"||!V||typeof V!="object"||T.method!==V.type)throw new Error("invalid server-request envelope");if(V.sessionId!==r)return;f?K(T):y.push(T)}catch(T){console.warn(`[${this.#a}] ignored a malformed Harness interaction frame:`,T.message)}},H=()=>m(l?null:new Error("Harness interaction WebSocket closed before opening")),q=()=>{m(new Error(l?"Harness interaction WebSocket failed":"Harness interaction WebSocket failed before opening")),R()},j=()=>{R(),m()};c.addEventListener("open",k),c.addEventListener("message",x),c.addEventListener("close",H,{once:!0}),c.addEventListener("error",q,{once:!0}),o.addEventListener("abort",j,{once:!0}),o.aborted&&j()})}stopManagedProcess(){this.#o?.exitCode===null&&this.#o.kill("SIGTERM")}};var Od=class extends qt{constructor(r){super({...r,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{randomUUID as ote}from"node:crypto";import{mkdir as nte,readFile as ste,rename as gte,unlink as cte,writeFile as Ite}from"node:fs/promises";import{dirname as lte}from"node:path";var Md=Object.freeze({version:1,sessions:{},seenMessageIds:[],pendingSenders:{}});function Pt(n){return typeof n=="string"&&n.trim()?n.trim():null}function sG(n){return(Pt(n)??"\u9489\u9489\u7528\u6237").slice(0,100)}function Ete(n,r){if(!n||typeof n!="object")return null;let o=Pt(n.requestId)??Pt(r),i=Pt(n.staffId),e=Pt(n.requestedAt)??Pt(n.lastSeenAt),a=Pt(n.lastSeenAt)??e;return!o||!i||!e||!a?null:{requestId:o,staffId:i,displayName:sG(n.displayName??n.nick),requestedAt:e,lastSeenAt:a}}function pte(n){if(!n||typeof n!="object")return structuredClone(Md);let r={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,a]of Object.entries(n.sessions)){let A=Pt(e),t=Pt(a);A&&t&&(r[A]=t)}let o={},i=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,a]of i){let A=Ete(a,e);if(!A)continue;let t=Object.values(o).find(s=>s.staffId===A.staffId);(!t||t.lastSeenAtnew Date().toISOString()}={}){if(!Pt(r))throw new TypeError("state path is required");if(typeof o!="function"||typeof i!="function")throw new TypeError("idFactory and now must be functions");this.#e=r,this.#r=o,this.#g=i}async load(){try{this.#A=pte(JSON.parse(await ste(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(Md),await this.#n()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){let i=Pt(r),e=Pt(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[i]=e,await this.#n()}async clearSession(r){let o=Pt(r);!o||!(o in this.#A.sessions)||(delete this.#A.sessions[o],await this.#n())}async clearSessions(){this.#A.sessions={},await this.#n()}hasSeen(r){let o=Pt(r);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(r){let o=Pt(r);if(!o)throw new TypeError("messageId is required");this.hasSeen(o)||(this.#A.seenMessageIds.push(o),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#n())}pendingSenders(){return Object.values(this.#A.pendingSenders).sort((r,o)=>r.requestedAt.localeCompare(o.requestedAt)).map(r=>structuredClone(r))}pendingSender(r){let o=Pt(r),i=o?this.#A.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(r,o,i){let e=r&&typeof r=="object"?r:{staffId:r,displayName:o,lastSeenAt:i},a=Pt(e.staffId);if(!a)throw new TypeError("staffId is required");let A=Pt(e.lastSeenAt)??Pt(e.requestedAt)??this.#g(),t=Object.values(this.#A.pendingSenders).find(g=>g.staffId===a),s={requestId:t?.requestId??`ding_sender_${this.#r()}`,staffId:a,displayName:sG(e.displayName??e.nick??o),requestedAt:t?.requestedAt??A,lastSeenAt:A};return this.#A.pendingSenders[s.requestId]=s,await this.#n(),structuredClone(s)}async removePendingSender(r){let o=Pt(r);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#n(),!0)}async removePendingSenderByStaffId(r){let o=Pt(r),i=o?Object.values(this.#A.pendingSenders).find(e=>e.staffId===o):null;return i?this.removePendingSender(i.requestId):!1}snapshot(){return structuredClone(this.#A)}async remove(){await this.#t;try{await cte(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(Md)}async#n(){let r=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await nte(lte(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await Ite(i,r,{encoding:"utf8",mode:384}),await gte(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{mkdir as Cte,readFile as hte,realpath as dte,rename as ute,stat as Bte,unlink as Qte,writeFile as fte}from"node:fs/promises";import{dirname as yte,isAbsolute as IG,resolve as RE}from"node:path";var eUe=Object.freeze({version:1,workspaces:Object.freeze({})});function _d(n){let r=new Error(n);return r.code=on,r}async function ID(n){return RE(await dte(n))}async function mte(n,r){if(n===r)return!0;try{return await ID(n)===await ID(r)}catch{return!1}}function ai(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new TypeError("Invalid bot id");return n}function Ste(n){if(!n||n.version!==1||!n.workspaces||typeof n.workspaces!="object"||Array.isArray(n.workspaces))return null;let r={};for(let[o,i]of Object.entries(n.workspaces)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(o)||typeof i!="string"||!IG(i))return null;r[o]=RE(i)}return{version:1,workspaces:r}}async function gG(n){if(typeof n!="string"||!n.trim()||!IG(n.trim())){let i=new Error("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");throw i.code="workspace-not-absolute",i}let r=RE(n.trim()),o;try{o=await Bte(r)}catch(i){let e=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002",{cause:i});throw e.code="workspace-not-found",e}if(!o.isDirectory()){let i=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");throw i.code="workspace-not-directory",i}return r}var Cr=class{#e;#A;#t={};#r=new Map;#g=1;#n=new Map;#E=1;#s=new Map;#I=new WeakMap;#a=new Set;#i=Promise.resolve();#o=new Map;constructor(r,{defaultWorkspace:o=process.cwd()}={}){if(typeof r!="string"||!r)throw new TypeError("workspace store path is required");this.#e=r,this.#A=RE(o)}async load(){try{let r=Ste(JSON.parse(await hte(this.#e,"utf8")));if(!r)throw new Error("dsh-im workspace config is invalid");this.#t=r.workspaces}catch(r){if(r?.code!=="ENOENT")throw r;this.#t={}}this.#r.clear(),this.#g=1,this.#n.clear(),this.#E=1,this.#s.clear(),this.#a.clear();for(let r of Object.keys(this.#t))this.#r.set(r,this.#c()),this.#n.set(r,this.#l());return this}has(r){let o=ai(r);return Object.hasOwn(this.#t,o)&&!this.#s.has(o)}incarnationFor(r){return this.#n.get(ai(r))??null}workspaceFor(r){return this.#t[ai(r)]??this.#A}generationFor(r){return this.#r.get(ai(r))??null}async whenIdle(){await this.#i}async whenBotIdle(r){let o=ai(r);for(;;){let i=this.#o.get(o);if(!i||(await i,this.#o.get(o)===i))return}}async ensure(r,{workspace:o=this.#A}={}){let i=ai(r),e=RE(o);return this.#C(i,async()=>{if(this.#t[i])this.#r.has(i)||this.#r.set(i,this.#c());else{this.#t[i]=e,this.#r.set(i,this.#c()),this.#n.set(i,this.#l());try{await this.#d()}catch(a){throw delete this.#t[i],this.#r.delete(i),this.#n.delete(i),a}}return this.#t[i]})}async setWorkspace(r,o,{clearSessions:i,incarnation:e}={}){let a=ai(r);if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){let t=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw t.code="workspace-bot-not-found",t}let A=await gG(o);return this.#C(a,async()=>{if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}if(A===this.workspaceFor(a))return A;let t=this.#t[a];this.#r.set(a,this.#c()),await i?.(),this.#t[a]=A;try{await this.#d()}catch(s){throw this.#t[a]=t,s}return A})}async bindWorkspaceSession(r,o,{conversationKey:i,sessionId:e,clearSessions:a,setSession:A,incarnation:t,expectedGeneration:s}={}){let g=ai(r);if(typeof i!="string"||!i||typeof e!="string"||!e)throw new TypeError("conversationKey and sessionId are required");if(typeof a!="function"||typeof A!="function")throw new TypeError("session state callbacks are required");if(!this.has(g)||t!==void 0&&t!==this.incarnationFor(g)){let l=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw l.code="workspace-bot-not-found",l}let c=await ID(await gG(o));return this.#C(g,async()=>{if(!this.has(g)||t!==void 0&&t!==this.incarnationFor(g)){let l=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw l.code="workspace-bot-not-found",l}if(s!==void 0&&s!==this.generationFor(g))throw _d("The bot workspace changed before the session binding could be committed.");if(!await mte(c,this.workspaceFor(g))){let l=this.#t[g];this.#r.set(g,this.#c()),await a(),this.#t[g]=c;try{await this.#d()}catch(p){throw this.#t[g]=l,p}}return await A(i,e),{workspace:c,sessionId:e,generation:this.#r.get(g)}})}async invalidateSessions(r,{clearSessions:o}={}){let i=ai(r);return this.#C(i,async()=>{this.#r.set(i,this.#c()),await o?.()})}async beginRemoval(r,{clearSessions:o}={}){let i=ai(r);return this.#C(i,async()=>{let e=this.#s.get(i);if(e)return e;let a=Object.freeze({});this.#s.set(i,a),this.#I.set(a,{botId:i,incarnation:this.incarnationFor(i)}),this.#r.set(i,this.#c());try{await o?.()}catch(A){throw this.#s.get(i)===a&&this.#s.delete(i),A}return a})}async abortRemoval(r){let{botId:o}=this.#p(r);return this.#C(o,async()=>this.#s.get(o)!==r?!1:(this.#s.delete(o),Object.hasOwn(this.#t,o)&&(this.#r.set(o,this.#c()),this.#n.has(o)||this.#n.set(o,this.#l())),!0))}async finishRemoval(r){let{botId:o,incarnation:i}=this.#p(r);return this.#C(o,async()=>this.#s.get(o)!==r?{removed:!1,persisted:!0,error:null,stale:!0}:this.incarnationFor(o)!==i?(this.#s.delete(o),{removed:!1,persisted:!0,error:null,stale:!0}):(this.#s.delete(o),this.#h(o)))}async retireAfterConfigCommit(r){let o=ai(r);return this.#C(o,async()=>(this.#s.delete(o),this.#h(o)))}async remove(r){let o=await this.retireAfterConfigCommit(r);if(o.error)throw o.error;return o.removed}async reconcile(r){let o=new Set([...r].map(ai)),i=new Set([...Object.keys(this.#t),...this.#a]);for(let e of i)o.has(e)||await this.remove(e)}decorateStatus(r){return!r||typeof r!="object"||!Array.isArray(r.bots)?r:{...r,bots:r.bots.map(o=>o?.botId?{...o,workspace:this.workspaceFor(o.botId)}:o)}}#c(){let r=this.#g;return this.#g+=1,r}#l(){let r=this.#E;return this.#E+=1,r}#p(r){if(!r||typeof r!="object")throw new TypeError("Invalid workspace removal transaction");let o=this.#I.get(r);if(!o)throw new TypeError("Invalid workspace removal transaction");return o}async#h(r){let o=Object.hasOwn(this.#t,r),i=o||this.#a.has(r);if(delete this.#t[r],this.#r.delete(r),this.#n.delete(r),!i)return{removed:!1,persisted:!0,error:null,stale:!1};try{return await this.#Q(),{removed:o,persisted:!0,error:null,stale:!1}}catch(e){return this.#a.add(r),{removed:o,persisted:!1,error:e,stale:!1}}}async#C(r,o){let i=this.#i.then(o,o),e=i.then(()=>{},()=>{});return this.#i=e,this.#o.set(r,e),e.finally(()=>{this.#o.get(r)===e&&this.#o.delete(r)}),i}async#d(){let r={version:1,workspaces:this.#t};await Cte(yte(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await fte(o,`${JSON.stringify(r,null,2)} -`,{encoding:"utf8",mode:384}),await ute(o,this.#e),this.#a.clear()}async#Q(){if(Object.keys(this.#t).length>0){await this.#d();return}try{await Qte(this.#e),this.#a.clear()}catch(r){if(r?.code!=="ENOENT")throw r;this.#a.clear()}}};function cG(n,r){return r&&typeof r.then=="function"?r.then(o=>n.decorateStatus(o)):n.decorateStatus(r)}function Dte(n){return Promise.resolve(n.status())}function Jr(n,{workspaces:r,method:o="remove",botIdFromRemoved:i=e=>e?.botId}){if(!n||!r||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(e,a){let A=Reflect.get(e,a,e);return a===o?async(...t)=>{let s=await A.apply(e,t),g=s?i(s,t):null;return g&&await r.retireAfterConfigCommit(g),s}:typeof A=="function"?A.bind(e):A}})}function qr(n,{botId:r,workspaces:o,state:i}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let e=o.incarnationFor(r),a=()=>o.has(r)&&o.incarnationFor(r)===e,A=new Map,t=new Proxy(n,{get(g,c){if(c==="currentWorkspace")return()=>{if(!a()){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}return o.workspaceFor(r)};if(c==="assertWorkspaceScope")return()=>{if(!a()){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}};if((c==="listWorkspaces"||c==="listWorkspaceSessions")&&typeof g[c]=="function")return async(...p)=>{if(!a()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}let B=await g[c](...p);if(!a()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}return B};if(c==="switchWorkspace")return p=>{if(!a()){let B=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");return B.code="workspace-bot-not-found",Promise.reject(B)}return o.setWorkspace(r,p,{clearSessions:()=>i.clearSessions(),incarnation:e})};if(c==="bindWorkspaceSession")return async(p,B)=>{if(typeof p!="string"||!p||typeof B!="string"||!B)throw new TypeError("conversationKey and sessionId are required");if(!a()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(typeof g.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let Q=o.generationFor(r),f=await g.adoptWorkspaceSession(B);if(!a()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(Q!==o.generationFor(r))throw _d("The bot workspace changed while the session was being adopted.");if(!f||typeof f!="object"||f.sessionId!==B||typeof f.workspace!="string")throw new TypeError("Harness returned an invalid adopted workspace session");let y=await o.bindWorkspaceSession(r,f.workspace,{conversationKey:p,sessionId:B,clearSessions:()=>i.clearSessions(),setSession:(m,R)=>i.setSession(m,R),incarnation:e,expectedGeneration:Q});if(!a()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(y.generation!==o.generationFor(r))throw _d("The bot workspace changed before the session binding completed.");return A.set(B,y.generation),{...f,workspace:y.workspace,sessionId:y.sessionId}};if(c==="createSession")return async(p={})=>{if(await o.whenBotIdle(r),!a()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}let B=o.generationFor(r),Q=await g.createSession({...p,workspace:o.workspaceFor(r)});return A.set(Q,B),Q};if(c==="workspaceSession")return p=>{if(typeof p!="string"||!p)throw new TypeError("sessionId is required");let B=A.get(p)??o.generationFor(r);A.delete(p);let Q=()=>a()&&B===o.generationFor(r);return Object.freeze({sessionId:p,async sessionExists(...f){if(!Q())return!1;let y=await g.sessionExists(p,...f);return Q()&&y},ask(...f){if(!Q())throw _d("The bot workspace changed before this prompt started.");return g.ask(p,...f)}})};if(c==="sessionExists")return(p,...B)=>{if(!a())return!1;let Q=A.get(p);return Q!==void 0&&Q!==o.generationFor(r)?(A.delete(p),!1):g.sessionExists(p,...B)};if(c==="ask")return(p,...B)=>{let Q=A.get(p);if(A.delete(p),!a()||Q!==void 0&&Q!==o.generationFor(r)){let f=new Error("The bot workspace changed before this prompt started.");throw f.code=on,f}return g.ask(p,...B)};if(c==="executeCommand"&&typeof g.executeCommand=="function")return(p,...B)=>{let Q=A.get(p);if(A.delete(p),!a()||Q!==void 0&&Q!==o.generationFor(r)){let f=new Error("The bot workspace changed before this command started.");throw f.code=on,f}return g.executeCommand(p,...B)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}}),s=new Proxy(i,{get(g,c){if(c===WS)return g;if(c==="sessionFor")return(p,...B)=>{if(!a())return null;let Q=g.sessionFor(p,...B);return Q&&!A.has(Q)&&A.set(Q,o.generationFor(r)),Q};if(c==="setSession")return(p,B,...Q)=>{let f=A.get(B);return!a()||f!==void 0&&f!==o.generationFor(r)?(A.delete(B),!1):g.setSession(p,B,...Q)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}});return Object.freeze({harness:t,state:s})}function Vr(n,{workspaces:r,stateFor:o}){if(!n||!r||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let i=new Map,e=(t,s)=>{let c=(i.get(t)??Promise.resolve()).catch(()=>{}).then(s);return i.set(t,c),c.finally(()=>{i.get(t)===c&&i.delete(t)})},a=(t,s)=>{let g=r.incarnationFor(t);return e(t,async()=>{if(!(await n.status())?.bots?.some(p=>p?.botId===t)){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}let l=await o(t);return await r.setWorkspace(t,s,{clearSessions:()=>l.clearSessions(),incarnation:g}),r.decorateStatus(await n.status())})},A=(t,s)=>e(t,async()=>{let g=await r.beginRemoval(t,{clearSessions:async()=>{try{let c=await o(t);if(!c||typeof c.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await c.clearSessions()}catch(c){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${t}:`,c?.message??c)}}});try{let c=await s();return await r.finishRemoval(g),r.decorateStatus(c)}catch(c){let l=await Dte(n).catch(()=>null);throw Array.isArray(l?.bots)&&!l.bots.some(B=>B?.botId===t)?await r.finishRemoval(g):await r.abortRemoval(g),c}});return new Proxy(n,{get(t,s){if(s==="updateWorkspace")return a;let g=Reflect.get(t,s,t);return typeof g!="function"?g:s==="deleteBot"?(c,...l)=>A(c,()=>g.call(t,c,...l)):s==="disconnect"?async(...c)=>{let p=(await t.status())?.bots?.[0]?.botId;return p?A(p,()=>g.apply(t,c)):cG(r,g.apply(t,c))}:(...c)=>cG(r,g.apply(t,c))}})}var lG=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function wte(n){if(!Array.isArray(n)||n.length===0)return[...lG];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...lG]}var Nd=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=wte(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(io.invoke({namespace:"commands",method:"execute",args:{agentId:i,line:e},signal:a.signal})}}function bte(n,r){if(r!==void 0)return new URL(r);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-dingtalk requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function _te(n){let r=pg(n.dshHome??process.env.DSH_HOME??kE(Mte(),".dsh")),o=pg(n.dataDir??kE(r,"integrations","dsh-dingtalk"));return{root:o,config:pg(n.configPath??kE(o,"config.json")),bots:pg(n.botsDir??kE(o,"bots")),workspaces:pg(n.workspacesPath??kE(o,"workspaces.json"))}}async function ED(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-dingtalk requires ctx.webServer");let i=o.ConfigStore??hd,e=o.DeviceAuth??ud,a=o.StateStore??bd,A=o.HarnessClient??Od,t=o.Controller??ME,s=o.Runtime??NE,g=o.createConnectionSupervisor??lD,c=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,l=_te(r),p=await new i(l.config).load(),B=pg(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=typeof p.list=="function",m=y?p.list():[];y&&await f.reconcile(m.map(V=>V.botId)),await Promise.all(m.map(V=>f.ensure(V.botId)));let R=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,k=o.deviceAuth??new e({baseUrl:r.registrationBaseUrl}),G=new Map,K=V=>pg(l.bots,V,"state.json"),x=async V=>{let U=G.get(V);return U||(U=await new a(K(V)).load(),G.set(V,U)),U},H=zr(n,o.commandExecutor),q=new A({baseUrl:bte(n.webServer,r.harnessBaseUrl),workspace:B,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...H?{commandExecutor:H}:{}}),j=new t({deviceAuth:k,credentials:n.credentials,configStore:R,logger:c,createRuntime:async({botId:V,config:U,clientSecret:b})=>{let L=await x(V);await f.ensure(V);let X=qr(q,{botId:V,workspaces:f,state:L});return new s({config:U,clientSecret:b,harness:X.harness,state:X.state,replyTimeoutMs:r.replyTimeoutMs??6e5,maxMessageChars:r.maxMessageChars??4e3,connectTimeoutMs:r.connectTimeoutMs??15e3,logger:{error:(...pe)=>c.error?.(`[${V}]`,...pe),warn:(...pe)=>c.warn?.(`[${V}]`,...pe),info:(...pe)=>c.info?.(`[${V}]`,...pe),debug:(...pe)=>c.debug?.(`[${V}]`,...pe)}})},deleteState:async({botId:V})=>{let U=G.get(V);if(G.delete(V),U&&typeof U.remove=="function")await U.remove();else try{await Ote(K(V))}catch(b){if(b?.code!=="ENOENT")throw b}}}),F=Vr(j,{workspaces:f,stateFor:x}),T=g({controller:F,harness:q,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:F,ready:T.ready,async close(){await T.close(),await F.close(),q.stopManagedProcess()}}}import Rte from"qrcode";var Nte=new Set(["loopback","trusted-host"]);function Wr(n){if(n===void 0)return"loopback";if(Nte.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as Tte}from"node:path";var da="bot.workspace.set";function Zr(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(r=>["botId","workspace"].includes(r))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&Tte(n.workspace.trim())}function Xr(n){return["workspace-not-absolute","workspace-not-found","workspace-not-directory","workspace-bot-not-found"].includes(n?.code)?{code:n.code,message:n.message}:null}var pG="/dingtalk",xt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),CG=Object.freeze(Object.values(xt)),kte=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function CD(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ts(n,r){return CD(n)&&Object.keys(n).every(o=>r.includes(o))}function Cg(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function EG(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function vte(n,r){return CD(r)?n===xt.status?ts(r,[])?null:"connection.status does not accept fields.":n===xt.beginProvisioning?ts(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[xt.pollProvisioning,xt.cancelProvisioning].includes(n)?ts(r,["attemptId"])&&Cg(r.attemptId)?null:`${n} requires an attemptId.`:n===xt.bindCredentials?ts(r,["clientId","clientSecret"])&&EG(r.clientId,256)&&EG(r.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===xt.reconnectBot?ts(r,["botId","sendTest"])&&Cg(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===xt.deleteBot?ts(r,["botId","confirm"])&&Cg(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===xt.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===xt.approveSender?ts(r,["botId","requestId","confirm"])&&Cg(r.botId)&&Cg(r.requestId)&&r.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===xt.revokeSender?ts(r,["botId","senderKey","confirm"])&&Cg(r.botId)&&Cg(r.senderKey)&&r.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function Td(n){return{ok:!1,error:{code:"bad-request",message:n}}}function vE(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function Pte(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Wc(n){if(Array.isArray(n))return n.map(Wc);if(!CD(n))return n;let r={};for(let[o,i]of Object.entries(n))kte.has(o)||(r[o]=Wc(i));return r}async function Gte(n){return Rte.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function pD(n,r){return!n||typeof n.verificationUrl!="string"?Wc(n):Wc({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function hg(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await pD(o.provisioning,r)),Wc(o)}function Fte(n){for(let r of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[r]!="function")throw new TypeError(`A complete DingTalk controller is required (${r})`)}function hG(n,{encodeQr:r=Gte}={}){Fte(n);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(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return vE();if(!CG.includes(e))return Td("Unknown DingTalk endpoint.");let t=vte(e,a);if(t)return Td(t);try{let s;if(e===xt.status)s=await hg(await n.status(),i);else if(e===xt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),vE();s=await pD(g,i)}else if(e===xt.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return Td("The provisioning attempt no longer exists.");s=await pD(g,i)}else if(e===xt.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return Td("The provisioning attempt no longer exists.");s=Wc(s)}else if(e===xt.bindCredentials)s=await hg(await n.bindCredentials(a),i);else if(e===xt.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return vE();let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u9489\u9489\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await hg({...g,...c?{testMessage:c}:{}},i)}else if(e===xt.deleteBot)s=await hg(await n.deleteBot(a.botId),i);else if(e===xt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await hg(await n.updateWorkspace(a.botId,a.workspace),i)}else e===xt.approveSender?s=await hg(await n.approveSender(a.botId,a.requestId),i):s=await hg(await n.revokeSender(a.botId,a.senderKey),i);return A?.aborted?vE():{ok:!0,value:s}}catch(s){let g=Xr(s);return A?.aborted?vE():g?{ok:!1,error:g}:Pte()}}}function Rd(n,r,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(pG,hG(r,o),{authority:Wr(i)})}async function dG(n,r={}){if(r?.controller)return Rd(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await ED(n,r,r.internals),i=Rd(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-dingtalk: close bot connections"),i}import{createHash as Lte}from"node:crypto";import{mkdir as Ute,readFile as Hte,rename as Kte,unlink as Yte,writeFile as xte}from"node:fs/promises";import{dirname as jte}from"node:path";var hD=Object.freeze({version:1,bots:Object.freeze([])});function nn(n){return typeof n=="string"&&n.trim()?n.trim():null}function uG(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PE(n,{botPrefix:r,tokenRefPrefix:o}){let i=nn(n);if(!i)throw new TypeError("platformId is required");let e=Lte("sha256").update(i).digest("hex").slice(0,24);return{botId:`${r}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function kd(n,r){let o=nn(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:r:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var Zc=class{#e;#A;#t;#r;#g;#n;#E=hD;#s=Promise.resolve();constructor(r,{channel:o,botPrefix:i,tokenRefPrefix:e}){this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=new RegExp(`^${uG(i)}_[a-f0-9]{24}$`),this.#n=new RegExp(`^${uG(e)}_[A-F0-9]{24}$`)}async load(){try{let r=this.#a(JSON.parse(await Hte(this.#e,"utf8")));if(!r)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#E=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#E=hD}return this}list(){return structuredClone(this.#E.bots)}get(r){let o=this.#E.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByPlatformId(r){let o=this.#E.bots.find(i=>i.platformId===r);return o?structuredClone(o):null}async save(r){let o=this.#I(r);if(!o)throw new Error(`Refusing to persist incomplete ${this.#A} bot data`);return this.#i(i=>{let e=i.find(t=>t.platformId===o.platformId&&t.botId!==o.botId),a=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||a)throw new Error(`Duplicate ${this.#A} bot identity`);let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!this.#g.test(r))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#i(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#s.then(async()=>{try{await Yte(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#E=hD});this.#s=r.then(()=>{},()=>{}),await r}#I(r){if(!r||typeof r!="object")return null;let o=nn(r.platformId),i=nn(r.botId),e=nn(r.tokenRef),a=nn(r.name);if(!o||!i||!e||!a||!this.#g.test(i)||!this.#n.test(e))return null;let A=PE(o,{botPrefix:this.#t,tokenRefPrefix:this.#r});return A.botId!==i||A.tokenRef!==e?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:a,username:nn(r.username),createdAt:nn(r.createdAt)??new Date().toISOString(),connectedAt:nn(r.connectedAt)})}#a(r){if(!r||r.version!==1||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#I(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#i(r){let o,i=this.#s.then(async()=>{let e=[...this.#E.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#o(a),this.#E=a});return this.#s=i.then(()=>{},()=>{}),await i,o}async#o(r){await Ute(jte(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await xte(o,`${JSON.stringify(r,null,2)} +`,{encoding:"utf8",mode:384}),await ute(o,this.#e),this.#a.clear()}async#Q(){if(Object.keys(this.#t).length>0){await this.#d();return}try{await Qte(this.#e),this.#a.clear()}catch(r){if(r?.code!=="ENOENT")throw r;this.#a.clear()}}};function cG(n,r){return r&&typeof r.then=="function"?r.then(o=>n.decorateStatus(o)):n.decorateStatus(r)}function Dte(n){return Promise.resolve(n.status())}function Jr(n,{workspaces:r,method:o="remove",botIdFromRemoved:i=e=>e?.botId}){if(!n||!r||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(e,a){let A=Reflect.get(e,a,e);return a===o?async(...t)=>{let s=await A.apply(e,t),g=s?i(s,t):null;return g&&await r.retireAfterConfigCommit(g),s}:typeof A=="function"?A.bind(e):A}})}function qr(n,{botId:r,workspaces:o,state:i}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let e=o.incarnationFor(r),a=()=>o.has(r)&&o.incarnationFor(r)===e,A=new Map,t=new Proxy(n,{get(g,c){if(c==="currentWorkspace")return()=>{if(!a()){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}return o.workspaceFor(r)};if(c==="assertWorkspaceScope")return()=>{if(!a()){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}};if((c==="listWorkspaces"||c==="listWorkspaceSessions")&&typeof g[c]=="function")return async(...p)=>{if(!a()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}let B=await g[c](...p);if(!a()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}return B};if(c==="switchWorkspace")return p=>{if(!a()){let B=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");return B.code="workspace-bot-not-found",Promise.reject(B)}return o.setWorkspace(r,p,{clearSessions:()=>i.clearSessions(),incarnation:e})};if(c==="bindWorkspaceSession")return async(p,B)=>{if(typeof p!="string"||!p||typeof B!="string"||!B)throw new TypeError("conversationKey and sessionId are required");if(!a()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(typeof g.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let Q=o.generationFor(r),f=await g.adoptWorkspaceSession(B);if(!a()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(Q!==o.generationFor(r))throw _d("The bot workspace changed while the session was being adopted.");if(!f||typeof f!="object"||f.sessionId!==B||typeof f.workspace!="string")throw new TypeError("Harness returned an invalid adopted workspace session");let y=await o.bindWorkspaceSession(r,f.workspace,{conversationKey:p,sessionId:B,clearSessions:()=>i.clearSessions(),setSession:(m,R)=>i.setSession(m,R),incarnation:e,expectedGeneration:Q});if(!a()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(y.generation!==o.generationFor(r))throw _d("The bot workspace changed before the session binding completed.");return A.set(B,y.generation),{...f,workspace:y.workspace,sessionId:y.sessionId}};if(c==="createSession")return async(p={})=>{if(await o.whenBotIdle(r),!a()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}let B=o.generationFor(r),Q=await g.createSession({...p,workspace:o.workspaceFor(r)});return A.set(Q,B),Q};if(c==="workspaceSession")return p=>{if(typeof p!="string"||!p)throw new TypeError("sessionId is required");let B=A.get(p)??o.generationFor(r);A.delete(p);let Q=()=>a()&&B===o.generationFor(r);return Object.freeze({sessionId:p,async sessionExists(...f){if(!Q())return!1;let y=await g.sessionExists(p,...f);return Q()&&y},ask(...f){if(!Q())throw _d("The bot workspace changed before this prompt started.");return g.ask(p,...f)}})};if(c==="sessionExists")return(p,...B)=>{if(!a())return!1;let Q=A.get(p);return Q!==void 0&&Q!==o.generationFor(r)?(A.delete(p),!1):g.sessionExists(p,...B)};if(c==="ask")return(p,...B)=>{let Q=A.get(p);if(A.delete(p),!a()||Q!==void 0&&Q!==o.generationFor(r)){let f=new Error("The bot workspace changed before this prompt started.");throw f.code=on,f}return g.ask(p,...B)};if(c==="executeCommand"&&typeof g.executeCommand=="function")return(p,...B)=>{let Q=A.get(p);if(A.delete(p),!a()||Q!==void 0&&Q!==o.generationFor(r)){let f=new Error("The bot workspace changed before this command started.");throw f.code=on,f}return g.executeCommand(p,...B)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}}),s=new Proxy(i,{get(g,c){if(c===WS)return g;if(c==="sessionFor")return(p,...B)=>{if(!a())return null;let Q=g.sessionFor(p,...B);return Q&&!A.has(Q)&&A.set(Q,o.generationFor(r)),Q};if(c==="setSession")return(p,B,...Q)=>{let f=A.get(B);return!a()||f!==void 0&&f!==o.generationFor(r)?(A.delete(B),!1):g.setSession(p,B,...Q)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}});return Object.freeze({harness:t,state:s})}function Vr(n,{workspaces:r,stateFor:o}){if(!n||!r||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let i=new Map,e=(t,s)=>{let c=(i.get(t)??Promise.resolve()).catch(()=>{}).then(s);return i.set(t,c),c.finally(()=>{i.get(t)===c&&i.delete(t)})},a=(t,s)=>{let g=r.incarnationFor(t);return e(t,async()=>{if(!(await n.status())?.bots?.some(p=>p?.botId===t)){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}let l=await o(t);return await r.setWorkspace(t,s,{clearSessions:()=>l.clearSessions(),incarnation:g}),r.decorateStatus(await n.status())})},A=(t,s)=>e(t,async()=>{let g=await r.beginRemoval(t,{clearSessions:async()=>{try{let c=await o(t);if(!c||typeof c.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await c.clearSessions()}catch(c){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${t}:`,c?.message??c)}}});try{let c=await s();return await r.finishRemoval(g),r.decorateStatus(c)}catch(c){let l=await Dte(n).catch(()=>null);throw Array.isArray(l?.bots)&&!l.bots.some(B=>B?.botId===t)?await r.finishRemoval(g):await r.abortRemoval(g),c}});return new Proxy(n,{get(t,s){if(s==="updateWorkspace")return a;let g=Reflect.get(t,s,t);return typeof g!="function"?g:s==="deleteBot"?(c,...l)=>A(c,()=>g.call(t,c,...l)):s==="disconnect"?async(...c)=>{let p=(await t.status())?.bots?.[0]?.botId;return p?A(p,()=>g.apply(t,c)):cG(r,g.apply(t,c))}:(...c)=>cG(r,g.apply(t,c))}})}var lG=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function wte(n){if(!Array.isArray(n)||n.length===0)return[...lG];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...lG]}var Nd=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=wte(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(io.invoke({namespace:"commands",method:"execute",args:{agentId:i,line:e},signal:a.signal})}}function bte(n,r){if(r!==void 0)return new URL(r);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-dingtalk requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function _te(n){let r=pg(n.dshHome??process.env.DSH_HOME??kE(Mte(),".dsh")),o=pg(n.dataDir??kE(r,"integrations","dsh-dingtalk"));return{root:o,config:pg(n.configPath??kE(o,"config.json")),bots:pg(n.botsDir??kE(o,"bots")),workspaces:pg(n.workspacesPath??kE(o,"workspaces.json"))}}async function ED(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-dingtalk requires ctx.webServer");let i=o.ConfigStore??hd,e=o.DeviceAuth??ud,a=o.StateStore??bd,A=o.HarnessClient??Od,t=o.Controller??ME,s=o.Runtime??NE,g=o.createConnectionSupervisor??lD,c=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,l=_te(r),p=await new i(l.config).load(),B=pg(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=typeof p.list=="function",m=y?p.list():[];y&&await f.reconcile(m.map(V=>V.botId)),await Promise.all(m.map(V=>f.ensure(V.botId)));let R=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,k=o.deviceAuth??new e({baseUrl:r.registrationBaseUrl}),G=new Map,K=V=>pg(l.bots,V,"state.json"),x=async V=>{let U=G.get(V);return U||(U=await new a(K(V)).load(),G.set(V,U)),U},H=zr(n,o.commandExecutor),q=new A({baseUrl:bte(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...H?{commandExecutor:H}:{}}),j=new t({deviceAuth:k,credentials:n.credentials,configStore:R,logger:c,createRuntime:async({botId:V,config:U,clientSecret:b})=>{let L=await x(V);await f.ensure(V);let X=qr(q,{botId:V,workspaces:f,state:L});return new s({config:U,clientSecret:b,harness:X.harness,state:X.state,replyTimeoutMs:r.replyTimeoutMs??6e5,maxMessageChars:r.maxMessageChars??4e3,connectTimeoutMs:r.connectTimeoutMs??15e3,logger:{error:(...pe)=>c.error?.(`[${V}]`,...pe),warn:(...pe)=>c.warn?.(`[${V}]`,...pe),info:(...pe)=>c.info?.(`[${V}]`,...pe),debug:(...pe)=>c.debug?.(`[${V}]`,...pe)}})},deleteState:async({botId:V})=>{let U=G.get(V);if(G.delete(V),U&&typeof U.remove=="function")await U.remove();else try{await Ote(K(V))}catch(b){if(b?.code!=="ENOENT")throw b}}}),F=Vr(j,{workspaces:f,stateFor:x}),T=g({controller:F,harness:q,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:F,ready:T.ready,async close(){await T.close(),await F.close(),q.stopManagedProcess()}}}import Rte from"qrcode";var Nte=new Set(["loopback","trusted-host"]);function Wr(n){if(n===void 0)return"loopback";if(Nte.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as Tte}from"node:path";var da="bot.workspace.set";function Zr(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(r=>["botId","workspace"].includes(r))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&Tte(n.workspace.trim())}function Xr(n){return["workspace-not-absolute","workspace-not-found","workspace-not-directory","workspace-bot-not-found"].includes(n?.code)?{code:n.code,message:n.message}:null}var pG="/dingtalk",xt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),CG=Object.freeze(Object.values(xt)),kte=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function CD(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ts(n,r){return CD(n)&&Object.keys(n).every(o=>r.includes(o))}function Cg(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function EG(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function vte(n,r){return CD(r)?n===xt.status?ts(r,[])?null:"connection.status does not accept fields.":n===xt.beginProvisioning?ts(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[xt.pollProvisioning,xt.cancelProvisioning].includes(n)?ts(r,["attemptId"])&&Cg(r.attemptId)?null:`${n} requires an attemptId.`:n===xt.bindCredentials?ts(r,["clientId","clientSecret"])&&EG(r.clientId,256)&&EG(r.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===xt.reconnectBot?ts(r,["botId","sendTest"])&&Cg(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===xt.deleteBot?ts(r,["botId","confirm"])&&Cg(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===xt.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===xt.approveSender?ts(r,["botId","requestId","confirm"])&&Cg(r.botId)&&Cg(r.requestId)&&r.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===xt.revokeSender?ts(r,["botId","senderKey","confirm"])&&Cg(r.botId)&&Cg(r.senderKey)&&r.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function Td(n){return{ok:!1,error:{code:"bad-request",message:n}}}function vE(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function Pte(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Wc(n){if(Array.isArray(n))return n.map(Wc);if(!CD(n))return n;let r={};for(let[o,i]of Object.entries(n))kte.has(o)||(r[o]=Wc(i));return r}async function Gte(n){return Rte.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function pD(n,r){return!n||typeof n.verificationUrl!="string"?Wc(n):Wc({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function hg(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await pD(o.provisioning,r)),Wc(o)}function Fte(n){for(let r of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[r]!="function")throw new TypeError(`A complete DingTalk controller is required (${r})`)}function hG(n,{encodeQr:r=Gte}={}){Fte(n);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(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return vE();if(!CG.includes(e))return Td("Unknown DingTalk endpoint.");let t=vte(e,a);if(t)return Td(t);try{let s;if(e===xt.status)s=await hg(await n.status(),i);else if(e===xt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),vE();s=await pD(g,i)}else if(e===xt.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return Td("The provisioning attempt no longer exists.");s=await pD(g,i)}else if(e===xt.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return Td("The provisioning attempt no longer exists.");s=Wc(s)}else if(e===xt.bindCredentials)s=await hg(await n.bindCredentials(a),i);else if(e===xt.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return vE();let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u9489\u9489\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await hg({...g,...c?{testMessage:c}:{}},i)}else if(e===xt.deleteBot)s=await hg(await n.deleteBot(a.botId),i);else if(e===xt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await hg(await n.updateWorkspace(a.botId,a.workspace),i)}else e===xt.approveSender?s=await hg(await n.approveSender(a.botId,a.requestId),i):s=await hg(await n.revokeSender(a.botId,a.senderKey),i);return A?.aborted?vE():{ok:!0,value:s}}catch(s){let g=Xr(s);return A?.aborted?vE():g?{ok:!1,error:g}:Pte()}}}function Rd(n,r,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(pG,hG(r,o),{authority:Wr(i)})}async function dG(n,r={}){if(r?.controller)return Rd(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await ED(n,r,r.internals),i=Rd(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-dingtalk: close bot connections"),i}import{createHash as Lte}from"node:crypto";import{mkdir as Ute,readFile as Hte,rename as Kte,unlink as Yte,writeFile as xte}from"node:fs/promises";import{dirname as jte}from"node:path";var hD=Object.freeze({version:1,bots:Object.freeze([])});function nn(n){return typeof n=="string"&&n.trim()?n.trim():null}function uG(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PE(n,{botPrefix:r,tokenRefPrefix:o}){let i=nn(n);if(!i)throw new TypeError("platformId is required");let e=Lte("sha256").update(i).digest("hex").slice(0,24);return{botId:`${r}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function kd(n,r){let o=nn(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:r:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var Zc=class{#e;#A;#t;#r;#g;#n;#E=hD;#s=Promise.resolve();constructor(r,{channel:o,botPrefix:i,tokenRefPrefix:e}){this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=new RegExp(`^${uG(i)}_[a-f0-9]{24}$`),this.#n=new RegExp(`^${uG(e)}_[A-F0-9]{24}$`)}async load(){try{let r=this.#a(JSON.parse(await Hte(this.#e,"utf8")));if(!r)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#E=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#E=hD}return this}list(){return structuredClone(this.#E.bots)}get(r){let o=this.#E.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByPlatformId(r){let o=this.#E.bots.find(i=>i.platformId===r);return o?structuredClone(o):null}async save(r){let o=this.#I(r);if(!o)throw new Error(`Refusing to persist incomplete ${this.#A} bot data`);return this.#i(i=>{let e=i.find(t=>t.platformId===o.platformId&&t.botId!==o.botId),a=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||a)throw new Error(`Duplicate ${this.#A} bot identity`);let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!this.#g.test(r))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#i(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#s.then(async()=>{try{await Yte(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#E=hD});this.#s=r.then(()=>{},()=>{}),await r}#I(r){if(!r||typeof r!="object")return null;let o=nn(r.platformId),i=nn(r.botId),e=nn(r.tokenRef),a=nn(r.name);if(!o||!i||!e||!a||!this.#g.test(i)||!this.#n.test(e))return null;let A=PE(o,{botPrefix:this.#t,tokenRefPrefix:this.#r});return A.botId!==i||A.tokenRef!==e?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:a,username:nn(r.username),createdAt:nn(r.createdAt)??new Date().toISOString(),connectedAt:nn(r.connectedAt)})}#a(r){if(!r||r.version!==1||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#I(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#i(r){let o,i=this.#s.then(async()=>{let e=[...this.#E.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#o(a),this.#E=a});return this.#s=i.then(()=>{},()=>{}),await i,o}async#o(r){await Ute(jte(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await xte(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await Kte(o,this.#e)}};var BG=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function QG(n){return PE(n,BG)}function fG(n){return kd(n,"Discord\u673A\u5668\u4EBA")}var vd=class extends Zc{constructor(r){super(r,{channel:"Discord",...BG})}};function GE(n){return typeof n=="string"&&n.trim()?n.trim():null}function Pd(n,r){return Object.freeze({code:n,message:r})}var Xc=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=new Map;#i=new Map;#o=new Map;#c=0;#l=!1;constructor({descriptor:r,credentials:o,configStore:i,inspectToken:e,deriveIdentity:a,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!r?.key||!r?.label||!r?.connectionLabel)throw new TypeError("TokenBotController requires a channel descriptor");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError(`${r.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${r.label} requires a config store`);if(typeof e!="function"||typeof a!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${r.label} controller dependencies are incomplete`);this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}async initialize(){if(this.#l)return this.status();for(let r of this.#t.list())await this.#Q(r.botId,async()=>{if(this.#l||this.#a.get(r.botId)?.status?.ready)return;let o=await this.#C(r.tokenRef);if(!o){this.#i.set(r.botId,Pd("missing-token",`${this.#e.label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002`));return}try{await this.#p(r,o),this.#i.delete(r.botId)}catch(i){this.#i.set(r.botId,Pd("connection-failed",`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${r.botId} failed to initialize:`,i)}finally{this.#u()}});return this.status()}async bindCredentials({token:r}={}){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let o=GE(r);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#r(o),e=GE(i?.platformId),a=GE(i?.name);if(!e||!a)throw new Error(`${this.#e.label} returned an invalid bot identity`);let A=this.#g(e);return await this.#Q(A.botId,async()=>{if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let t=this.#t.getByPlatformId(e),s=await this.#A.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:a,username:GE(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(A.tokenRef,o);try{await this.#t.save(g)}catch(c){throw await this.#d(A.tokenRef,s),c}try{await this.#p(g,o),this.#i.delete(A.botId)}catch(c){this.#i.set(A.botId,Pd("connection-failed",`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002`)),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${A.botId} credential connection failed:`,c)}this.#u()}),this.status()}async reconnectBot(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(r,async()=>{let i=await this.#C(o.tokenRef);if(!i)throw new Error(`${this.#e.label} bot token is missing`);try{await this.#p(o,i),this.#i.delete(r)}catch(e){throw this.#i.set(r,Pd("connection-failed",`${this.#e.label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`)),e}finally{this.#u()}}),this.status()}async sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return this.#Q(r,async()=>{let i=this.#a.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let a=new Error(`${this.#e.label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5`);throw a.code="test-target-unavailable",a}let e=`${o.name}\uFF08${this.#n(o.platformId)}\uFF09`;return await i.sendConnectionTest(Yr(e,`${this.#e.label}\u673A\u5668\u4EBA`)),{sent:!0}})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(r,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(r);try{await this.#A.unset(o.tokenRef),await this.#t.remove(r)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#p(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#e.label} bot safely.`,{cause:e})}await this.#s({botId:r,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${r} state cleanup failed:`,e)}),this.#i.delete(r),this.#u()}),this.status()}status(){let r=this.#t.list().map(i=>{let e=this.#a.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#i.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#n(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?`${this.#e.label}${this.#e.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5`:`${this.#e.label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF`,lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},error:structuredClone(this.#i.get(i.botId)??null)}}),o=r.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o}}}async close(){this.#l||(this.#l=!0,await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#a.keys()].map(r=>this.#h(r))))}async#p(r,o){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(r.botId),this.#l)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#E({botId:r.botId,config:r,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#a.set(r.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#a.delete(r.botId),e}}async#h(r){let o=this.#a.get(r);this.#a.delete(r),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${r} failed to stop cleanly:`,i)})}async#C(r){let o=await this.#A.resolve(r).catch(()=>{});return GE(o?.value)}async#d(r,o){o?.value?await this.#A.set(r,o.value).catch(()=>{}):await this.#A.unset(r).catch(()=>{})}#Q(r,o){let a=(this.#o.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(r)===a&&this.#o.delete(r)});return this.#o.set(r,a),a}#u(){this.#c+=1}};var Jte="https://discord.com/api/v10/";function FE(n){return typeof n=="string"&&n.trim()?n.trim():null}function qte(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function Vte(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),r?.addEventListener("abort",()=>{clearTimeout(e),i(r.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function $c(n,r){let o=FE(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${r}`);return o}function zte(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var LE=class{#e;#A;#t;constructor({token:r,fetchImpl:o=fetch,baseUrl:i=Jte}){if(!zte(r))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=r.trim(),this.#A=o,this.#t=new URL(i)}getCurrentUser(r={}){return this.#r("users/@me",{...r,method:"GET"})}getGatewayBot(r={}){return this.#r("gateway/bot",{...r,method:"GET"})}createMessage({channelId:r,content:o,replyToMessageId:i,signal:e}){return this.#r(`channels/${$c(r,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:$c(i,"message id"),channel_id:$c(r,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:r,messageId:o,content:i,signal:e}){return this.#r(`channels/${$c(r,"channel id")}/messages/${$c(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:r,signal:o}){return this.#r(`channels/${$c(r,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#r(r,{method:o,body:i,signal:e,timeoutMs:a=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#A(new URL(r,this.#t),{method:o,headers:{authorization:`Bot ${this.#e}`,"content-type":"application/json","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.10.0)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:qte(e,a),redirect:"error"})}catch(c){throw c?.name==="AbortError"||c?.name==="TimeoutError"?c:new Error(`Discord ${o} transport failed`)}let g=null;if(A||s.status===429||!s.ok)try{g=await s.json()}catch{if(A)throw new Error(`Discord ${o} returned invalid JSON`)}if(s.status===429&&t){let c=Math.min(1e4,Math.max(50,Number(g?.retry_after)*1e3||1e3));return await Vte(c,e),this.#r(r,{method:o,body:i,signal:e,timeoutMs:a,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(FE(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function yG(n,r={}){let i=await new LE({token:n,...r}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:FE(i.global_name)??FE(i.username)??"Discord\u673A\u5668\u4EBA",username:FE(i.username)}}var mG="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function Pi(n){return typeof n=="string"?n.trim():""}function Wte(n,r,o){return r.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!Mr(n)&&!!Pi(n.content)}function ka(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var lo=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Set;#c=new Set;#l;constructor({descriptor:r,bot:o,harness:i,state:e,status:a=ka(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!r?.key||!r?.label)throw new TypeError("A channel descriptor is required");if(!o||typeof o.sendText!="function")throw new TypeError("A bot client is required");if(!i||!e)throw new TypeError("Harness client and state store are required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#l=new Ca({label:r.key,logger:A})}get status(){return structuredClone(this.#g)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Pi(r?.conversationId),i=r?.kind==="group"?"group":"direct",e={...r,kind:i,conversationId:o},a=Pi(e.messageId),A=Pi(e.senderId);if(!a||!A||!o||e.senderIsBot===!0||this.#r.hasSeen(a)||this.#o.has(a))return Promise.resolve();this.#o.add(a),e.kind==="direct"&&Va(this.#r,e.connectionTestTarget??e.replyTarget);let t=`${i}:${o}`,s=this.#a.get(t),g=this.#l.claimReply({key:t,actor:A,messageId:a,text:Mr(e)?"":e.content,addressed:e.kind!=="group"||e.addressed===!0,hasPendingQuestion:!!s,questionCompletion:s?.submitting||s?.claimedReplyMessageId?s.queue:null,isQuestionPending:()=>this.#a.has(t),send:c=>this.#A.sendText(e.replyTarget,c)});if(g){let c;return c=g.process(async()=>this.#r.hasSeen(a)?!1:(await this.#r.markSeen(a),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(a),this.#c.delete(c)}),this.#c.add(c),c}if(s&&s.actor!==A)return this.#p(e,a,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#p(e,a,A,t);if(s){Wte(e,s,A)&&(s.claimedReplyMessageId=a);let l=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#C(e,a,A,t,s)).finally(()=>{this.#o.delete(a),s.claimedReplyMessageId===a&&(s.claimedReplyMessageId=null),s.queue===l&&(s.queue=null)});return s.queue=l,l}return this.#p(e,a,A,t)}#p(r,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#h(r,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&this.#o.delete(o),this.#I.get(e)===s&&this.#I.delete(e)});return this.#I.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c])}sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:`${this.#e.label}\u673A\u5668\u4EBA`,send:(o,i)=>this.#A.sendText(o,i)})}async#h(r,o,i,e,{alreadyRecorded:a=!1}={}){if(!a){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}let A=r.replyTarget,t=Pi(r.content),s=null;try{if(this.#s?.throwIfAborted(),r.kind==="group"&&r.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let g=Mr(r);if(!t&&!g){await this.#A.sendText(A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002");return}let c=t.toLowerCase();if(!g&&c==="/help"){await this.#A.sendText(A,[`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002`,"","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` `));return}if(!g&&c==="/status"){await this.#t.ensureRunning({signal:this.#s}),await this.#A.sendText(A,`${this.#e.label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002`);return}let l=g?null:await ti(t,this.#t,e);if(l){for(let y of l.messages??[l.message])await this.#A.sendText(A,y);return}if(!g&&c==="/new"){await this.#r.clearSession(e),await this.#A.sendText(A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002");return}let p=g?null:await Ai(t,this.#t,this.#r,e,{signal:this.#s});if(p){await this.#A.sendText(A,p.message);return}await this.#A.sendTyping?.(A).catch(y=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] typing indicator failed:`,y)});let B=!1;if(typeof this.#A.openStream=="function")try{s=await this.#A.openStream(A)}catch(y){this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to start a streamed reply; using text:`,y)}let Q=g?await Wa(r,{signal:this.#s}):void 0,{answer:f}=await ha({harness:this.#t,state:this.#r,key:e,text:t,content:Q,createOptions:this.#s?{signal:this.#s}:void 0,existsOptions:this.#s?{signal:this.#s}:void 0,askOptions:{timeoutMs:this.#E,signal:this.#s,onUpdate:s?async y=>{let m=y.type==="text"?y.text:y.type==="tool"?`\u6B63\u5728\u4F7F\u7528${y.name}\u2026`:y.text;m&&await s.update(m)}:void 0,onInteraction:y=>this.#d(y,{key:e,actor:i,target:A,requiresMention:r.kind==="group"}),onInteractionResolved:y=>this.#Q(y)}});if(s)try{await s.finish(f),B=!0}catch(y){s.cancel?.(),this.#n.warn?.(`[dsh-im:${this.#e.key}] streamed reply finalization failed; using text:`,y)}B||await this.#A.sendText(A,f),this.#g.messagesReplied+=1,this.#g.lastReplyAt=new Date().toISOString(),this.#g.lastError=null}catch(g){if(s?.cancel?.(),this.#s?.aborted)return;this.#g.lastError=g?.message??String(g);let c=Za(g);if(c){try{await this.#A.sendText(A,c)}catch(l){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send the image error reply:`,l)}return}this.#n.error?.(`[dsh-im:${this.#e.key}] failed to process a message:`,g);try{await this.#A.sendText(A,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}catch(l){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send the safe error reply:`,l)}}finally{await Promise.allSettled([this.#m(e),this.#l.closeRoute(e)])}}async#C(r,o,i,e,a){if(this.#s?.aborted)return;let A=this.#a.get(e),t=a.claimedReplyMessageId===o;if(!A||A!==a||A.submitting)return t&&(!A||A!==a)?this.#B(r,o):this.#p(r,o,i,e,{releaseMessageId:!1});if(this.#r.hasSeen(o))return;if(await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),r.kind==="group"&&r.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let s=r.replyTarget,g=Pi(r.content);if(!g||Mr(r)){try{await this.#A.sendText(s,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")}catch(p){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to reject a non-text interaction reply:`,p)}return}let c=this.#a.get(e);if(!c||c!==a||c.submitting)return t&&(!c||c!==a)?this.#B(r,o,{alreadyRecorded:!0}):this.#p(r,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(c.target=s,c.needsPresentation){let p=c.presentationTask!==null;try{await this.#u(c)}catch(Q){this.#g.lastError=`${this.#e.label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002`,this.#n.error?.(`[dsh-im:${this.#e.key}] failed to retry an interaction question:`,Q),c.interaction.reconnect?.();return}let B=this.#a.get(e);if(!B||B!==a||B.submitting)return t&&(!B||B!==a)?this.#B(r,o,{alreadyRecorded:!0}):this.#p(r,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(!p)return}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,g)),c.index+=1,c.indexthis.#A.sendText(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=Pi(r?.interactionId)||Pi(r?.rpcId);if(!Pi(r?.rpcId)||!t||!Pi(r?.sessionId)||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#n.warn?.(`[dsh-im:${this.#e.key}] ignored an invalid Harness question interaction`);return}if(r.recovered===!0){await this.#D(r,`${this.#e.label} safely cancelled an interaction left by an earlier client.`);try{await this.#A.sendText(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")}catch(c){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send an interaction recovery notice:`,c)}return}let s=this.#a.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#u(s);return}if(this.#i.has(t))return;if(s){this.#n.warn?.(`[dsh-im:${this.#e.key}] cancelled a second pending Harness question`),await this.#D(r,`${this.#e.label} is already handling another user interaction.`);return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationTask:null};this.#a.set(o,g),this.#i.set(t,o),await this.#u(g)}async#Q(r){if(r?.kind==="approval"){await this.#l.handleResolved(r);return}let o=Pi(r?.interactionId);if(r?.kind!=="question"||!o)return;let i=this.#i.get(o);i&&this.#f(i,o)}#u(r){if(r.presentationTask)return r.presentationTask;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=(async()=>{await this.#A.sendText(r.target,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})),r.needsPresentation=!1})();return r.presentationTask=i,i.then(()=>{r.presentationTask===i&&(r.presentationTask=null)},()=>{r.presentationTask===i&&(r.presentationTask=null)}),i}async#B(r,o,{alreadyRecorded:i=!1}={}){if(!i){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}try{await this.#A.sendText(r.replyTarget,mG)}catch(e){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send an expired interaction notice:`,e)}}#y(r,o){let i=this.#a.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#a.delete(r),this.#i.delete(i.interactionId),i)}#f(r,o){return this.#y(r,o)!==null}async#D(r,o){try{await r.respond({ok:!1,error:{code:"cancelled",message:o,details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){if(i?.code!=="interaction-not-pending")throw i}}async#m(r){let o=this.#y(r);if(!(!o||o.kind!=="question"))try{await this.#D(o.interaction,`The ${this.#e.label} interaction ended before the user answered.`)}catch(i){this.#n.warn?.(`[dsh-im:${this.#e.key}] failed to cancel a pending Harness interaction:`,i)}}};var dD=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5"}),Gd=class extends lo{constructor(r){super({descriptor:dD,...r})}};var UE=class extends Xc{constructor(r){super({...r,descriptor:dD,inspectToken:r.inspectToken??yG,deriveIdentity:QG,maskPlatformId:fG})}};var Fd=class extends qt{constructor(r){super({...r,rpcIdPrefix:"discord",logPrefix:"dsh-discord"})}};function ii(n,r){let o=typeof n=="string"?n.trim():"";if(!o)return[];let i=[],e=o;for(;e.length>r;){let a=e.lastIndexOf(` `,r);a{l||g!==null||c||!s||(g=setTimeout(()=>{g=null;let Q=s;s=null;let f=ii(Q,r)[0]??n;c=Promise.resolve(f===p?void 0:e(t,f)).then(()=>{p=f}).catch(y=>A.warn?.("[dsh-im] streamed message update failed:",y)).finally(()=>{c=null,B()})},o),g?.unref?.())};return{async start(){return t=await i(n),this},update(Q){l||typeof Q!="string"||!Q.trim()||(s=Q,B())},async finish(Q){if(l)throw new Error("Message stream is already closed");l=!0,g!==null&&clearTimeout(g),g=null,s=null,await c?.catch(()=>{});let f=ii(Q,r),y=f[0]??"\u5904\u7406\u5B8C\u6210\u3002";y!==p&&await e(t,y),p=y;for(let m of f.slice(1))await a(m)},cancel(){l=!0,s=null,g!==null&&clearTimeout(g),g=null}}}var Zte=4609,SG=Object.freeze([1e3,3e3,5e3,1e4,3e4]),Xte=new Set(["image/jpeg","image/png","image/webp","image/gif"]),$te=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]),ere=Object.freeze(["cdn.discordapp.com"]);function Are(n){let r=new URL(n);if(r.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return r.searchParams.set("v","10"),r.searchParams.set("encoding","json"),r.href}function uD(n,r,o){if(typeof n.addEventListener=="function")n.addEventListener(r,o);else if(typeof n.on=="function")n.on(r,o);else throw new TypeError("Discord WebSocket does not support events")}function tre(n){return typeof n=="string"?n:typeof n?.data=="string"?n.data:Buffer.isBuffer(n)?n.toString("utf8"):Buffer.isBuffer(n?.data)?n.data.toString("utf8"):null}function rre(n){if(n===4004){let o=new Error("Discord Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002");return o.code="discord-401",o}if(n===4013||n===4014){let o=new Error("Discord Gateway Intents \u914D\u7F6E\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 Developer Portal \u7684 Bot \u8BBE\u7F6E\u3002");return o.code="discord-intents",o}let r=new Error(`Discord Gateway closed (${n||"unknown"})`);return r.code="discord-gateway-closed",r}function are(n,r){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${r}>`,"g"),"").trim()}function ire(n){let r=typeof n?.content_type=="string"?n.content_type.split(";",1)[0].trim().toLowerCase():"";if(Xte.has(r))return r;let o=typeof n?.filename=="string"?n.filename.toLowerCase():"";for(let[i,e]of $te)if(o.endsWith(i))return e;return null}function ore(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function nre(n,r){let o=ire(n);return!o||typeof n?.url!="string"?null:{name:typeof n.filename=="string"?n.filename:void 0,mediaType:o,size:ore(n.size),load:i=>za(n.url,{...i,fetchImpl:r,allowedHosts:ere})}}function sre(n,r,{fetchImpl:o=fetch}={}){if(!n?.id||!n?.channel_id||!n?.author?.id)return null;let i=!n.guild_id,e=i||n.mentions?.some(a=>String(a?.id)===String(r));return{messageId:String(n.id),senderId:String(n.author.id),senderIsBot:n.author.bot===!0,kind:i?"direct":"group",conversationId:String(n.channel_id),content:are(n.content??"",r),images:Array.isArray(n.attachments)?n.attachments.map(a=>nre(a,o)).filter(Boolean):[],addressed:e,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)},connectionTestTarget:{channelId:String(n.channel_id)}}}var BD=class{#e;#A;constructor({api:r,signal:o}){this.#e=r,this.#A=o}async sendText(r,o){let i=ii(o,1900),e=null;for(let[a,A]of i.entries())e=await this.#e.createMessage({channelId:r.channelId,content:A,replyToMessageId:a===0?r.replyToMessageId:void 0,signal:this.#A});return e}sendTyping(r){return this.#e.sendTyping({channelId:r.channelId,signal:this.#A})}async openStream(r){return Ld({limit:1900,create:async i=>(await this.#e.createMessage({channelId:r.channelId,content:i,replyToMessageId:r.replyToMessageId,signal:this.#A})).id,edit:(i,e)=>this.#e.editMessage({channelId:r.channelId,messageId:i,content:e,signal:this.#A}),sendRemainder:i=>this.#e.createMessage({channelId:r.channelId,content:i,signal:this.#A})}).start()}};function gre(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var HE=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i=gre();#o=null;#c=null;#l=null;#p=null;#h=null;#C=null;#d=null;#Q=null;#u=null;#B=!0;#y=null;#f=0;#D=0;#m=!0;#w=null;constructor({config:r,token:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,createApi:s=l=>new LE(l),createWebSocket:g=l=>new WebSocket(l),random:c=Math.random}){if(!r||!o||!i||!e)throw new TypeError("DiscordRuntime requires config, token, Harness, and state");if(typeof g!="function")throw new TypeError("DiscordRuntime requires WebSocket");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#a=c}get status(){return structuredClone(this.#i)}async sendConnectionTest(r){if(!this.#i.ready||!this.#c){let o=new Error("Discord bot is not connected");throw o.code="test-target-unavailable",o}return this.#c.sendConnectionTest(r)}async start(){return this.#i.ready&&this.#p?this.status:this.#w?this.#w:(this.#w=this.#N().finally(()=>{this.#w=null}),this.#w)}async#N(){await this.stop(),this.#m=!1,this.#d=null,this.#C=null,this.#Q=null,this.#f=0,this.#i.startedAt=new Date().toISOString(),this.#i.connectionState="connecting",this.#i.lastError=null,await this.#t.ensureRunning(),this.#i.harnessReachable=!0;let r=new AbortController;this.#l=r;let o=this.#s({token:this.#A});this.#o=o;try{let[i,e]=await Promise.all([o.getCurrentUser({signal:r.signal}),o.getGatewayBot({signal:r.signal})]);if(String(i?.id??"")!==this.#e.platformId||i?.bot!==!0)throw new Error("Discord token identity does not match the saved bot");this.#h=e?.url;let a=new BD({api:o,signal:r.signal});this.#c=new Gd({bot:a,harness:this.#t,state:this.#r,status:this.#i,logger:this.#g,replyTimeoutMs:this.#n,signal:r.signal});let A;try{await Promise.race([this.#S(!1),new Promise((t,s)=>{A=setTimeout(()=>s(new Error("Discord Gateway did not become ready in time")),this.#E)})])}finally{clearTimeout(A)}return this.status}catch(i){throw this.#i.ready=!1,this.#i.connectionState="failed",this.#i.lastError=i?.message??String(i),await this.stop(),i}}#S(r){if(this.#m)return Promise.reject(new Error("Discord runtime is stopped"));let o=++this.#D,i=Are(r&&this.#C?this.#C:this.#h),e=this.#I(i);this.#p=e;let a=!1;return new Promise((A,t)=>{let s=()=>{if(a||o!==this.#D)return;a=!0,this.#f=0;let g=Date.now();this.#i.ready=!0,this.#i.connectionState="connected",this.#i.lastCheckedAt=g,this.#i.lastConnectedAt=g,this.#i.lastError=null,A()};uD(e,"message",g=>{if(o!==this.#D||this.#m)return;let c=tre(g);if(!c)return;let l;try{l=JSON.parse(c)}catch{this.#g.warn?.("[dsh-im:discord] ignored malformed Gateway JSON");return}if(Number.isSafeInteger(l.s)&&(this.#Q=l.s),l.op===10){this.#M(l.d?.heartbeat_interval,e,o),r&&this.#d?this.#O(e,{op:6,d:{token:this.#A,session_id:this.#d,seq:this.#Q}}):this.#O(e,{op:2,d:{token:this.#A,intents:Zte,properties:{os:process.platform,browser:"dsh-im",device:"dsh-im"}}});return}if(l.op===11){this.#B=!0,this.#i.lastCheckedAt=Date.now();return}if(l.op===1){this.#F(e);return}if(l.op===7){e.close(4e3,"Reconnect requested");return}if(l.op===9){l.d!==!0&&(this.#d=null,this.#C=null,this.#Q=null),e.close(4e3,"Invalid session");return}if(l.op===0){if(l.t==="READY")this.#d=l.d?.session_id??null,this.#C=l.d?.resume_gateway_url??null,s();else if(l.t==="RESUMED")s();else if(l.t==="MESSAGE_CREATE"){let p=sre(l.d,this.#e.platformId),B=this.#c;p&&B&&B.accept(p).catch(Q=>{o!==this.#D||this.#m||this.#g.error?.(`[dsh-im:discord] bot ${this.#e.botId} message handling failed:`,Q)})}}}),uD(e,"close",(g={})=>{if(o!==this.#D)return;if(this.#T(),this.#p===e&&(this.#p=null),this.#m){a||t(new DOMException("Stopped","AbortError"));return}let c=rre(Number(g.code)||0);if(this.#i.ready=!1,this.#i.connectionState="connecting",this.#i.lastError=c.message,a||(a=!0,t(c)),c.code==="discord-401"||c.code==="discord-intents"){this.#i.connectionState="failed";return}this.#L()}),uD(e,"error",()=>{o!==this.#D||this.#m||(this.#i.lastError="Discord Gateway WebSocket error")})})}#O(r,o){r.readyState===1&&r.send(JSON.stringify(o))}#M(r,o,i){if(this.#T(),!Number.isFinite(r)||r<1e3){o.close(4e3,"Invalid heartbeat interval");return}this.#B=!0;let e=a=>{this.#u=setTimeout(()=>{if(!(this.#m||i!==this.#D||this.#p!==o)){if(!this.#B){o.close(4e3,"Heartbeat was not acknowledged");return}this.#F(o),e(r)}},a),this.#u?.unref?.()};e(Math.floor(r*this.#a()))}#F(r){this.#B=!1,this.#O(r,{op:1,d:this.#Q})}#T(){this.#u!==null&&clearTimeout(this.#u),this.#u=null,this.#B=!0}#L(){if(this.#m||this.#y!==null)return;let r=SG[Math.min(this.#f,SG.length-1)];this.#f+=1,this.#y=setTimeout(()=>{this.#y=null,this.#S(!!this.#d).catch(o=>{this.#m||(this.#g.warn?.("[dsh-im:discord] Gateway reconnect failed:",o),this.#L())})},r),this.#y?.unref?.()}async stop(){this.#m=!0,this.#D+=1,this.#l?.abort(),this.#l=null,this.#y!==null&&clearTimeout(this.#y),this.#y=null,this.#T();let r=this.#p,o=this.#c;this.#p=null,this.#c=null,this.#o=null;try{r&&r.readyState<2&&r.close(1e3,"Plugin stopped")}catch(i){this.#g.warn?.(`[dsh-im:discord] bot ${this.#e.botId} failed to close Gateway:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#i.ready=!1,this.#i.connectionState="idle",this.status}};import{mkdir as cre,readFile as Ire,rename as lre,unlink as Ere,writeFile as pre}from"node:fs/promises";import{dirname as Cre}from"node:path";var Ud=Object.freeze({version:1,sessions:{},seenMessageIds:[],cursor:null});function hre(n){if(!n||typeof n!="object")return structuredClone(Ud);let r={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&o&&typeof i=="string"&&i&&(r[o]=i);return{version:1,sessions:r,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string"&&o).slice(-1e3):[],cursor:Number.isSafeInteger(n.cursor)&&n.cursor>=0?n.cursor:null}}var Eo=class{#e;#A=structuredClone(Ud);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{this.#A=hre(JSON.parse(await Ire(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(Ud),await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}cursor(){return this.#A.cursor}async setCursor(r){if(!Number.isSafeInteger(r)||r<0)throw new TypeError("Invalid update cursor");this.#A.cursor=r,await this.#r()}snapshot(){return structuredClone(this.#A)}async remove(){try{await Ere(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(Ud)}async#r(){let r=`${JSON.stringify(this.#A,null,2)} -`,o=this.#t.then(async()=>{await cre(Cre(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await pre(i,r,{encoding:"utf8",mode:384}),await lre(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var Hd=class extends Eo{};import{unlink as ure}from"node:fs/promises";import{homedir as Bre}from"node:os";import{join as KE,resolve as dg}from"node:path";var DG=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function dre(n){if(!Array.isArray(n)||n.length===0)return[...DG];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...DG]}var QD=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=null;#a=null;#i=0;#o=!1;#c=!1;#l;#p;constructor({channel:r,controller:o,harness:i,logger:e=console,retryDelaysMs:a,healthyIntervalMs:A=15e3,setTimeoutImpl:t=setTimeout,clearTimeoutImpl:s=clearTimeout}){if(!r)throw new TypeError("TokenConnectionSupervisor requires a channel");if(!o||typeof o.initialize!="function"||typeof o.status!="function")throw new TypeError("TokenConnectionSupervisor requires a controller");if(!i||typeof i.ensureRunning!="function")throw new TypeError("TokenConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=dre(a),this.#n=Number.isFinite(A)&&A>=0?A:15e3,this.#E=t,this.#s=s,this.#l=new Promise(g=>{this.#p=g})}get ready(){return this.#l}start(){return this.#c||this.#o?this:(this.#c=!0,this.#h(0),this)}async close(){this.#o||(this.#o=!0,this.#I!==null&&this.#s(this.#I),this.#I=null,await this.#a?.catch(()=>{}),this.#p?.(null),this.#p=null)}#h(r){this.#o||(this.#I=this.#E(()=>{this.#I=null,this.#C()},r),this.#I?.unref?.())}async#C(){if(this.#o||this.#a)return;let r=this.#d();this.#a=r;try{await r}finally{this.#a===r&&(this.#a=null)}}async#d(){try{if(await this.#t.ensureRunning(),this.#o)return;let r=await this.#A.initialize();if(this.#o)return;this.#p?.(r),this.#p=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-im token channel requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function yD(n,r){let o=dg(n.dshHome??process.env.DSH_HOME??KE(Bre(),".dsh")),i=dg(n.dataDir??KE(o,"integrations",`dsh-${r}`));return{config:dg(n.configPath??KE(i,"config.json")),bots:dg(n.botsDir??KE(i,"bots")),workspaces:dg(n.workspacesPath??KE(i,"workspaces.json"))}}async function Kd(n,r,o,i){let{channel:e,ConfigStore:a,StateStore:A,HarnessClient:t,Controller:s,Runtime:g}=i;if(!n?.credentials)throw new TypeError(`dsh-im ${e} requires ctx.credentials`);if(!n?.webServer)throw new TypeError(`dsh-im ${e} requires ctx.webServer`);let c=o.ConfigStore??a,l=o.StateStore??A,p=o.HarnessClient??t,B=o.Controller??s,Q=o.Runtime??g,f=o.createConnectionSupervisor??eI,y=typeof n.logger=="function"?n.logger(`dsh-im:${e}`):n.logger??console,m=yD(r,e),R=await new c(m.config).load(),k=dg(r.workspace??process.cwd()),G=o.WorkspaceStore??Cr,K=o.workspaces??await new G(m.workspaces,{defaultWorkspace:k}).load(),x=R.list();await K.reconcile(x.map(X=>X.botId)),await Promise.all(x.map(X=>K.ensure(X.botId)));let H=typeof R.remove=="function"?Jr(R,{workspaces:K}):R,q=new Map,j=X=>dg(m.bots,X,"state.json"),F=async X=>{let pe=q.get(X);return pe||(pe=await new l(j(X)).load(),q.set(X,pe)),pe},T=zr(n,o.commandExecutor),V=new p({baseUrl:fD(n.webServer,r.harnessBaseUrl),workspace:k,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...T?{commandExecutor:T}:{}}),U=new B({credentials:n.credentials,configStore:H,logger:y,...o.inspectToken?{inspectToken:o.inspectToken}:{},createRuntime:async({botId:X,config:pe,token:me})=>{let qe=await F(X);await K.ensure(X);let Se=qr(V,{botId:X,workspaces:K,state:qe});return new Q({config:pe,token:me,harness:Se.harness,state:Se.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,logger:{error:(...Ge)=>y.error?.(`[${X}]`,...Ge),warn:(...Ge)=>y.warn?.(`[${X}]`,...Ge),info:(...Ge)=>y.info?.(`[${X}]`,...Ge),debug:(...Ge)=>y.debug?.(`[${X}]`,...Ge)}})},deleteState:async({botId:X})=>{let pe=q.get(X);if(q.delete(X),pe&&typeof pe.remove=="function")await pe.remove();else try{await ure(j(X))}catch(me){if(me?.code!=="ENOENT")throw me}}}),b=Vr(U,{workspaces:K,stateFor:F}),L=f({channel:e,controller:b,harness:V,logger:y,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:b,ready:L.ready,async close(){await L.close(),await b.close(),V.stopManagedProcess()}}}function mD(n,r={},o={}){return Kd(n,r,o,{channel:"discord",ConfigStore:vd,StateStore:Hd,HarnessClient:Fd,Controller:UE,Runtime:HE})}var ua=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),Qre=Object.freeze(Object.values(ua)),fre=new Set(["token","botToken","tokenRef","platformId","secret","secretRef"]);function DD(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Yd(n,r){return DD(n)&&Object.keys(n).every(o=>r.includes(o))}function wG(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function yre(n){return typeof n=="string"&&n.trim().length>=20&&n.length<=4096}function mre(n,r){return DD(r)?n===ua.status?Yd(r,[])?null:"connection.status does not accept fields.":n===ua.bindCredentials?Yd(r,["token"])&&yre(r.token)?null:"bot.bind-credentials requires a Bot Token.":n===ua.reconnectBot?Yd(r,["botId","sendTest"])&&wG(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===ua.deleteBot?Yd(r,["botId","confirm"])&&wG(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ua.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown bot endpoint.":"Payload must be an object."}function SD(n){if(Array.isArray(n))return n.map(SD);if(!DD(n))return n;let r={};for(let[o,i]of Object.entries(n))fre.has(o)||(r[o]=SD(i));return r}function Sre(n,r){let o=Xr(r);return o||(r?.code==="webhook-configured"?{code:"webhook-configured",message:r.message}:r?.code==="telegram-401"||r?.code==="discord-401"?{code:"invalid-token",message:`${n} Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002`}:r?.code==="discord-intents"?{code:"discord-intents",message:r.message}:{code:`${n.toLowerCase()}-operation-failed`,message:`${n} \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`})}function wD(n,{channel:r}){for(let o of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[o]!="function")throw new TypeError(`A complete ${r} controller is required (${o})`);return async(o,i,e)=>{if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!Qre.includes(o))return{ok:!1,error:{code:"bad-request",message:`Unknown ${r} endpoint.`}};let a=mre(o,i);if(a)return{ok:!1,error:{code:"bad-request",message:a}};try{let A;if(o===ua.status)A=await n.status();else if(o===ua.bindCredentials)A=await n.bindCredentials(i);else if(o===ua.reconnectBot){if(A=await n.reconnectBot(i.botId),e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(i.sendTest===!0){let t=null;try{if(A?.bots?.find(s=>s?.botId===i.botId)?.connected!==!0){let s=new Error("Bot is not connected");throw s.code="test-target-unavailable",s}if(typeof n.sendConnectionTest!="function"){let s=new Error("Connection test is unavailable");throw s.code="test-target-unavailable",s}await n.sendConnectionTest(i.botId)}catch(s){t=s}A={...A,testMessage:Ot(t)}}}else if(o===ua.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");A=await n.updateWorkspace(i.botId,i.workspace)}else A=await n.deleteBot(i.botId);return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:SD(A)}}catch(A){return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:Sre(r,A)}}}}function xd(n,r,{channel:o,rpcChannel:i,authority:e}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(i,wD(r,{channel:o}),{authority:Wr(e)})}var OG="/discord",MG=ua,Dre=Object.freeze(Object.values(MG));function jd(n,r,o){return xd(n,r,{channel:"Discord",rpcChannel:OG,authority:o})}async function bG(n,r={}){if(r?.controller)return jd(n,r.controller,r.rpcAuthority);let o=await mD(n,r,r.internals??{}),i=jd(n,o.controller,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Discord bot connections"),i}var wre=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]);function Ore(n){let r=n?.client_id??n?.appId,o=n?.client_secret??n?.appSecret;if(typeof r!="string"||r.length===0||typeof o!="string"||o.length===0)throw new TypeError("Feishu registration returned invalid credentials");return{appId:r,appSecret:o,userInfo:n?.user_info??n?.userInfo}}async function Mre(n){return typeof n.status!="function"?{}:await n.status()}function bre(n){return n?.connected===!0?!0:n?.ready===!0&&n?.feishuLongConnectionState==="connected"&&n?.harnessReachable===!0}var Jd=class{#e;#A;#t;#r;#g=!1;#n=null;constructor({createProvisioningManager:r,credentialStore:o,connectionManager:i,registrationOptions:e={}}={}){if(typeof r!="function")throw new TypeError("createProvisioningManager is required");if(!o||typeof o.save!="function"||typeof o.clear!="function")throw new TypeError("credentialStore.save/clear are required");if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("connectionManager.connect/disconnect are required");if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registrationOptions must be an object");if(this.#e=o,this.#A=i,this.#t=structuredClone(e),this.#r=r({onCredentials:a=>this.#E(a)}),!this.#r||typeof this.#r.start!="function"||typeof this.#r.status!="function"||typeof this.#r.cancel!="function")throw new TypeError("The provisioning manager must implement start/status/cancel")}async startRegistration(){return this.#n=null,await this.#r.start(structuredClone(this.#t)),this.status()}async cancelRegistration(){return await this.#r.cancel(),this.status()}async disconnect(){await this.#r.cancel(),await this.#A.disconnect();try{await this.#e.clear(),this.#g=!1,this.#n=null}catch{this.#n={code:"credential_removal_failed",message:"Unable to remove the Feishu credentials."}}return this.status()}async status(){let r=await this.#r.status(),o=await Mre(this.#A),i=bre(o),e=this.#g;if(typeof this.#e.configured=="function")try{e=await this.#e.configured()}catch{e=this.#g}let a="unconfigured";return i?a="connected":wre.has(r?.state)?a="registering":r?.state==="saving"?a="connecting":this.#n||r?.state==="error"?a="error":e&&(a="disconnected"),{phase:a,connected:i,configured:e,registration:r,connection:o,error:this.#n??r?.error??null}}async close(){await this.#r.cancel(),await this.#A.disconnect()}async#E(r){let o=Ore(r);try{await this.#e.save(o),this.#g=!0,await this.#A.connect(o),this.#n=null}catch{throw this.#n={code:"connection_failed",message:"The bot was created, but its connection could not be started."},new Error("Unable to activate the Feishu connection.")}}};function OD(n){return new Jd(n)}import{homedir as ABe}from"node:os";import{join as xI,resolve as Bs}from"node:path";import{unlink as tBe}from"node:fs/promises";var yN={};er(yN,{AESCipher:()=>eC,AccessTokenError:()=>HI,Aily:()=>X_,AppType:()=>mo,CAppTicket:()=>$p,CTenantAccessToken:()=>Vp,CardActionHandler:()=>V_,Client:()=>MB,ClientAssertionError:()=>ea,DefaultCache:()=>DB,Domain:()=>So,EventDispatcher:()=>_B,LarkChannel:()=>PB,LarkChannelError:()=>It,LoggerLevel:()=>La,LoggerProxy:()=>us,WSClient:()=>TB,adaptDefault:()=>Bhe,adaptExpress:()=>Qhe,adaptKoa:()=>fhe,adaptKoaRouter:()=>yhe,createLarkChannel:()=>oue,defaultHttpInstance:()=>KI,defaultLogger:()=>fn,generateChallenge:()=>tC,internalCache:()=>AC,messageCard:()=>She,normalize:()=>d1,normalizeBotAdded:()=>C1,normalizeCardAction:()=>p1,normalizeComment:()=>h1,normalizeReaction:()=>IN,registerApp:()=>vhe,withAll:()=>Ehe,withHelpDeskCredential:()=>Che,withTenantKey:()=>phe,withTenantToken:()=>hhe,withUserAccessToken:()=>dhe});function YE(n,r){return function(){return n.apply(r,arguments)}}var{toString:_re}=Object.prototype,{getPrototypeOf:AI}=Object,{iterator:jE,toStringTag:TG}=Symbol,Vd=(({hasOwnProperty:n})=>(r,o)=>n.call(r,o))(Object.prototype),xE=(n,r)=>{let o=n,i=[];for(;o!=null&&o!==Object.prototype;){if(i.indexOf(o)!==-1)return!1;if(i.push(o),Vd(o,r))return!0;o=AI(o)}return!1},Nre=(n,r)=>n!=null&&xE(n,r)?n[r]:void 0,bD=(n=>r=>{let o=_re.call(r);return n[o]||(n[o]=o.slice(8,-1).toLowerCase())})(Object.create(null)),oi=n=>(n=n.toLowerCase(),r=>bD(r)===n),zd=n=>r=>typeof r===n,{isArray:Bg}=Array,Qg=zd("undefined");function tI(n){return n!==null&&!Qg(n)&&n.constructor!==null&&!Qg(n.constructor)&&Ba(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}var RG=oi("ArrayBuffer");function Tre(n){let r;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?r=ArrayBuffer.isView(n):r=n&&n.buffer&&RG(n.buffer),r}var Rre=zd("string"),Ba=zd("function"),kG=zd("number"),rI=n=>n!==null&&typeof n=="object",kre=n=>n===!0||n===!1,qd=n=>{if(!rI(n))return!1;let r=AI(n);return(r===null||r===Object.prototype||AI(r)===null)&&!xE(n,TG)&&!xE(n,jE)},vre=n=>{if(!rI(n)||tI(n))return!1;try{return Object.keys(n).length===0&&Object.getPrototypeOf(n)===Object.prototype}catch{return!1}},Pre=oi("Date"),Gre=oi("File"),Fre=n=>!!(n&&typeof n.uri<"u"),Lre=n=>n&&typeof n.getParts<"u",Ure=oi("Blob"),Hre=oi("FileList"),Kre=oi("Set"),Yre=n=>rI(n)&&Ba(n.pipe);function xre(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var _G=xre(),NG=typeof _G.FormData<"u"?_G.FormData:void 0,jre=n=>{if(!n)return!1;if(NG&&n instanceof NG)return!0;let r=AI(n);if(!r||r===Object.prototype||!Ba(n.append))return!1;let o=bD(n);return o==="formdata"||o==="object"&&Ba(n.toString)&&n.toString()==="[object FormData]"},Jre=oi("URLSearchParams"),[qre,Vre,zre,Wre]=["ReadableStream","Request","Response","Headers"].map(oi),Zre=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function JE(n,r,{allOwnKeys:o=!1}={}){if(n===null||typeof n>"u")return;let i,e;if(typeof n!="object"&&(n=[n]),Bg(n))for(i=0,e=n.length;i0;)if(e=o[i],r===e.toLowerCase())return e;return null}var ug=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,PG=n=>!Qg(n)&&n!==ug;function MD(...n){let{caseless:r,skipUndefined:o}=PG(this)&&this||{},i={},e=(a,A)=>{if(A==="__proto__"||A==="constructor"||A==="prototype")return;let t=r&&typeof A=="string"&&vG(i,A)||A,s=Vd(i,t)?i[t]:void 0;qd(s)&&qd(a)?i[t]=MD(s,a):qd(a)?i[t]=MD({},a):Bg(a)?i[t]=a.slice():(!o||!Qg(a))&&(i[t]=a)};for(let a=0,A=n.length;a(JE(r,(e,a)=>{o&&Ba(e)?Object.defineProperty(n,a,{__proto__:null,value:YE(e,o),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(n,a,{__proto__:null,value:e,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),n),$re=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),eae=(n,r,o,i)=>{n.prototype=Object.create(r.prototype,i),Object.defineProperty(n.prototype,"constructor",{__proto__:null,value:n,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(n,"super",{__proto__:null,value:r.prototype}),o&&Object.assign(n.prototype,o)},Aae=(n,r,o,i)=>{let e,a,A,t={};if(r=r||{},n==null)return r;do{for(e=Object.getOwnPropertyNames(n),a=e.length;a-- >0;)A=e[a],(!i||i(A,n,r))&&!t[A]&&(r[A]=n[A],t[A]=!0);n=o!==!1&&AI(n)}while(n&&(!o||o(n,r))&&n!==Object.prototype);return r},tae=(n,r,o)=>{n=String(n),(o===void 0||o>n.length)&&(o=n.length),o-=r.length;let i=n.indexOf(r,o);return i!==-1&&i===o},rae=n=>{if(!n)return null;if(Bg(n))return n;let r=n.length;if(!kG(r))return null;let o=new Array(r);for(;r-- >0;)o[r]=n[r];return o},aae=(n=>r=>n&&r instanceof n)(typeof Uint8Array<"u"&&AI(Uint8Array)),iae=(n,r)=>{let i=(n&&n[jE]).call(n),e;for(;(e=i.next())&&!e.done;){let a=e.value;r.call(n,a[0],a[1])}},oae=(n,r)=>{let o,i=[];for(;(o=n.exec(r))!==null;)i.push(o);return i},nae=oi("HTMLFormElement"),sae=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(o,i,e){return i.toUpperCase()+e}),{propertyIsEnumerable:gae}=Object.prototype,cae=oi("RegExp"),GG=(n,r)=>{let o=Object.getOwnPropertyDescriptors(n),i={};JE(o,(e,a)=>{let A;(A=r(e,a,n))!==!1&&(i[a]=A||e)}),Object.defineProperties(n,i)},Iae=n=>{GG(n,(r,o)=>{if(Ba(n)&&["arguments","caller","callee"].includes(o))return!1;let i=n[o];if(Ba(i)){if(r.enumerable=!1,"writable"in r){r.writable=!1;return}r.set||(r.set=()=>{throw Error("Can not rewrite read-only method '"+o+"'")})}})},lae=(n,r)=>{let o={},i=e=>{e.forEach(a=>{o[a]=!0})};return Bg(n)?i(n):i(String(n).split(r)),o},Eae=()=>{},pae=(n,r)=>n!=null&&Number.isFinite(n=+n)?n:r;function Cae(n){return!!(n&&Ba(n.append)&&n[TG]==="FormData"&&n[jE])}var hae=n=>{let r=new WeakSet,o=i=>{if(rI(i)){if(r.has(i))return;if(tI(i))return i;if(!("toJSON"in i)){r.add(i);let e;if(Kre(i)){e=[];for(let a of i){let A=o(a);!Qg(A)&&e.push(A)}}else e=Bg(i)?[]:{},JE(i,(a,A)=>{let t=o(a);!Qg(t)&&(e[A]=t)});return r.delete(i),e}}return i};return o(n)},dae=oi("AsyncFunction"),uae=n=>n&&(rI(n)||Ba(n))&&Ba(n.then)&&Ba(n.catch),FG=((n,r)=>n?setImmediate:r?((o,i)=>(ug.addEventListener("message",({source:e,data:a})=>{e===ug&&a===o&&i.length&&i.shift()()},!1),e=>{i.push(e),ug.postMessage(o,"*")}))(`axios@${Math.random()}`,[]):o=>setTimeout(o))(typeof setImmediate=="function",Ba(ug.postMessage)),Bae=typeof queueMicrotask<"u"?queueMicrotask.bind(ug):typeof process<"u"&&process.nextTick||FG,LG=n=>n!=null&&Ba(n[jE]),Qae=n=>n!=null&&xE(n,jE)&&LG(n),J={isArray:Bg,isArrayBuffer:RG,isBuffer:tI,isFormData:jre,isArrayBufferView:Tre,isString:Rre,isNumber:kG,isBoolean:kre,isObject:rI,isPlainObject:qd,isEmptyObject:vre,isReadableStream:qre,isRequest:Vre,isResponse:zre,isHeaders:Wre,isUndefined:Qg,isDate:Pre,isFile:Gre,isReactNativeBlob:Fre,isReactNative:Lre,isBlob:Ure,isRegExp:cae,isFunction:Ba,isStream:Yre,isURLSearchParams:Jre,isTypedArray:aae,isFileList:Hre,forEach:JE,merge:MD,extend:Xre,trim:Zre,stripBOM:$re,inherits:eae,toFlatObject:Aae,kindOf:bD,kindOfTest:oi,endsWith:tae,toArray:rae,forEachEntry:iae,matchAll:oae,isHTMLForm:nae,hasOwnProperty:Vd,hasOwnProp:Vd,hasOwnInPrototypeChain:xE,getSafeProp:Nre,reduceDescriptors:GG,freezeMethods:Iae,toObjectSet:lae,toCamelCase:sae,noop:Eae,toFiniteNumber:pae,findKey:vG,global:ug,isContextDefined:PG,isSpecCompliantForm:Cae,toJSONObject:hae,isAsyncFn:dae,isThenable:uae,setImmediate:FG,asap:Bae,isIterable:LG,isSafeIterable:Qae};var fae=J.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),UG=n=>{let r={},o,i,e;return n&&n.split(` +`,o=this.#t.then(async()=>{await cre(Cre(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await pre(i,r,{encoding:"utf8",mode:384}),await lre(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var Hd=class extends Eo{};import{unlink as ure}from"node:fs/promises";import{homedir as Bre}from"node:os";import{join as KE,resolve as dg}from"node:path";var DG=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function dre(n){if(!Array.isArray(n)||n.length===0)return[...DG];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...DG]}var QD=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=null;#a=null;#i=0;#o=!1;#c=!1;#l;#p;constructor({channel:r,controller:o,harness:i,logger:e=console,retryDelaysMs:a,healthyIntervalMs:A=15e3,setTimeoutImpl:t=setTimeout,clearTimeoutImpl:s=clearTimeout}){if(!r)throw new TypeError("TokenConnectionSupervisor requires a channel");if(!o||typeof o.initialize!="function"||typeof o.status!="function")throw new TypeError("TokenConnectionSupervisor requires a controller");if(!i||typeof i.ensureRunning!="function")throw new TypeError("TokenConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=dre(a),this.#n=Number.isFinite(A)&&A>=0?A:15e3,this.#E=t,this.#s=s,this.#l=new Promise(g=>{this.#p=g})}get ready(){return this.#l}start(){return this.#c||this.#o?this:(this.#c=!0,this.#h(0),this)}async close(){this.#o||(this.#o=!0,this.#I!==null&&this.#s(this.#I),this.#I=null,await this.#a?.catch(()=>{}),this.#p?.(null),this.#p=null)}#h(r){this.#o||(this.#I=this.#E(()=>{this.#I=null,this.#C()},r),this.#I?.unref?.())}async#C(){if(this.#o||this.#a)return;let r=this.#d();this.#a=r;try{await r}finally{this.#a===r&&(this.#a=null)}}async#d(){try{if(await this.#t.ensureRunning(),this.#o)return;let r=await this.#A.initialize();if(this.#o)return;this.#p?.(r),this.#p=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-im token channel requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function yD(n,r){let o=dg(n.dshHome??process.env.DSH_HOME??KE(Bre(),".dsh")),i=dg(n.dataDir??KE(o,"integrations",`dsh-${r}`));return{config:dg(n.configPath??KE(i,"config.json")),bots:dg(n.botsDir??KE(i,"bots")),workspaces:dg(n.workspacesPath??KE(i,"workspaces.json"))}}async function Kd(n,r,o,i){let{channel:e,ConfigStore:a,StateStore:A,HarnessClient:t,Controller:s,Runtime:g}=i;if(!n?.credentials)throw new TypeError(`dsh-im ${e} requires ctx.credentials`);if(!n?.webServer)throw new TypeError(`dsh-im ${e} requires ctx.webServer`);let c=o.ConfigStore??a,l=o.StateStore??A,p=o.HarnessClient??t,B=o.Controller??s,Q=o.Runtime??g,f=o.createConnectionSupervisor??eI,y=typeof n.logger=="function"?n.logger(`dsh-im:${e}`):n.logger??console,m=yD(r,e),R=await new c(m.config).load(),k=dg(r.workspace??process.cwd()),G=o.WorkspaceStore??Cr,K=o.workspaces??await new G(m.workspaces,{defaultWorkspace:k}).load(),x=R.list();await K.reconcile(x.map(X=>X.botId)),await Promise.all(x.map(X=>K.ensure(X.botId)));let H=typeof R.remove=="function"?Jr(R,{workspaces:K}):R,q=new Map,j=X=>dg(m.bots,X,"state.json"),F=async X=>{let pe=q.get(X);return pe||(pe=await new l(j(X)).load(),q.set(X,pe)),pe},T=zr(n,o.commandExecutor),V=new p({baseUrl:fD(n.webServer,r.harnessBaseUrl),workspace:k,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...T?{commandExecutor:T}:{}}),U=new B({credentials:n.credentials,configStore:H,logger:y,...o.inspectToken?{inspectToken:o.inspectToken}:{},createRuntime:async({botId:X,config:pe,token:me})=>{let qe=await F(X);await K.ensure(X);let Se=qr(V,{botId:X,workspaces:K,state:qe});return new Q({config:pe,token:me,harness:Se.harness,state:Se.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,logger:{error:(...Ge)=>y.error?.(`[${X}]`,...Ge),warn:(...Ge)=>y.warn?.(`[${X}]`,...Ge),info:(...Ge)=>y.info?.(`[${X}]`,...Ge),debug:(...Ge)=>y.debug?.(`[${X}]`,...Ge)}})},deleteState:async({botId:X})=>{let pe=q.get(X);if(q.delete(X),pe&&typeof pe.remove=="function")await pe.remove();else try{await ure(j(X))}catch(me){if(me?.code!=="ENOENT")throw me}}}),b=Vr(U,{workspaces:K,stateFor:F}),L=f({channel:e,controller:b,harness:V,logger:y,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:b,ready:L.ready,async close(){await L.close(),await b.close(),V.stopManagedProcess()}}}function mD(n,r={},o={}){return Kd(n,r,o,{channel:"discord",ConfigStore:vd,StateStore:Hd,HarnessClient:Fd,Controller:UE,Runtime:HE})}var ua=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),Qre=Object.freeze(Object.values(ua)),fre=new Set(["token","botToken","tokenRef","platformId","secret","secretRef"]);function DD(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Yd(n,r){return DD(n)&&Object.keys(n).every(o=>r.includes(o))}function wG(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function yre(n){return typeof n=="string"&&n.trim().length>=20&&n.length<=4096}function mre(n,r){return DD(r)?n===ua.status?Yd(r,[])?null:"connection.status does not accept fields.":n===ua.bindCredentials?Yd(r,["token"])&&yre(r.token)?null:"bot.bind-credentials requires a Bot Token.":n===ua.reconnectBot?Yd(r,["botId","sendTest"])&&wG(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===ua.deleteBot?Yd(r,["botId","confirm"])&&wG(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ua.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown bot endpoint.":"Payload must be an object."}function SD(n){if(Array.isArray(n))return n.map(SD);if(!DD(n))return n;let r={};for(let[o,i]of Object.entries(n))fre.has(o)||(r[o]=SD(i));return r}function Sre(n,r){let o=Xr(r);return o||(r?.code==="webhook-configured"?{code:"webhook-configured",message:r.message}:r?.code==="telegram-401"||r?.code==="discord-401"?{code:"invalid-token",message:`${n} Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002`}:r?.code==="discord-intents"?{code:"discord-intents",message:r.message}:{code:`${n.toLowerCase()}-operation-failed`,message:`${n} \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`})}function wD(n,{channel:r}){for(let o of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[o]!="function")throw new TypeError(`A complete ${r} controller is required (${o})`);return async(o,i,e)=>{if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!Qre.includes(o))return{ok:!1,error:{code:"bad-request",message:`Unknown ${r} endpoint.`}};let a=mre(o,i);if(a)return{ok:!1,error:{code:"bad-request",message:a}};try{let A;if(o===ua.status)A=await n.status();else if(o===ua.bindCredentials)A=await n.bindCredentials(i);else if(o===ua.reconnectBot){if(A=await n.reconnectBot(i.botId),e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(i.sendTest===!0){let t=null;try{if(A?.bots?.find(s=>s?.botId===i.botId)?.connected!==!0){let s=new Error("Bot is not connected");throw s.code="test-target-unavailable",s}if(typeof n.sendConnectionTest!="function"){let s=new Error("Connection test is unavailable");throw s.code="test-target-unavailable",s}await n.sendConnectionTest(i.botId)}catch(s){t=s}A={...A,testMessage:Ot(t)}}}else if(o===ua.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");A=await n.updateWorkspace(i.botId,i.workspace)}else A=await n.deleteBot(i.botId);return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:SD(A)}}catch(A){return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:Sre(r,A)}}}}function xd(n,r,{channel:o,rpcChannel:i,authority:e}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(i,wD(r,{channel:o}),{authority:Wr(e)})}var OG="/discord",MG=ua,Dre=Object.freeze(Object.values(MG));function jd(n,r,o){return xd(n,r,{channel:"Discord",rpcChannel:OG,authority:o})}async function bG(n,r={}){if(r?.controller)return jd(n,r.controller,r.rpcAuthority);let o=await mD(n,r,r.internals??{}),i=jd(n,o.controller,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Discord bot connections"),i}var wre=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]);function Ore(n){let r=n?.client_id??n?.appId,o=n?.client_secret??n?.appSecret;if(typeof r!="string"||r.length===0||typeof o!="string"||o.length===0)throw new TypeError("Feishu registration returned invalid credentials");return{appId:r,appSecret:o,userInfo:n?.user_info??n?.userInfo}}async function Mre(n){return typeof n.status!="function"?{}:await n.status()}function bre(n){return n?.connected===!0?!0:n?.ready===!0&&n?.feishuLongConnectionState==="connected"&&n?.harnessReachable===!0}var Jd=class{#e;#A;#t;#r;#g=!1;#n=null;constructor({createProvisioningManager:r,credentialStore:o,connectionManager:i,registrationOptions:e={}}={}){if(typeof r!="function")throw new TypeError("createProvisioningManager is required");if(!o||typeof o.save!="function"||typeof o.clear!="function")throw new TypeError("credentialStore.save/clear are required");if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("connectionManager.connect/disconnect are required");if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registrationOptions must be an object");if(this.#e=o,this.#A=i,this.#t=structuredClone(e),this.#r=r({onCredentials:a=>this.#E(a)}),!this.#r||typeof this.#r.start!="function"||typeof this.#r.status!="function"||typeof this.#r.cancel!="function")throw new TypeError("The provisioning manager must implement start/status/cancel")}async startRegistration(){return this.#n=null,await this.#r.start(structuredClone(this.#t)),this.status()}async cancelRegistration(){return await this.#r.cancel(),this.status()}async disconnect(){await this.#r.cancel(),await this.#A.disconnect();try{await this.#e.clear(),this.#g=!1,this.#n=null}catch{this.#n={code:"credential_removal_failed",message:"Unable to remove the Feishu credentials."}}return this.status()}async status(){let r=await this.#r.status(),o=await Mre(this.#A),i=bre(o),e=this.#g;if(typeof this.#e.configured=="function")try{e=await this.#e.configured()}catch{e=this.#g}let a="unconfigured";return i?a="connected":wre.has(r?.state)?a="registering":r?.state==="saving"?a="connecting":this.#n||r?.state==="error"?a="error":e&&(a="disconnected"),{phase:a,connected:i,configured:e,registration:r,connection:o,error:this.#n??r?.error??null}}async close(){await this.#r.cancel(),await this.#A.disconnect()}async#E(r){let o=Ore(r);try{await this.#e.save(o),this.#g=!0,await this.#A.connect(o),this.#n=null}catch{throw this.#n={code:"connection_failed",message:"The bot was created, but its connection could not be started."},new Error("Unable to activate the Feishu connection.")}}};function OD(n){return new Jd(n)}import{homedir as ABe}from"node:os";import{join as xI,resolve as Bs}from"node:path";import{unlink as tBe}from"node:fs/promises";var yN={};er(yN,{AESCipher:()=>eC,AccessTokenError:()=>HI,Aily:()=>X_,AppType:()=>mo,CAppTicket:()=>$p,CTenantAccessToken:()=>Vp,CardActionHandler:()=>V_,Client:()=>MB,ClientAssertionError:()=>ea,DefaultCache:()=>DB,Domain:()=>So,EventDispatcher:()=>_B,LarkChannel:()=>PB,LarkChannelError:()=>It,LoggerLevel:()=>La,LoggerProxy:()=>us,WSClient:()=>TB,adaptDefault:()=>Bhe,adaptExpress:()=>Qhe,adaptKoa:()=>fhe,adaptKoaRouter:()=>yhe,createLarkChannel:()=>oue,defaultHttpInstance:()=>KI,defaultLogger:()=>fn,generateChallenge:()=>tC,internalCache:()=>AC,messageCard:()=>She,normalize:()=>d1,normalizeBotAdded:()=>C1,normalizeCardAction:()=>p1,normalizeComment:()=>h1,normalizeReaction:()=>IN,registerApp:()=>vhe,withAll:()=>Ehe,withHelpDeskCredential:()=>Che,withTenantKey:()=>phe,withTenantToken:()=>hhe,withUserAccessToken:()=>dhe});function YE(n,r){return function(){return n.apply(r,arguments)}}var{toString:_re}=Object.prototype,{getPrototypeOf:AI}=Object,{iterator:jE,toStringTag:TG}=Symbol,Vd=(({hasOwnProperty:n})=>(r,o)=>n.call(r,o))(Object.prototype),xE=(n,r)=>{let o=n,i=[];for(;o!=null&&o!==Object.prototype;){if(i.indexOf(o)!==-1)return!1;if(i.push(o),Vd(o,r))return!0;o=AI(o)}return!1},Nre=(n,r)=>n!=null&&xE(n,r)?n[r]:void 0,bD=(n=>r=>{let o=_re.call(r);return n[o]||(n[o]=o.slice(8,-1).toLowerCase())})(Object.create(null)),oi=n=>(n=n.toLowerCase(),r=>bD(r)===n),zd=n=>r=>typeof r===n,{isArray:Bg}=Array,Qg=zd("undefined");function tI(n){return n!==null&&!Qg(n)&&n.constructor!==null&&!Qg(n.constructor)&&Ba(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}var RG=oi("ArrayBuffer");function Tre(n){let r;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?r=ArrayBuffer.isView(n):r=n&&n.buffer&&RG(n.buffer),r}var Rre=zd("string"),Ba=zd("function"),kG=zd("number"),rI=n=>n!==null&&typeof n=="object",kre=n=>n===!0||n===!1,qd=n=>{if(!rI(n))return!1;let r=AI(n);return(r===null||r===Object.prototype||AI(r)===null)&&!xE(n,TG)&&!xE(n,jE)},vre=n=>{if(!rI(n)||tI(n))return!1;try{return Object.keys(n).length===0&&Object.getPrototypeOf(n)===Object.prototype}catch{return!1}},Pre=oi("Date"),Gre=oi("File"),Fre=n=>!!(n&&typeof n.uri<"u"),Lre=n=>n&&typeof n.getParts<"u",Ure=oi("Blob"),Hre=oi("FileList"),Kre=oi("Set"),Yre=n=>rI(n)&&Ba(n.pipe);function xre(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var _G=xre(),NG=typeof _G.FormData<"u"?_G.FormData:void 0,jre=n=>{if(!n)return!1;if(NG&&n instanceof NG)return!0;let r=AI(n);if(!r||r===Object.prototype||!Ba(n.append))return!1;let o=bD(n);return o==="formdata"||o==="object"&&Ba(n.toString)&&n.toString()==="[object FormData]"},Jre=oi("URLSearchParams"),[qre,Vre,zre,Wre]=["ReadableStream","Request","Response","Headers"].map(oi),Zre=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function JE(n,r,{allOwnKeys:o=!1}={}){if(n===null||typeof n>"u")return;let i,e;if(typeof n!="object"&&(n=[n]),Bg(n))for(i=0,e=n.length;i0;)if(e=o[i],r===e.toLowerCase())return e;return null}var ug=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,PG=n=>!Qg(n)&&n!==ug;function MD(...n){let{caseless:r,skipUndefined:o}=PG(this)&&this||{},i={},e=(a,A)=>{if(A==="__proto__"||A==="constructor"||A==="prototype")return;let t=r&&typeof A=="string"&&vG(i,A)||A,s=Vd(i,t)?i[t]:void 0;qd(s)&&qd(a)?i[t]=MD(s,a):qd(a)?i[t]=MD({},a):Bg(a)?i[t]=a.slice():(!o||!Qg(a))&&(i[t]=a)};for(let a=0,A=n.length;a(JE(r,(e,a)=>{o&&Ba(e)?Object.defineProperty(n,a,{__proto__:null,value:YE(e,o),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(n,a,{__proto__:null,value:e,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),n),$re=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),eae=(n,r,o,i)=>{n.prototype=Object.create(r.prototype,i),Object.defineProperty(n.prototype,"constructor",{__proto__:null,value:n,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(n,"super",{__proto__:null,value:r.prototype}),o&&Object.assign(n.prototype,o)},Aae=(n,r,o,i)=>{let e,a,A,t={};if(r=r||{},n==null)return r;do{for(e=Object.getOwnPropertyNames(n),a=e.length;a-- >0;)A=e[a],(!i||i(A,n,r))&&!t[A]&&(r[A]=n[A],t[A]=!0);n=o!==!1&&AI(n)}while(n&&(!o||o(n,r))&&n!==Object.prototype);return r},tae=(n,r,o)=>{n=String(n),(o===void 0||o>n.length)&&(o=n.length),o-=r.length;let i=n.indexOf(r,o);return i!==-1&&i===o},rae=n=>{if(!n)return null;if(Bg(n))return n;let r=n.length;if(!kG(r))return null;let o=new Array(r);for(;r-- >0;)o[r]=n[r];return o},aae=(n=>r=>n&&r instanceof n)(typeof Uint8Array<"u"&&AI(Uint8Array)),iae=(n,r)=>{let i=(n&&n[jE]).call(n),e;for(;(e=i.next())&&!e.done;){let a=e.value;r.call(n,a[0],a[1])}},oae=(n,r)=>{let o,i=[];for(;(o=n.exec(r))!==null;)i.push(o);return i},nae=oi("HTMLFormElement"),sae=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(o,i,e){return i.toUpperCase()+e}),{propertyIsEnumerable:gae}=Object.prototype,cae=oi("RegExp"),GG=(n,r)=>{let o=Object.getOwnPropertyDescriptors(n),i={};JE(o,(e,a)=>{let A;(A=r(e,a,n))!==!1&&(i[a]=A||e)}),Object.defineProperties(n,i)},Iae=n=>{GG(n,(r,o)=>{if(Ba(n)&&["arguments","caller","callee"].includes(o))return!1;let i=n[o];if(Ba(i)){if(r.enumerable=!1,"writable"in r){r.writable=!1;return}r.set||(r.set=()=>{throw Error("Can not rewrite read-only method '"+o+"'")})}})},lae=(n,r)=>{let o={},i=e=>{e.forEach(a=>{o[a]=!0})};return Bg(n)?i(n):i(String(n).split(r)),o},Eae=()=>{},pae=(n,r)=>n!=null&&Number.isFinite(n=+n)?n:r;function Cae(n){return!!(n&&Ba(n.append)&&n[TG]==="FormData"&&n[jE])}var hae=n=>{let r=new WeakSet,o=i=>{if(rI(i)){if(r.has(i))return;if(tI(i))return i;if(!("toJSON"in i)){r.add(i);let e;if(Kre(i)){e=[];for(let a of i){let A=o(a);!Qg(A)&&e.push(A)}}else e=Bg(i)?[]:{},JE(i,(a,A)=>{let t=o(a);!Qg(t)&&(e[A]=t)});return r.delete(i),e}}return i};return o(n)},dae=oi("AsyncFunction"),uae=n=>n&&(rI(n)||Ba(n))&&Ba(n.then)&&Ba(n.catch),FG=((n,r)=>n?setImmediate:r?((o,i)=>(ug.addEventListener("message",({source:e,data:a})=>{e===ug&&a===o&&i.length&&i.shift()()},!1),e=>{i.push(e),ug.postMessage(o,"*")}))(`axios@${Math.random()}`,[]):o=>setTimeout(o))(typeof setImmediate=="function",Ba(ug.postMessage)),Bae=typeof queueMicrotask<"u"?queueMicrotask.bind(ug):typeof process<"u"&&process.nextTick||FG,LG=n=>n!=null&&Ba(n[jE]),Qae=n=>n!=null&&xE(n,jE)&&LG(n),J={isArray:Bg,isArrayBuffer:RG,isBuffer:tI,isFormData:jre,isArrayBufferView:Tre,isString:Rre,isNumber:kG,isBoolean:kre,isObject:rI,isPlainObject:qd,isEmptyObject:vre,isReadableStream:qre,isRequest:Vre,isResponse:zre,isHeaders:Wre,isUndefined:Qg,isDate:Pre,isFile:Gre,isReactNativeBlob:Fre,isReactNative:Lre,isBlob:Ure,isRegExp:cae,isFunction:Ba,isStream:Yre,isURLSearchParams:Jre,isTypedArray:aae,isFileList:Hre,forEach:JE,merge:MD,extend:Xre,trim:Zre,stripBOM:$re,inherits:eae,toFlatObject:Aae,kindOf:bD,kindOfTest:oi,endsWith:tae,toArray:rae,forEachEntry:iae,matchAll:oae,isHTMLForm:nae,hasOwnProperty:Vd,hasOwnProp:Vd,hasOwnInPrototypeChain:xE,getSafeProp:Nre,reduceDescriptors:GG,freezeMethods:Iae,toObjectSet:lae,toCamelCase:sae,noop:Eae,toFiniteNumber:pae,findKey:vG,global:ug,isContextDefined:PG,isSpecCompliantForm:Cae,toJSONObject:hae,isAsyncFn:dae,isThenable:uae,setImmediate:FG,asap:Bae,isIterable:LG,isSafeIterable:Qae};var fae=J.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),UG=n=>{let r={},o,i,e;return n&&n.split(` `).forEach(function(A){e=A.indexOf(":"),o=A.substring(0,e).trim().toLowerCase(),i=A.substring(e+1).trim();let t=J.hasOwnProp(r,o);!o||t&&J.hasOwnProp(fae,o)||(o==="set-cookie"?t?r[o].push(i):r[o]=[i]:r[o]=t?r[o]+", "+i:i)}),r};function yae(n){let r=0,o=n.length;for(;rr;){let i=n.charCodeAt(o-1);if(i!==9&&i!==32)break;o-=1}return r===0&&o===n.length?n:n.slice(r,o)}var mae=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Sae=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function _D(n,r){return J.isArray(n)?n.map(o=>_D(o,r)):yae(String(n).replace(r,""))}var HG=n=>_D(n,mae),Dae=n=>_D(n,Sae);function aI(n){let r=Object.create(null);return J.forEach(n.toJSON(),(o,i)=>{r[i]=Dae(o)}),r}var KG=Symbol("internals");function qE(n){return n&&String(n).trim().toLowerCase()}function Wd(n){return n===!1||n==null?n:J.isArray(n)?n.map(Wd):HG(String(n))}function wae(n){let r=Object.create(null),o=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=o.exec(n);)r[i[1]]=i[2];return r}var Oae=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function ND(n){let r=0,o=n.length;for(;rr;){let i=n.charCodeAt(o-1);if(i!==9&&i!==32)break;o-=1}return r===0&&o===n.length?n:n.slice(r,o)}function Mae(n){let r=n.length-1;if(r<1||n.charCodeAt(0)!==34||n.charCodeAt(r)!==34)return n;let o="";for(let i=1;i=r))return n;o+=n[i]}return o}function bae(n){let r=Object.create(null),o=String(n),i=0,e=!1,a=!1;function A(t){let s=ND(o.slice(i,t)),g=s.indexOf("=");if(g<1)return;let c=ND(s.slice(0,g));if(!Oae.test(c))return;let l=c.toLowerCase();if(l==="__proto__"||l==="constructor"||l==="prototype")return;let p=ND(s.slice(g+1));r[l]=Mae(p)}for(let t=0;t/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());function TD(n,r,o,i,e){if(J.isFunction(i))return i.call(this,r,o);if(e&&(r=o),!!J.isString(r)){if(J.isString(i))return r.indexOf(i)!==-1;if(J.isRegExp(i))return i.test(r)}}function Nae(n){return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(r,o,i)=>o.toUpperCase()+i)}function Tae(n,r){let o=J.toCamelCase(" "+r);["get","set","has"].forEach(i=>{Object.defineProperty(n,i+o,{__proto__:null,value:function(e,a,A){return this[i].call(this,r,e,a,A)},configurable:!0})})}var iI=class{constructor(r){r&&this.set(r)}set(r,o,i){let e=this;function a(t,s,g){let c=qE(s);if(!c)return;let l=J.findKey(e,c);(!l||e[l]===void 0||g===!0||g===void 0&&e[l]!==!1)&&(e[l||s]=Wd(t))}let A=(t,s)=>J.forEach(t,(g,c)=>a(g,c,s));if(J.isPlainObject(r)||r instanceof this.constructor)A(r,o);else if(J.isString(r)&&(r=r.trim())&&!_ae(r))A(UG(r),o);else if(J.isObject(r)&&J.isSafeIterable(r)){let t=Object.create(null),s,g;for(let c of r){if(!J.isArray(c))throw new TypeError("Object iterator must return a key-value pair");g=c[0],J.hasOwnProp(t,g)?(s=t[g],t[g]=J.isArray(s)?[...s,c[1]]:[s,c[1]]):t[g]=c[1]}A(t,o)}else r!=null&&a(o,r,i);return this}get(r,o){if(r=qE(r),r){let i=J.findKey(this,r);if(i){let e=this[i];if(!o)return e;if(o===!0)return wae(e);if(J.isFunction(o))return o.call(this,e,i);if(J.isRegExp(o))return o.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(r,o){if(r=qE(r),r){let i=J.findKey(this,r);return!!(i&&this[i]!==void 0&&(!o||TD(this,this[i],i,o)))}return!1}delete(r,o){let i=this,e=!1;function a(A){if(A=qE(A),A){let t=J.findKey(i,A);t&&(!o||TD(i,i[t],t,o))&&(delete i[t],e=!0)}}return J.isArray(r)?r.forEach(a):a(r),e}clear(r){let o=Object.keys(this),i=o.length,e=!1;for(;i--;){let a=o[i];(!r||TD(this,this[a],a,r,!0))&&(delete this[a],e=!0)}return e}normalize(r){let o=this,i={};return J.forEach(this,(e,a)=>{let A=J.findKey(i,a);if(A){o[A]=Wd(e),delete o[a];return}let t=r?Nae(a):String(a).trim();t!==a&&delete o[a],o[t]=Wd(e),i[t]=!0}),this}concat(...r){return this.constructor.concat(this,...r)}toJSON(r){let o=Object.create(null);return J.forEach(this,(i,e)=>{i!=null&&i!==!1&&(o[e]=r&&J.isArray(i)?i.join(", "):i)}),o}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([r,o])=>r+": "+o).join(` `)}getSetCookie(){let r=this.get("set-cookie");return J.isArray(r)?r:r==null||r===!1?[]:[r]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(r){return r instanceof this?r:new this(r)}static parseParameters(r){return bae(r)}static concat(r,...o){let i=new this(r);return o.forEach(e=>i.set(e)),i}static accessor(r){let i=(this[KG]=this[KG]={accessors:{}}).accessors,e=this.prototype;function a(A){let t=qE(A);i[t]||(Tae(e,A),i[t]=!0)}return J.isArray(r)?r.forEach(a):a(r),this}};iI.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);J.reduceDescriptors(iI.prototype,({value:n},r)=>{let o=r[0].toUpperCase()+r.slice(1);return{get:()=>n,set(i){this[o]=i}}});J.freezeMethods(iI);var Ct=iI;var VE="[REDACTED ****]";function Rae(n){if(J.hasOwnProp(n,"toJSON"))return!0;let r=Object.getPrototypeOf(n);for(;r&&r!==Object.prototype;){if(J.hasOwnProp(r,"toJSON"))return!0;r=Object.getPrototypeOf(r)}return!1}function kae(n,r){let o=new Set(r.map(a=>String(a).toLowerCase())),i=[],e=a=>{if(a===null||typeof a!="object"||J.isBuffer(a))return a;if(i.indexOf(a)!==-1)return;a instanceof Ct&&(a=a.toJSON()),i.push(a);let A;if(J.isArray(a))A=[],a.forEach((t,s)=>{let g=e(t);J.isUndefined(g)||(A[s]=g)});else{if(!J.isPlainObject(a)&&Rae(a))return i.pop(),a;A=Object.create(null);for(let[t,s]of Object.entries(a)){let g=o.has(t.toLowerCase())?VE:e(s);J.isUndefined(g)||(A[t]=g)}}return i.pop(),A};return e(n)}function YG(n){try{return String(n)}catch{return""}}function vae(n){return n.errors.map(o=>{try{return o&&o.message?YG(o.message):YG(o)}catch{return""}}).filter(Boolean).join("; ")||n.name||"AggregateError"}var br=class n extends Error{static from(r,o,i,e,a,A){let t=r.message;!t&&J.isArray(r.errors)&&r.errors.length&&(t=vae(r));let s=new n(t,o||r.code,i,e,a);return Object.defineProperty(s,"cause",{__proto__:null,value:r,writable:!0,enumerable:!1,configurable:!0}),s.name=r.name,r.status!=null&&s.status==null&&(s.status=r.status),A&&Object.assign(s,A),s}constructor(r,o,i,e,a){super(r),Object.defineProperty(this,"message",{__proto__:null,value:r,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,o&&(this.code=o),i&&(this.config=i),e&&(this.request=e),a&&(this.response=a,this.status=a.status)}toJSON(){let r=this.config,o=r&&J.hasOwnProp(r,"redact")?r.redact:void 0,i=J.isArray(o)&&o.length>0?kae(r,o):J.toJSONObject(r);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}};br.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";br.ERR_BAD_OPTION="ERR_BAD_OPTION";br.ECONNABORTED="ECONNABORTED";br.ETIMEDOUT="ETIMEDOUT";br.ECONNREFUSED="ECONNREFUSED";br.ERR_NETWORK="ERR_NETWORK";br.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";br.ERR_DEPRECATED="ERR_DEPRECATED";br.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";br.ERR_BAD_REQUEST="ERR_BAD_REQUEST";br.ERR_CANCELED="ERR_CANCELED";br.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";br.ERR_INVALID_URL="ERR_INVALID_URL";br.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var de=br;var jL=Le(xL(),1),ou=jL.default;var nu={isBufferAvailable(){return typeof Buffer<"u"},from(n){return Buffer.from(n)}};var tw=100;function Aw(n){return J.isPlainObject(n)||J.isArray(n)}function JL(n){return J.endsWith(n,"[]")?n.slice(0,-2):n}function ew(n,r,o){return n?n.concat(r).map(function(e,a){return e=JL(e),!o&&a?"["+e+"]":e}).join(o?".":""):r}function Qoe(n){return J.isArray(n)&&!n.some(Aw)}var foe=J.toFlatObject(J,{},null,function(r){return/^is[A-Z]/.test(r)});function yoe(n,r,o){if(!J.isObject(n))throw new TypeError("target must be an object");r=r||new(ou||FormData),o=J.toFlatObject(o,{metaTokens:!0,dots:!1,indexes:!1},!1,function(R,k){return!J.isUndefined(k[R])});let i=o.metaTokens,e=o.visitor||Q,a=o.dots,A=o.indexes,t=o.Blob||typeof Blob<"u"&&Blob,s=o.maxDepth===void 0?tw:o.maxDepth,g=t&&J.isSpecCompliantForm(r),c=[];if(!J.isFunction(e))throw new TypeError("visitor must be a function");function l(m){if(m===null)return"";if(J.isDate(m))return m.toISOString();if(J.isBoolean(m))return m.toString();if(!g&&J.isBlob(m))throw new de("Blob is not supported. Use a Buffer instead.");if(J.isArrayBuffer(m)||J.isTypedArray(m)){if(g&&typeof t=="function")return new t([m]);if(nu&&nu.isBufferAvailable())return nu.from(m);throw new de("Blob is not supported. Use a Buffer instead.",de.ERR_NOT_SUPPORT)}return m}function p(m){if(m>s)throw new de("Object is too deeply nested ("+m+" levels). Max depth: "+s,de.ERR_FORM_DATA_DEPTH_EXCEEDED)}function B(m,R){if(s===1/0)return JSON.stringify(m);let k=[];return JSON.stringify(m,function(K,x){if(!J.isObject(x))return x;for(;k.length&&k[k.length-1]!==this;)k.pop();return k.push(x),p(R+k.length-1),x})}function Q(m,R,k){let G=m;if(J.isReactNative(r)&&J.isReactNativeBlob(m))return r.append(ew(k,R,a),l(m)),!1;if(m&&!k&&typeof m=="object"){if(J.endsWith(R,"{}"))R=i?R:R.slice(0,-2),m=B(m,1);else if(J.isArray(m)&&Qoe(m)||(J.isFileList(m)||J.endsWith(R,"[]"))&&(G=J.toArray(m)))return R=JL(R),G.forEach(function(x,H){!(J.isUndefined(x)||x===null)&&r.append(A===!0?ew([R],H,a):A===null?R:R+"[]",l(x))}),!1}return Aw(m)?!0:(r.append(ew(k,R,a),l(m)),!1)}let f=Object.assign(foe,{defaultVisitor:Q,convertValue:l,isVisitable:Aw});function y(m,R,k=0){if(!J.isUndefined(m)){if(p(k),c.indexOf(m)!==-1)throw new Error("Circular reference detected in "+R.join("."));c.push(m),J.forEach(m,function(K,x){(!(J.isUndefined(K)||K===null)&&e.call(r,K,J.isString(x)?x.trim():x,R,f))===!0&&y(K,R?R.concat(x):[x],k+1)}),c.pop()}}if(!J.isObject(n))throw new TypeError("data must be an object");return y(n),r}var is=yoe;function qL(n){let r={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(n).replace(/[!'()~]|%20/g,function(i){return r[i]})}function VL(n,r){this._pairs=[],n&&is(n,this,r)}var zL=VL.prototype;zL.append=function(r,o){this._pairs.push([r,o])};zL.toString=function(r){let o=r?i=>r.call(this,i,qL):qL;return this._pairs.map(function(e){return o(e[0])+"="+o(e[1])},"").join("&")};var WL=VL;function moe(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function yg(n,r,o){if(!r)return n;n=n||"";let i=J.isFunction(o)?{serialize:o}:o,e=J.getSafeProp(i,"encode")||moe,a=J.getSafeProp(i,"serialize"),A;if(a?A=a(r,i):A=J.isURLSearchParams(r)?r.toString():new WL(r,i).toString(e),A){let t=n.indexOf("#");t!==-1&&(n=n.slice(0,t)),n+=(n.indexOf("?")===-1?"?":"&")+A}return n}var rw=class{constructor(){this.handlers=[]}use(r,o,i){return this.handlers.push({fulfilled:r,rejected:o,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(r){this.handlers[r]&&(this.handlers[r]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(r){J.forEach(this.handlers,function(i){i!==null&&r(i)})}},aw=rw;var os={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0};import Doe from"crypto";import Soe from"url";var ZL=Soe.URLSearchParams;var iw="abcdefghijklmnopqrstuvwxyz",XL="0123456789",$L={DIGIT:XL,ALPHA:iw,ALPHA_DIGIT:iw+iw.toUpperCase()+XL},woe=(n=16,r=$L.ALPHA_DIGIT)=>{let o="",{length:i}=r,e=new Uint32Array(n);Doe.randomFillSync(e);for(let a=0;anw,hasStandardBrowserEnv:()=>Ooe,hasStandardBrowserWebWorkerEnv:()=>Moe,navigator:()=>ow,origin:()=>boe});var nw=typeof window<"u"&&typeof document<"u",ow=typeof navigator=="object"&&navigator||void 0,Ooe=nw&&(!ow||["ReactNative","NativeScript","NS"].indexOf(ow.product)<0),Moe=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",boe=nw&&window.location.href||"http://localhost";var $A={...sw,...e2};function gw(n,r){return is(n,new $A.classes.URLSearchParams,{visitor:function(o,i,e,a){return $A.isNode&&J.isBuffer(o)?(this.append(i,o.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...r})}var A2=tw;function t2(n){if(n>A2)throw new de("FormData field is too deeply nested ("+n+" levels). Max depth: "+A2,de.ERR_FORM_DATA_DEPTH_EXCEEDED)}function _oe(n){let r=[],o=/[^.[\]]+|\[([^.[\]]*)]/g,i;for(;(i=o.exec(n))!==null;)t2(r.length),r.push(i[0]==="[]"?"":i[1]||i[0]);return r}function Noe(n){let r={},o=Object.keys(n),i,e=o.length,a;for(i=0;i=o.length;return A=!A&&J.isArray(e)?e.length:A,s?(J.hasOwnProp(e,A)?e[A]=J.isArray(e[A])?e[A].concat(i):[e[A],i]:e[A]=i,!t):((!J.hasOwnProp(e,A)||!J.isObject(e[A]))&&(e[A]=[]),r(o,i,e[A],a)&&J.isArray(e[A])&&(e[A]=Noe(e[A])),!t)}if(J.isFormData(n)&&J.isFunction(n.entries)){let o={};return J.forEachEntry(n,(i,e)=>{r(_oe(i),e,o,0)}),o}return null}var su=Toe;var cI=(n,r)=>n!=null&&J.hasOwnProp(n,r)?n[r]:void 0;function Roe(n,r,o){if(J.isString(n))try{return(r||JSON.parse)(n),J.trim(n)}catch(i){if(i.name!=="SyntaxError")throw i}return(o||JSON.stringify)(n)}var cw={transitional:os,adapter:["xhr","http","fetch"],transformRequest:[function(r,o){let i=o.getContentType()||"",e=i.indexOf("application/json")>-1,a=J.isObject(r);if(a&&J.isHTMLForm(r)&&(r=new FormData(r)),J.isFormData(r))return e?JSON.stringify(su(r)):r;if(J.isArrayBuffer(r)||J.isBuffer(r)||J.isStream(r)||J.isFile(r)||J.isBlob(r)||J.isReadableStream(r))return r;if(J.isArrayBufferView(r))return r.buffer;if(J.isURLSearchParams(r))return o.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),r.toString();let t;if(a){let s=cI(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return gw(r,s).toString();if((t=J.isFileList(r))||i.indexOf("multipart/form-data")>-1){let g=cI(this,"env"),c=g&&g.FormData;return is(t?{"files[]":r}:r,c&&new c,s)}}return a||e?(o.setContentType("application/json",!1),Roe(r)):r}],transformResponse:[function(r){let o=cI(this,"transitional")||cw.transitional,i=o&&o.forcedJSONParsing,e=cI(this,"responseType"),a=e==="json";if(J.isResponse(r)||J.isReadableStream(r))return r;if(r&&J.isString(r)&&(i&&!e||a)){let t=!(o&&o.silentJSONParsing)&&a;try{return JSON.parse(r,cI(this,"parseReviver"))}catch(s){if(t)throw s.name==="SyntaxError"?de.from(s,de.ERR_BAD_RESPONSE,this,null,cI(this,"response")):s}}return r}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:$A.classes.FormData,Blob:$A.classes.Blob},validateStatus:function(r){return r>=200&&r<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};J.forEach(["delete","get","head","post","put","patch","query"],n=>{cw.headers[n]={}});var II=cw;function ep(n,r){let o=this||II,i=r||o,e=Ct.from(i.headers),a=i.data;return J.forEach(n,function(t){a=t.call(o,a,e.normalize(),r?r.status:void 0)}),e.normalize(),a}function Ap(n){return!!(n&&n.__CANCEL__)}var Iw=class extends de{constructor(r,o,i){super(r??"canceled",de.ERR_CANCELED,o,i),this.name="CanceledError",this.__CANCEL__=!0}},va=Iw;function po(n,r,o){let i=o.config.validateStatus;!o.status||!i||i(o.status)?n(o):r(new de("Request failed with status code "+o.status,o.status>=400&&o.status<500?de.ERR_BAD_REQUEST:de.ERR_BAD_RESPONSE,o.config,o.request,o))}function lw(n){return typeof n!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function Ew(n,r){if(!r)return n;let o=n.length;for(;o>0&&n.charCodeAt(o-1)===47;)o--;return n.slice(0,o)+"/"+r.replace(/^\/+/,"")}var koe=/^https?:(?!\/\/)/i,voe=/[\t\n\r]/g;function Poe(n){let r=0;for(;r`${o}${i}${VE}`)}function Loe(n){let r=n.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${VE}@`),o=r.indexOf("#"),e=(o===-1?r:r.slice(0,o)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${VE}`);return o===-1?e:`${e}#${Foe(r.slice(o+1))}`}function r2(n,r){if(typeof n=="string"){let o=Goe(n);if(koe.test(o))throw new de(`Invalid URL ${JSON.stringify(Loe(o))}: missing "//" after protocol`,de.ERR_INVALID_URL,r)}}function mg(n,r,o,i){r2(r,i);let e=!lw(r);return n&&(e||o===!1)?(r2(n,i),Ew(n,r)):r}var Uoe={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Hoe(n){try{return new URL(n)}catch{return null}}function a2(n){var r=(typeof n=="string"?Hoe(n):n)||{},o=r.protocol,i=r.host,e=r.port;if(typeof i!="string"||!i||typeof o!="string"||(o=o.split(":",1)[0],i=i.replace(/:\d*$/,""),e=parseInt(e)||Uoe[o]||0,!Koe(i,e)))return"";var a=pw(o+"_proxy")||pw("all_proxy");return a&&a.indexOf("://")===-1&&(a=o+"://"+a),a}function Koe(n,r){var o=pw("no_proxy").toLowerCase();return o?o==="*"?!1:o.split(/[,\s]/).every(function(i){if(!i)return!0;var e=i.match(/^(.+):(\d+)$/),a=e?e[1]:i,A=e?parseInt(e[2]):0;return A&&A!==r?!0:/^[.*]/.test(a)?(a.charAt(0)==="*"&&(a=a.slice(1)),!n.endsWith(a)):n!==a}):!0}function pw(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}var qw=Le(Q2(),1),tU=Le(O2(),1);import eU from"http";import AU from"https";import dse from"http2";import use from"util";import{resolve as x2}from"path";import ni from"zlib";var sn="1.19.0";function cp(n){let r=/^([-+\w]{1,25}):(?:\/\/)?/.exec(n);return r&&r[1]||""}var Kne=/^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;function Pw(n,r,o){let i=o&&o.Blob||$A.classes.Blob,e=cp(n);if(r===void 0&&i&&(r=!0),e==="data"){n=e.length?n.slice(e.length+1):n;let a=Kne.exec(n);if(!a)throw new de("Invalid URL",de.ERR_INVALID_URL);let A=a[1],t=a[2],s=a[3]?"base64":"utf8",g=a[4],c="";A?c=t?A+t:A:t&&(c="text/plain"+t);let l=s==="base64"?Buffer.from(g,"base64"):Buffer.from(decodeURIComponent(g),s);if(r){if(!i)throw new de("Blob is not supported",de.ERR_NOT_SUPPORT);return new i([l],{type:c})}return l}throw new de("Unsupported protocol "+e,de.ERR_NOT_SUPPORT)}import Fi from"stream";var Yne=["content-type","content-length"];function Ip(n,r,o){if(o!=="content-only"){n.set(r);return}Object.entries(r||{}).forEach(([i,e])=>{Yne.includes(i.toLowerCase())&&n.set(i,e)})}import xne from"stream";var Gw=Symbol("internals"),Fw=class extends xne.Transform{constructor(r){r=J.toFlatObject(r,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,e)=>!J.isUndefined(e[i])),super({readableHighWaterMark:r.chunkSize});let o=this[Gw]={timeWindow:r.timeWindow,chunkSize:r.chunkSize,maxRate:r.maxRate,minChunkSize:r.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(o.isCaptured||(o.isCaptured=!0))})}_read(r){let o=this[Gw];return o.onReadCallback&&o.onReadCallback(),super._read(r)}_transform(r,o,i){let e=this[Gw],a=e.maxRate,A=this.readableHighWaterMark,t=e.timeWindow,s=1e3/t,g=a/s,c=e.minChunkSize!==!1?Math.max(e.minChunkSize,g*.01):0,l=(B,Q)=>{let f=Buffer.byteLength(B);e.bytesSeen+=f,e.bytes+=f,e.isCaptured&&this.emit("progress",e.bytesSeen),this.push(B)?process.nextTick(Q):e.onReadCallback=()=>{e.onReadCallback=null,process.nextTick(Q)}},p=(B,Q)=>{let f=Buffer.byteLength(B),y=null,m=A,R,k=0;if(a){let G=Date.now();(!e.ts||(k=G-e.ts)>=t)&&(e.ts=G,R=g-e.bytes,e.bytes=R<0?-R:0,k=0),R=g-e.bytes}if(a){if(R<=0)return setTimeout(()=>{Q(null,B)},t-k);Rm&&f-m>c&&(y=B.subarray(m),B=B.subarray(0,m)),l(B,y?()=>{process.nextTick(Q,null,y)}:Q)};p(r,function B(Q,f){if(Q)return i(Q);f?p(f,B):i(null)})}},Lw=Fw;import{EventEmitter as Bse}from"events";import Jne from"util";import{Readable as qne}from"stream";var{asyncIterator:M2}=Symbol,jne=async function*(n){n.stream?yield*n.stream():n.arrayBuffer?yield await n.arrayBuffer():n[M2]?yield*n[M2]():yield n},pu=jne;var Vne=$A.ALPHABET.ALPHA_DIGIT+"-_",lp=typeof TextEncoder=="function"?new TextEncoder:new Jne.TextEncoder,Mg=`\r `,zne=lp.encode(Mg),Wne=2,Uw=class{constructor(r,o){let{escapeName:i}=this.constructor,e=J.isString(o),a=`Content-Disposition: form-data; name="${i(r)}"${!e&&o.name?`; filename="${i(o.name)}"`:""}${Mg}`;if(e)o=lp.encode(String(o).replace(/\r?\n|\r\n?/g,Mg));else{let A=String(o.type||"application/octet-stream").replace(/[\r\n]/g,"");a+=`Content-Type: ${A}${Mg}`}this.headers=lp.encode(a+Mg),this.contentLength=e?o.byteLength:o.size,this.size=this.headers.byteLength+this.contentLength+Wne,this.name=r,this.value=o}async*encode(){yield this.headers;let{value:r}=this;J.isTypedArray(r)?yield r:yield*pu(r),yield zne}static escapeName(r){return String(r).replace(/[\r\n"]/g,o=>({"\r":"%0D","\n":"%0A",'"':"%22"})[o])}},Zne=(n,r,o)=>{let{tag:i="form-data-boundary",size:e=25,boundary:a=i+"-"+$A.generateString(e,Vne)}=o||{};if(!J.isFormData(n))throw new TypeError("FormData instance required");if(a.length<1||a.length>70)throw new Error("boundary must be 1-70 characters long");let A=lp.encode("--"+a+Mg),t=lp.encode("--"+a+"--"+Mg),s=t.byteLength,g=Array.from(n.entries()).map(([l,p])=>{let B=new Uw(l,p);return s+=B.size,B});s+=A.byteLength*g.length,s=J.toFiniteNumber(s);let c={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(s)&&(c["Content-Length"]=s),r&&r(c),qne.from((async function*(){for(let l of g)yield A,yield*l.encode();yield t})())},b2=Zne;import Xne from"stream";var Hw=class extends Xne.Transform{__transform(r,o,i){this.push(r),i()}_transform(r,o,i){if(r.length!==0&&(this._transform=this.__transform,r[0]!==120)){let e=Buffer.alloc(2);e[0]=120,e[1]=156,this.push(e,o)}this.__transform(r,o,i)}},_2=Hw;import $ne from"http2";import ese from"util";var Kw=class{constructor(){this.sessions=Object.create(null)}getSession(r,o){o=Object.assign({sessionTimeout:1e3},o);let i=this.sessions[r];if(i){let l=i.length;for(let p=0;p{if(a)return;a=!0,A&&(clearTimeout(A),A=null);let l=i,p=l.length,B=p;for(;B--;)if(l[B][0]===e){p===1?delete this.sessions[r]:l.splice(B,1),e.closed||e.close();return}},s=e.request,{sessionTimeout:g}=o;if(g!=null){let l=0;e.request=function(){let p=s.apply(this,arguments);return l++,A&&(clearTimeout(A),A=null),p.once("close",()=>{--l||(A=setTimeout(()=>{A=null,t()},g))}),p}}e.once("close",t);let c=[e,o];return i?i.push(c):i=this.sessions[r]=[c],e}},N2=Kw;var Ase=(n,r)=>J.isAsyncFn(n)?function(...o){let i=o.pop();n.apply(this,o).then(e=>{try{r?i(null,...r(e)):i(null,e)}catch(a){i(a)}},i)}:n,T2=Ase;var tse=new Set(["localhost","0.0.0.0"]),v2=n=>{let r=n.split(".");return r.length!==4||r[0]!=="127"?!1:r.every(o=>/^\d+$/.test(o)&&Number(o)>=0&&Number(o)<=255)},Yw=n=>{if(/^0[xX][0-9a-fA-F]+$/.test(n)){let r=parseInt(n.slice(2),16);return Number.isFinite(r)?r:null}if(n.length>1&&/^0[0-7]+$/.test(n)){let r=parseInt(n,8);return Number.isFinite(r)?r:null}if(n.length>1&&/^0[0-9]+$/.test(n))return null;if(/^[0-9]+$/.test(n)){let r=parseInt(n,10);return Number.isFinite(r)?r:null}return null},rse=n=>{if(typeof n!="string"||!n||n.indexOf(":")!==-1)return n;let r=n;if(r.charAt(0)==="["&&r.charAt(r.length-1)==="]"&&(r=r.slice(1,-1)),r=r.replace(/\.+$/,""),!/^[0-9.xXa-fA-F]+$/.test(r))return n;let o=r.split(".");if(o.some(c=>c===""))return n;if(o.length===4){let c=o.map(Yw);return c.some(l=>l===null||l<0||l>255)?n:c.join(".")}if(o.length>4||o.length===1)return n;let i=o.slice(0,-1),e=o[o.length-1],a=4-i.length,A=Yw(e);if(A===null)return n;let t=(1<<8*a)-1;if(A<0||A>t)return n;let s=new Array(a).fill(0);for(let c=a-1,l=A;c>=0;c--,l>>=8)s[c]=l&255;let g=i.map(Yw);return g.some(c=>c===null||c<0||c>255)?n:[...g,...s].join(".")},xw=n=>/^0{1,4}$/.test(n),ase=n=>{if(n==="::")return!0;let r=n.indexOf("::");if(r!==-1){if(r!==n.lastIndexOf("::"))return!1;let i=n.slice(0,r),e=n.slice(r+2),a=i?i.split(":"):[],A=e?e.split(":"):[];return a.length+A.length<8&&a.every(xw)&&A.every(xw)}let o=n.split(":");return o.length===8&&o.every(xw)},ise=n=>{if(n==="::1")return!0;let r=n.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(r)return v2(r[1]);let o=n.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(o){let e=parseInt(o[1],16);return e>=32512&&e<=32767}let i=n.split(":");if(i.length===8){for(let e=0;e<7;e++)if(!/^0+$/.test(i[e]))return!1;return/^0*1$/.test(i[7])}return!1},R2=n=>n?tse.has(n)||v2(n)||ase(n)?!0:ise(n):!1,ose={http:80,https:443,ws:80,wss:443,ftp:21},nse=n=>{let r=n,o=0;if(r.charAt(0)==="["){let a=r.indexOf("]");if(a!==-1){let A=r.slice(1,a),t=r.slice(a+1);return t.charAt(0)===":"&&/^\d+$/.test(t.slice(1))&&(o=Number.parseInt(t.slice(1),10)),[A,o]}}let i=r.indexOf(":"),e=r.lastIndexOf(":");return i!==-1&&i===e&&/^\d+$/.test(r.slice(e+1))&&(o=Number.parseInt(r.slice(e+1),10),r=r.slice(0,e)),[r,o]},sse=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i,gse=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,cse=n=>{if(typeof n!="string"||n.indexOf(":")===-1)return n;let r=n.match(sse);if(r)return r[1];let o=n.match(gse);if(o){let i=parseInt(o[1],16),e=parseInt(o[2],16);return`${i>>8}.${i&255}.${e>>8}.${e&255}`}return n},k2=n=>{if(!n)return n;n.charAt(0)==="["&&n.charAt(n.length-1)==="]"&&(n=n.slice(1,-1));let r=n.replace(/\.+$/,""),o=rse(r);return o!==r?o:cse(r)};function jw(n){let r;try{r=new URL(n)}catch{return!1}let o=(process.env.no_proxy||process.env.NO_PROXY||"").toLowerCase();if(!o)return!1;if(o==="*")return!0;let i=Number.parseInt(r.port,10)||ose[r.protocol.split(":",1)[0]]||0,e=k2(r.hostname.toLowerCase());return o.split(/[\s,]+/).some(a=>{if(!a)return!1;if(a==="*")return!0;let[A,t]=nse(a);return A=k2(A),!A||t&&t!==i?!1:(A.charAt(0)==="*"&&(A=A.slice(1)),A.charAt(0)==="."?e.endsWith(A):e===A||R2(e)&&R2(A))})}function Ise(n,r){n=n||10;let o=new Array(n),i=new Array(n),e=0,a=0,A;return r=r!==void 0?r:1e3,function(s){let g=Date.now(),c=i[a];A||(A=g),o[e]=s,i[e]=g;let l=a,p=0;for(;l!==e;)p+=o[l++],l=l%n;if(e=(e+1)%n,e===a&&(a=(a+1)%n),g-A{o=c,e=null,a&&(clearTimeout(a),a=null),n(...g)};return[(...g)=>{let c=Date.now(),l=c-o;l>=i?A(g,c):(e=g,a||(a=setTimeout(()=>{a=null,A(e)},i-l)))},()=>e&&A(e)]}var G2=lse;var gn=(n,r,o=3)=>{let i=0,e=P2(50,250);return G2(a=>{if(!a||typeof a.loaded!="number")return;let A=a.loaded,t=a.lengthComputable?a.total:void 0,s=Math.max(0,t!=null?Math.min(A,t):A),g=Math.max(0,s-i),c=e(g);i=Math.max(i,s);let l={loaded:s,total:t,progress:t?s/t:void 0,bytes:g,rate:c||void 0,estimated:c&&t?(t-s)/c:void 0,event:a,lengthComputable:t!=null,[r?"download":"upload"]:!0};n(l)},o)},hI=(n,r)=>{let o=n!=null;return[i=>r[0]({lengthComputable:o,total:n,loaded:i}),r[1]]},dI=(n,r=J.asap)=>(...o)=>r(()=>n(...o));var F2=n=>n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102,U2=(n,r,o)=>r+2n<=57?n-48:(n&223)-55,Ese=n=>n>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||n===43||n===47||n===45||n===95,pse=n=>n===9||n===10||n===12||n===13||n===32,Cse=n=>{let r=Math.floor(n/4),o=n%4;return r*3+(o===2?1:o===3?2:0)},H2=n=>{let r=n.length,o=0;return r>0&&n.charCodeAt(r-1)===61&&(o++,r>1&&n.charCodeAt(r-2)===61&&o++),Math.floor((r-o)*3/4)},hse=n=>{let r=n.length,o=0,i=0,e=!1;for(let a=0;a0){e=!0;continue}o++}}return e||i>2||i>0&&(o+i)%4!==0||o%4===1?H2(n):Cse(o)},K2=(n,r)=>{if(!n||typeof n!="string"||!n.startsWith("data:"))return 0;let o=n.indexOf(",");if(o<0)return 0;let i=n.slice(5,o),e=n.slice(o+1);if(/;base64/i.test(i))return r(e);let A=0;for(let t=0,s=e.length;t=55296&&g<=56319&&t+1=56320&&c<=57343?(A+=4,t++):A+=3}else A+=3}return A};function Jw(n){let r=typeof n=="string"?n.indexOf("#"):-1;return K2(r===-1?n:n.slice(0,r),hse)}function Y2(n){return K2(n,H2)}var j2={flush:ni.constants.Z_SYNC_FLUSH,finishFlush:ni.constants.Z_SYNC_FLUSH},Qse={flush:ni.constants.BROTLI_OPERATION_FLUSH,finishFlush:ni.constants.BROTLI_OPERATION_FLUSH},fse={flush:ni.constants.ZSTD_e_flush,finishFlush:ni.constants.ZSTD_e_flush},rU=J.isFunction(ni.createBrotliDecompress),aU=J.isFunction(ni.createZstdDecompress),iU="gzip, compress, deflate"+(rU?", br":""),yse=iU+(aU?", zstd":""),J2=typeof process<"u"&&process.nextTick?process.nextTick.bind(process):J.asap,{http:mse,https:Sse}=tU.default,Vw=/https:?/,q2=Symbol("axios.http.socketListener"),Cu=Symbol("axios.http.currentReq"),oU=Symbol("axios.http.installedTunnel"),Dse=new Map,V2=new WeakMap,z2={22:21,24:5};function wse(n=process.versions&&process.versions.node){if(!n)return!1;let[r,o]=n.split(".").map(i=>Number(i));return!Number.isInteger(r)||!Number.isInteger(o)?!1:r>24?!0:z2[r]!=null&&o>=z2[r]}function Ose(n,r=process.versions&&process.versions.node){if(!wse(r))return!1;let o=n&&n.options;return!!(o&&J.hasOwnProp(o,"proxyEnv")&&o.proxyEnv!=null)}function Mse(n,r,o){return Vw.test(n.protocol)?o||AU.globalAgent:r||eU.globalAgent}function bse(n,r){let o=n.protocol+"//"+n.hostname+":"+(n.port||"")+"#"+(n.auth||""),i=r?V2.get(r)||V2.set(r,new Map).get(r):Dse,e=i.get(o);if(e)return e;let a=r&&r.options?{...r.options,...n}:n;if(e=new qw.default(a),r&&r.options){let A={...r.options},t=e.callback;e.callback=function(g,c){return t.call(this,g,{...A,...c})}}return e[oU]=!0,i.set(o,e),e}var W2=$A.protocols.map(n=>n+":"),Z2=n=>{if(!J.isString(n))return n;try{return decodeURIComponent(n)}catch{return n}},X2=(n,[r,o])=>(n.on("end",o).on("error",o),r),_se=new N2;function Nse(n,r,o){n.beforeRedirects.proxy&&n.beforeRedirects.proxy(n),n.beforeRedirects.auth&&n.beforeRedirects.auth(n),n.beforeRedirects.sensitiveHeaders&&n.beforeRedirects.sensitiveHeaders(n,o),n.beforeRedirects.config&&n.beforeRedirects.config(n,r,o)}function Tse(n,r){n&&Object.keys(n).forEach(o=>{r.has(o.toLowerCase())&&delete n[o]})}function Rse(n,r){if(!r)return!1;try{return new URL(r.url).origin===new URL(n.href).origin}catch{return!1}}function nU(n,r,o,i,e,a){let A=r,t=Mse(n,a,e);if(!A&&A!==!1&&!Ose(t)){let s=a2(o);s&&(jw(o)||(A=new URL(s)))}if(i&&n.headers)for(let s of Object.keys(n.headers))s.toLowerCase()==="proxy-authorization"&&delete n.headers[s];if(i&&n.agent&&n.agent[oU]&&(n.agent=void 0),A){let s=A instanceof URL,g=Q=>s||J.hasOwnProp(A,Q)?A[Q]:void 0,c=g("username"),l=g("password"),p=J.hasOwnProp(A,"auth")?A.auth:void 0;if(c&&(p=(c||"")+":"+(l||"")),p){let Q=typeof p=="object",f=Q&&J.hasOwnProp(p,"username")?p.username:void 0,y=Q&&J.hasOwnProp(p,"password")?p.password:void 0;if(!!(f||y))p=(f||"")+":"+(y||"");else if(Q)throw new de("Invalid proxy authorization",de.ERR_BAD_OPTION,{proxy:A})}if(Vw.test(n.protocol)){if(!(e instanceof qw.default)){let Q=g("hostname")||g("host"),f=g("port"),y=g("protocol"),m=y?y.includes(":")?y:`${y}:`:"http:",R=Q&&Q.includes(":")&&!Q.startsWith("[")?`[${Q}]`:Q,k=new URL(`${m}//${R}${f?":"+f:""}`),G={protocol:k.protocol,hostname:k.hostname.replace(/^\[|\]$/g,""),port:k.port,auth:p&&typeof p=="string"?p:void 0};k.protocol==="https:"&&(G.ALPNProtocols=["http/1.1"]);let K=bse(G,e);n.agent=K,n.agents&&(n.agents.https=K)}}else{if(p){let m=Buffer.from(p,"utf8").toString("base64");n.headers["Proxy-Authorization"]="Basic "+m}let Q=!1;for(let m of Object.keys(n.headers))if(m.toLowerCase()==="host"){Q=!0;break}Q||(n.headers.host=n.hostname+(n.port?":"+n.port:""));let f=g("hostname")||g("host");n.hostname=f,n.host=f,n.port=g("port"),n.path=o;let y=g("protocol");y&&(n.protocol=y.includes(":")?y:`${y}:`)}}n.beforeRedirects.proxy=function(g){nU(g,r,g.href,!0,e,a)}}var kse=typeof process<"u"&&J.kindOf(process)==="process",vse=n=>new Promise((r,o)=>{let i,e,a=(s,g)=>{e||(e=!0,i&&i(s,g))},A=s=>{a(s),r(s)},t=s=>{a(s,!0),o(s)};n(A,t,s=>i=s).catch(t)}),Pse=({address:n,family:r})=>{if(!J.isString(n))throw TypeError("address must be a string");return{address:n,family:r||(n.indexOf(".")<0?6:4)}},$2=(n,r)=>Pse(J.isObject(n)?n:{address:n,family:r}),Gse={request(n,r){let o=n.protocol+"//"+n.hostname+":"+(n.port||(n.protocol==="https:"?443:80)),{http2Options:i,headers:e}=n,a=_se.getSession(o,i),{HTTP2_HEADER_SCHEME:A,HTTP2_HEADER_METHOD:t,HTTP2_HEADER_PATH:s,HTTP2_HEADER_STATUS:g}=dse.constants,c={[A]:n.protocol.replace(":",""),[t]:n.method,[s]:n.path};J.forEach(e,(p,B)=>{B.charAt(0)!==":"&&(c[B]=p)});let l=a.request(c);return l.once("response",p=>{let B=l;p=Object.assign({},p);let Q=p[g];delete p[g],B.headers=p,B.statusCode=+Q,r(B)}),l}},sU=kse&&function(r){return vse(async function(i,e,a){let A=Ie=>J.getSafeProp(r,Ie),t=A("transitional")||os,s=A("data"),g=A("lookup"),c=A("family"),l=A("httpVersion");l===void 0&&(l=1);let p=A("http2Options"),B=A("httpAgent"),Q=A("httpsAgent"),f=A("proxy"),y=A("responseType"),m=A("responseEncoding"),R=A("socketPath"),k=A("method").toUpperCase(),G=A("maxRedirects"),K=A("maxBodyLength"),x=A("maxContentLength"),H=A("decompress"),q,j=!1,F,T;if(l=+l,Number.isNaN(l))throw TypeError(`Invalid protocol version: '${r.httpVersion}' is not a number`);if(l!==1&&l!==2)throw TypeError(`Unsupported protocol version '${l}'`);let V=l===2;if(g){let Ie=T2(g,ye=>J.isArray(ye)?ye:[ye]);g=(ye,_e,DA)=>{Ie(ye,_e,(Te,OA,zA)=>{if(Te)return DA(Te);let BA=J.isArray(OA)?OA.map(rt=>$2(rt)):[$2(OA,zA)];_e.all?DA(Te,BA):DA(Te,BA[0].address,BA[0].family)})}}let U=new Bse;function b(Ie){try{U.emit("abort",!Ie||Ie.type?new va(null,r,F):Ie)}catch{}}function L(){T&&(clearTimeout(T),T=null)}function X(){let Ie=A("timeout"),ye=Ie?"timeout of "+Ie+"ms exceeded":"timeout exceeded",_e=A("timeoutErrorMessage");return _e&&(ye=_e),new de(ye,t.clarifyTimeoutError?de.ETIMEDOUT:de.ECONNABORTED,r,F)}U.once("abort",e);let pe=()=>{L(),r.cancelToken&&r.cancelToken.unsubscribe(b),r.signal&&r.signal.removeEventListener("abort",b),U.removeAllListeners()};(r.cancelToken||r.signal)&&(r.cancelToken&&r.cancelToken.subscribe(b),r.signal&&(r.signal.aborted?b():r.signal.addEventListener("abort",b))),a((Ie,ye)=>{if(q=!0,L(),ye){j=!0,pe();return}let{data:_e}=Ie;if(_e instanceof Fi.Readable||_e instanceof Fi.Duplex){let DA=Fi.finished(_e,()=>{DA(),pe()})}else pe()});let me=mg(A("baseURL"),A("url"),A("allowAbsoluteUrls"),r),qe=R?"http://localhost":$A.hasBrowserEnv?$A.origin:void 0,Se=new URL(me,qe),Ge=Se.protocol||W2[0];if(Ge==="data:"){if(x>-1){let ye=String(A("url")||me||"");if(Y2(ye)>x)return e(new de("maxContentLength size of "+x+" exceeded",de.ERR_BAD_RESPONSE,r))}let Ie;if(k!=="GET")return po(i,e,{status:405,statusText:"method not allowed",headers:{},config:r});try{Ie=Pw(A("url"),y==="blob",{Blob:r.env&&r.env.Blob})}catch(ye){throw de.from(ye,de.ERR_BAD_REQUEST,r)}return y==="text"?(Ie=Ie.toString(m),(!m||m==="utf8")&&(Ie=J.stripBOM(Ie))):y==="stream"&&(Ie=Fi.Readable.from(Ie)),po(i,e,{data:Ie,status:200,statusText:"OK",headers:new Ct,config:r})}if(W2.indexOf(Ge)===-1)return e(new de("Unsupported protocol "+Ge,de.ERR_BAD_REQUEST,r));let je=Ct.from(r.headers).normalize();je.set("User-Agent","axios/"+sn,!1);let{onUploadProgress:Xe,onDownloadProgress:rA}=r,nA=r.maxRate,Fe,hA;if(J.isSpecCompliantForm(s)){let Ie=je.getContentType(/boundary=([-_\w\d]{10,70})/i);s=b2(s,ye=>{je.set(ye)},{tag:`axios-${sn}-boundary`,boundary:Ie&&Ie[1]||void 0})}else if(J.isFormData(s)&&J.isFunction(s.getHeaders)&&s.getHeaders!==Object.prototype.getHeaders){if(Ip(je,s.getHeaders(),A("formDataHeaderPolicy")),!je.hasContentLength())try{let Ie=await use.promisify(s.getLength).call(s);Number.isFinite(Ie)&&Ie>=0&&je.setContentLength(Ie)}catch{}}else if(J.isBlob(s)||J.isFile(s))s.size&&je.setContentType(s.type||"application/octet-stream"),je.setContentLength(s.size||0),s=Fi.Readable.from(pu(s));else if(s&&!J.isStream(s)){if(!Buffer.isBuffer(s))if(J.isArrayBuffer(s))s=Buffer.from(new Uint8Array(s));else if(J.isString(s))s=Buffer.from(s,"utf-8");else return e(new de("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",de.ERR_BAD_REQUEST,r));if(je.setContentLength(s.length,!1),K>-1&&s.length>K)return e(new de("Request body larger than maxBodyLength limit",de.ERR_BAD_REQUEST,r))}let Ce=J.toFiniteNumber(je.getContentLength());J.isArray(nA)?(Fe=nA[0],hA=nA[1]):Fe=hA=nA,s&&(Xe||Fe)&&(J.isStream(s)||(s=Fi.Readable.from(s,{objectMode:!1})),s=Fi.pipeline([s,new Lw({maxRate:J.toFiniteNumber(Fe)})],J.noop),Xe&&s.on("progress",X2(s,hI(Ce,gn(dI(Xe,J2),!1,3)))));let ce,Ye=A("auth");if(Ye){let Ie=J.getSafeProp(Ye,"username")||"",ye=J.getSafeProp(Ye,"password")||"";ce=Ie+":"+ye}if(!ce&&(Se.username||Se.password)){let Ie=Z2(Se.username),ye=Z2(Se.password);ce=Ie+":"+ye}ce&&je.delete("authorization");let ve;try{ve=yg(Se.pathname+Se.search,A("params"),A("paramsSerializer")).replace(/^\?/,"")}catch(Ie){return e(de.from(Ie,de.ERR_BAD_REQUEST,r,null,null,{url:A("url"),exists:!0}))}je.set("Accept-Encoding",J.hasOwnProp(t,"advertiseZstdAcceptEncoding")&&t.advertiseZstdAcceptEncoding===!0?yse:iU,!1);let ue=Object.assign(Object.create(null),{path:ve,method:k,headers:aI(je),agents:{http:B,https:Q},auth:ce,protocol:Ge,family:c,beforeRedirect:Nse,beforeRedirects:Object.create(null),http2Options:p});if(!J.isUndefined(g)&&(ue.lookup=g),R){if(typeof R!="string")return e(new de("socketPath must be a string",de.ERR_BAD_OPTION_VALUE,r));let Ie=A("allowedSocketPaths");if(Ie!=null){let ye=Array.isArray(Ie)?Ie:[Ie],_e=x2(R);if(!ye.some(Te=>typeof Te=="string"&&x2(Te)===_e))return e(new de(`socketPath "${R}" is not permitted by allowedSocketPaths`,de.ERR_BAD_OPTION_VALUE,r))}ue.socketPath=R}else ue.hostname=Se.hostname.startsWith("[")?Se.hostname.slice(1,-1):Se.hostname,ue.port=Se.port,nU(ue,f,Ge+"//"+Se.hostname+(Se.port?":"+Se.port:"")+ue.path,!1,Q,B);let aA,iA=!1,$e=!1,Ue=Vw.test(ue.protocol);if(ue.agent==null&&(ue.agent=Ue?Q:B),V)aA=Gse;else{let Ie=A("transport");if(Ie)aA=Ie;else if(G===0)aA=Ue?AU:eU,iA=!0;else{$e=!0,ue.sensitiveHeaders=[],G&&(ue.maxRedirects=G);let ye=A("beforeRedirect");if(ye&&(ue.beforeRedirects.config=ye),ce){let DA=Se.origin,Te=ce;ue.beforeRedirects.auth=function(zA){try{new URL(zA.href).origin===DA&&(zA.auth=Te)}catch{}}}let _e=A("sensitiveHeaders");if(_e!=null){if(!J.isArray(_e))return e(new de("sensitiveHeaders must be an array of strings",de.ERR_BAD_OPTION_VALUE,r));let DA=new Set;for(let Te of _e){if(!J.isString(Te))return e(new de("sensitiveHeaders must be an array of strings",de.ERR_BAD_OPTION_VALUE,r));DA.add(Te.toLowerCase())}DA.size&&(ue.sensitiveHeaders=Array.from(DA),ue.beforeRedirects.sensitiveHeaders=function(OA,zA){Rse(OA,zA)||Tse(OA.headers,DA)})}aA=Ue?Sse:mse}}K>-1?ue.maxBodyLength=K:ue.maxBodyLength=1/0,ue.insecureHTTPParser=!!A("insecureHTTPParser"),F=aA.request(ue,function(ye){if(L(),F.destroyed)return;let _e=[ye],DA=J.toFiniteNumber(ye.headers["content-length"]);if(rA||hA){let BA=new Lw({maxRate:J.toFiniteNumber(hA)});rA&&BA.on("progress",X2(BA,hI(DA,gn(dI(rA,J2),!0,3)))),_e.push(BA)}let Te=ye,OA=ye.req||F;if(H!==!1&&ye.headers["content-encoding"])switch((k==="HEAD"||ye.statusCode===204)&&delete ye.headers["content-encoding"],(ye.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":_e.push(ni.createUnzip(j2)),delete ye.headers["content-encoding"];break;case"deflate":_e.push(new _2),_e.push(ni.createUnzip(j2)),delete ye.headers["content-encoding"];break;case"br":rU&&(_e.push(ni.createBrotliDecompress(Qse)),delete ye.headers["content-encoding"]);break;case"zstd":aU&&(_e.push(ni.createZstdDecompress(fse)),delete ye.headers["content-encoding"]);break}Te=_e.length>1?Fi.pipeline(_e,J.noop):_e[0];let zA={status:ye.statusCode,statusText:ye.statusMessage,headers:new Ct(ye.headers),config:r,request:OA};if(y==="stream"){if(x>-1){let BA=x,rt=Te;async function*Jt(){let NA=0;for await(let oe of rt){if(NA+=oe.length,NA>BA)throw new de("maxContentLength size of "+BA+" exceeded",de.ERR_BAD_RESPONSE,r,OA);yield oe}}Te=Fi.Readable.from(Jt(),{objectMode:!1})}zA.data=Te,po(i,e,zA)}else{let BA=[],rt=0;Te.on("data",function(NA){BA.push(NA),rt+=NA.length,x>-1&&rt>x&&(j=!0,Te.destroy(),b(new de("maxContentLength size of "+x+" exceeded",de.ERR_BAD_RESPONSE,r,OA)))}),Te.on("aborted",function(){if(j)return;let NA=new de("stream has been aborted",de.ERR_BAD_RESPONSE,r,OA,zA);Te.destroy(NA),e(NA)}),Te.on("error",function(NA){j||e(de.from(NA,null,r,OA,zA))}),Te.on("end",function(){try{let NA=BA.length===1?BA[0]:Buffer.concat(BA);y!=="arraybuffer"&&(NA=NA.toString(m),(!m||m==="utf8")&&(NA=J.stripBOM(NA))),zA.data=NA}catch(NA){return e(de.from(NA,null,r,zA.request,zA))}po(i,e,zA)})}U.once("abort",BA=>{Te.destroyed||(Te.emit("error",BA),Te.destroy())})}),U.once("abort",Ie=>{F.close?F.close():F.destroy(Ie)}),F.on("error",function(ye){e(de.from(ye,null,r,F))});let yA=new Set;if(F.on("socket",function(ye){typeof ye.setKeepAlive=="function"&&ye.setKeepAlive(!0,1e3*60),ye[q2]||(ye.on("error",function(DA){let Te=ye[Cu];Te&&!Te.destroyed&&Te.destroy(DA)}),ye[q2]=!0),ye[Cu]=F,yA.add(ye)}),F.once("close",function(){L();for(let ye of yA)ye[Cu]===F&&(ye[Cu]=null);yA.clear()}),A("timeout")){let Ie=parseInt(A("timeout"),10);if(Number.isNaN(Ie)){b(new de("error trying to parse `config.timeout` to int",de.ERR_BAD_OPTION_VALUE,r,F));return}let ye=function(){q||b(X())};iA&&Ie>0&&(T=setTimeout(ye,Ie)),F.setTimeout(Ie,ye)}else F.setTimeout(0);if(J.isStream(s)){let Ie=!1,ye=!1;s.on("end",()=>{Ie=!0}),s.once("error",DA=>{ye=!0,F.destroy(DA)}),s.on("close",()=>{!Ie&&!ye&&b(new va("Request stream has been aborted",r,F))});let _e=s;if(K>-1&&!$e){let DA=K,Te=0;_e=Fi.pipeline([s,new Fi.Transform({transform(OA,zA,BA){if(Te+=OA.length,Te>DA)return BA(new de("Request body larger than maxBodyLength limit",de.ERR_BAD_REQUEST,r,F));BA(null,OA)}})],J.noop),_e.on("error",OA=>{F.destroyed||F.destroy(OA)})}_e.pipe(F)}else s&&F.write(s),F.end()})};var gU=$A.hasStandardBrowserEnv?((n,r)=>o=>(o=new URL(o,$A.origin),n.protocol===o.protocol&&n.host===o.host&&(r||n.port===o.port)))(new URL($A.origin),$A.navigator&&/(msie|trident)/i.test($A.navigator.userAgent)):()=>!0;var cU=$A.hasStandardBrowserEnv?{write(n,r,o,i,e,a,A){if(typeof document>"u")return;let t=[`${n}=${encodeURIComponent(r)}`];J.isNumber(o)&&t.push(`expires=${new Date(o).toUTCString()}`),J.isString(i)&&t.push(`path=${i}`),J.isString(e)&&t.push(`domain=${e}`),a===!0&&t.push("secure"),J.isString(A)&&t.push(`SameSite=${A}`),document.cookie=t.join("; ")},read(n){if(typeof document>"u")return null;let r=document.cookie.split(";");for(let o=0;on instanceof Ct?{...n}:n,Fse=n=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(n).concat(Object.getOwnPropertySymbols(n).filter(r=>Object.getOwnPropertyDescriptor(n,r).enumerable)):Object.keys(n);function Li(n,r){n=n||{},r=r||{};let o=Object.create(null);Object.defineProperty(o,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function i(c,l,p,B){return J.isPlainObject(c)&&J.isPlainObject(l)?J.merge.call({caseless:B},c,l):J.isPlainObject(l)?J.merge({},l):J.isArray(l)?l.slice():l}function e(c,l,p,B){if(J.isUndefined(l)){if(!J.isUndefined(c))return i(void 0,c,p,B)}else return i(c,l,p,B)}function a(c,l){if(!J.isUndefined(l))return i(void 0,l)}function A(c,l){if(J.isUndefined(l)){if(!J.isUndefined(c))return i(void 0,c)}else return i(void 0,l)}function t(c){let l=J.hasOwnProp(r,"transitional")?r.transitional:void 0;if(!J.isUndefined(l))if(J.isPlainObject(l)){if(J.hasOwnProp(l,c))return l[c]}else return;let p=J.hasOwnProp(n,"transitional")?n.transitional:void 0;if(J.isPlainObject(p)&&J.hasOwnProp(p,c))return p[c]}function s(c,l,p){if(J.hasOwnProp(r,p))return i(c,l);if(J.hasOwnProp(n,p))return i(void 0,c)}let g={url:a,method:a,data:a,baseURL:A,transformRequest:A,transformResponse:A,paramsSerializer:A,timeout:A,timeoutMessage:A,withCredentials:A,withXSRFToken:A,adapter:A,responseType:A,xsrfCookieName:A,xsrfHeaderName:A,onUploadProgress:A,onDownloadProgress:A,decompress:A,maxContentLength:A,maxBodyLength:A,beforeRedirect:A,transport:A,httpAgent:A,httpsAgent:A,cancelToken:A,socketPath:A,allowedSocketPaths:A,responseEncoding:A,validateStatus:s,headers:(c,l,p)=>e(IU(c),IU(l),p,!0)};return J.forEach(Fse({...n,...r}),function(l){if(l==="__proto__"||l==="constructor"||l==="prototype")return;let p=J.hasOwnProp(g,l)?g[l]:e,B=J.hasOwnProp(n,l)?n[l]:void 0,Q=J.hasOwnProp(r,l)?r[l]:void 0,f=p(B,Q,l);J.isUndefined(f)&&p!==s||(o[l]=f)}),J.hasOwnProp(r,"validateStatus")&&J.isUndefined(r.validateStatus)&&t("validateStatusUndefinedResolves")===!1&&(J.hasOwnProp(n,"validateStatus")?o.validateStatus=i(void 0,n.validateStatus):delete o.validateStatus),o}var Lse=n=>encodeURIComponent(n).replace(/%([0-9A-F]{2})/gi,(r,o)=>String.fromCharCode(parseInt(o,16)));function Use(n){let r=Li({},n),o=p=>J.hasOwnProp(r,p)?r[p]:void 0,i=o("data"),e=o("withXSRFToken"),a=o("xsrfHeaderName"),A=o("xsrfCookieName"),t=o("headers"),s=o("auth"),g=o("baseURL"),c=o("allowAbsoluteUrls"),l=o("url");if(r.headers=t=Ct.from(t),r.url=yg(mg(g,l,c,r),o("params"),o("paramsSerializer")),s){let p=J.getSafeProp(s,"username")||"",B=J.getSafeProp(s,"password")||"";try{t.set("Authorization","Basic "+btoa(p+":"+(B?Lse(B):"")))}catch(Q){throw de.from(Q,de.ERR_BAD_OPTION_VALUE,n)}}if(J.isFormData(i)&&($A.hasStandardBrowserEnv||$A.hasStandardBrowserWebWorkerEnv||J.isReactNative(i)?t.setContentType(void 0):J.isFunction(i.getHeaders)&&Ip(t,i.getHeaders(),o("formDataHeaderPolicy"))),$A.hasStandardBrowserEnv&&(J.isFunction(e)&&(e=e(r)),e===!0||e==null&&gU(r.url))){let B=a&&A&&cU.read(A);B&&t.set(a,B)}return r}var hu=Use;var Hse=typeof XMLHttpRequest<"u",lU=Hse&&function(n){return new Promise(function(o,i){let e=hu(n),a=e.data,A=Ct.from(e.headers).normalize(),{responseType:t,onUploadProgress:s,onDownloadProgress:g}=e,c,l,p,B,Q;function f(){B&&B(),Q&&Q(),e.cancelToken&&e.cancelToken.unsubscribe(c),e.signal&&e.signal.removeEventListener("abort",c)}let y=new XMLHttpRequest;y.open(e.method.toUpperCase(),e.url,!0),y.timeout=e.timeout;function m(){if(!y)return;let k=Ct.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),K={data:!t||t==="text"||t==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:k,config:n,request:y};po(function(H){o(H),f()},function(H){i(H),f()},K),y=null}"onloadend"in y?y.onloadend=m:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.startsWith("file:"))||setTimeout(m)},y.onabort=function(){y&&(i(new de("Request aborted",de.ECONNABORTED,n,y)),f(),y=null)},y.onerror=function(G){let K=G&&G.message?G.message:"Network Error",x=new de(K,de.ERR_NETWORK,n,y);x.event=G||null,i(x),f(),y=null},y.ontimeout=function(){let G=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",K=e.transitional||os;e.timeoutErrorMessage&&(G=e.timeoutErrorMessage),i(new de(G,K.clarifyTimeoutError?de.ETIMEDOUT:de.ECONNABORTED,n,y)),f(),y=null},a===void 0&&A.setContentType(null),"setRequestHeader"in y&&J.forEach(aI(A),function(G,K){y.setRequestHeader(K,G)}),J.isUndefined(e.withCredentials)||(y.withCredentials=!!e.withCredentials),t&&t!=="json"&&(y.responseType=e.responseType),g&&([p,Q]=gn(g,!0),y.addEventListener("progress",p)),s&&y.upload&&([l,B]=gn(s),y.upload.addEventListener("progress",l),y.upload.addEventListener("loadend",B)),(e.cancelToken||e.signal)&&(c=k=>{y&&(i(!k||k.type?new va(null,n,y):k),y.abort(),f(),y=null)},e.cancelToken&&e.cancelToken.subscribe(c),e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c)));let R=cp(e.url);if(R&&!$A.protocols.includes(R)){i(new de("Unsupported protocol "+R+":",de.ERR_BAD_REQUEST,n)),f();return}y.send(a||null)})};var Kse=(n,r)=>{if(n=n?n.filter(Boolean):[],!r&&!n.length)return;let o=new AbortController,i=!1,e=function(s){if(!i){i=!0,A();let g=s instanceof Error?s:this.reason;o.abort(g instanceof de?g:new va(g instanceof Error?g.message:g))}},a=r&&setTimeout(()=>{a=null,e(new de(`timeout of ${r}ms exceeded`,de.ETIMEDOUT))},r),A=()=>{n&&(a&&clearTimeout(a),a=null,n.forEach(s=>{s.unsubscribe?s.unsubscribe(e):s.removeEventListener("abort",e)}),n=null)};n.forEach(s=>{if(!i){if(s.aborted){e.call(s);return}s.addEventListener("abort",e,{once:!0})}});let{signal:t}=o;return t.unsubscribe=()=>J.asap(A),t},EU=Kse;var Yse=function*(n,r){let o=n.byteLength;if(!r||o{let e=xse(n,r),a=0,A,t=s=>{A||(A=!0,i&&i(s))};return new ReadableStream({async pull(s){try{let{done:g,value:c}=await e.next();if(g){t(),s.close();return}let l=c.byteLength;if(o){let p=a+=l;o(p)}s.enqueue(new Uint8Array(c))}catch(g){throw t(g),g}},cancel(s){return t(s),e.return()}},{highWaterMark:2})};var pU=64*1024,{isFunction:du}=J,Jse=n=>encodeURIComponent(n).replace(/%([0-9A-F]{2})/gi,(r,o)=>String.fromCharCode(parseInt(o,16))),CU=n=>{if(!J.isString(n))return n;try{return decodeURIComponent(n)}catch{return n}},hU=(n,...r)=>{try{return!!n(...r)}catch{return!1}},qse=n=>{let r=n.indexOf("://"),o=n;return r!==-1&&(o=o.slice(r+3)),o.includes("@")||o.includes(":")},Vse=n=>{let r=J.global!==void 0&&J.global!==null?J.global:globalThis,{ReadableStream:o,TextEncoder:i}=r;n=J.merge.call({skipUndefined:!0},{Request:r.Request,Response:r.Response},n);let{fetch:e,Request:a,Response:A}=n,t=e?du(e):typeof fetch=="function",s=du(a),g=du(A);if(!t)return!1;let c=t&&du(o),l=t&&(typeof i=="function"?(m=>R=>m.encode(R))(new i):async m=>new Uint8Array(await new a(m).arrayBuffer())),p=s&&c&&hU(()=>{let m=!1,R=new a($A.origin,{body:new o,method:"POST",get duplex(){return m=!0,"half"}}),k=R.headers.has("Content-Type");return R.body!=null&&R.body.cancel(),m&&!k}),B=g&&c&&hU(()=>J.isReadableStream(new A("").body)),Q={stream:B&&(m=>m.body)};t&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!Q[m]&&(Q[m]=(R,k)=>{let G=R&&R[m];if(G)return G.call(R);throw new de(`Response type '${m}' is not supported`,de.ERR_NOT_SUPPORT,k)})});let f=async m=>{if(m==null)return 0;if(J.isBlob(m))return m.size;if(J.isSpecCompliantForm(m))return(await new a($A.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(J.isArrayBufferView(m)||J.isArrayBuffer(m))return m.byteLength;if(J.isURLSearchParams(m)&&(m=m+""),J.isString(m))return(await l(m)).byteLength},y=async(m,R)=>{let k=J.toFiniteNumber(m.getContentLength());return k??f(R)};return async m=>{let{url:R,method:k,data:G,signal:K,cancelToken:x,timeout:H,onDownloadProgress:q,onUploadProgress:j,responseType:F,headers:T,withCredentials:V="same-origin",fetchOptions:U,maxContentLength:b,maxBodyLength:L}=hu(m),X=J.isNumber(b)&&b>-1,pe=J.isNumber(L)&&L>-1,me=Fe=>J.hasOwnProp(m,Fe)?m[Fe]:void 0,qe=e||fetch;F=F?(F+"").toLowerCase():"text";let Se=EU([K,x&&x.toAbortSignal()],H),Ge=null,je=Se&&Se.unsubscribe&&(()=>{Se.unsubscribe()}),Xe,rA=null,nA=()=>new de("Request body larger than maxBodyLength limit",de.ERR_BAD_REQUEST,m,Ge);try{let Fe,hA=me("auth");if(hA){let Ue=J.getSafeProp(hA,"username")||"",yA=J.getSafeProp(hA,"password")||"";Fe={username:Ue,password:yA}}if(qse(R)){let Ue=new URL(R,$A.origin);if(!Fe&&(Ue.username||Ue.password)){let yA=CU(Ue.username),Ie=CU(Ue.password);Fe={username:yA,password:Ie}}(Ue.username||Ue.password)&&(Ue.username="",Ue.password="",R=Ue.href)}if(Fe&&(T.delete("authorization"),T.set("Authorization","Basic "+btoa(Jse((Fe.username||"")+":"+(Fe.password||""))))),X&&typeof R=="string"&&R.startsWith("data:")&&Jw(R)>b)throw new de("maxContentLength size of "+b+" exceeded",de.ERR_BAD_RESPONSE,m,Ge);if(pe&&k!=="get"&&k!=="head"){let Ue=await f(G);if(typeof Ue=="number"&&isFinite(Ue)&&(Xe=Ue,Ue>L))throw nA()}let Ce=pe&&(J.isReadableStream(G)||J.isStream(G)),ce=(Ue,yA,Ie)=>zw(Ue,pU,ye=>{if(pe&&ye>L)throw rA=nA();yA&&yA(ye)},Ie);if(p&&k!=="get"&&k!=="head"&&(j||Ce)){if(Xe=Xe??await y(T,G),Xe!==0||Ce){let Ue=new a(R,{method:"POST",body:G,duplex:"half"}),yA;if(J.isFormData(G)&&(yA=Ue.headers.get("content-type"))&&T.setContentType(yA),Ue.body){let[Ie,ye]=j&&hI(Xe,gn(dI(j)))||[];G=ce(Ue.body,Ie,ye)}}}else if(Ce&&!s&&c&&k!=="get"&&k!=="head")G=ce(G);else if(Ce&&s&&!p&&k!=="get"&&k!=="head")throw new de("Stream request bodies are not supported by the current fetch implementation",de.ERR_NOT_SUPPORT,m,Ge);J.isString(V)||(V=V?"include":"omit");let Ye=s&&"credentials"in a.prototype;if(J.isFormData(G)){let Ue=T.getContentType();Ue&&/^multipart\/form-data/i.test(Ue)&&!/boundary=/i.test(Ue)&&T.delete("content-type")}T.set("User-Agent","axios/"+sn,!1);let ve={...U,signal:Se,method:k.toUpperCase(),headers:aI(T.normalize()),body:G,duplex:"half",credentials:Ye?V:void 0};Ge=s&&new a(R,ve);let ue=await(s?qe(Ge,U):qe(R,ve)),aA=Ct.from(ue.headers);if(X){let Ue=J.toFiniteNumber(aA.getContentLength());if(Ue!=null&&Ue>b)throw new de("maxContentLength size of "+b+" exceeded",de.ERR_BAD_RESPONSE,m,Ge)}let iA=B&&(F==="stream"||F==="response");if(B&&ue.body&&(q||X||iA&&je)){let Ue={};["status","statusText","headers"].forEach(Te=>{Ue[Te]=ue[Te]});let yA=J.toFiniteNumber(aA.getContentLength()),[Ie,ye]=q&&hI(yA,gn(dI(q),!0))||[],_e=0,DA=Te=>{if(X&&(_e=Te,_e>b))throw new de("maxContentLength size of "+b+" exceeded",de.ERR_BAD_RESPONSE,m,Ge);Ie&&Ie(Te)};ue=new A(zw(ue.body,pU,DA,()=>{ye&&ye(),je&&je()}),Ue)}F=F||"text";let $e=await Q[J.findKey(Q,F)||"text"](ue,m);if(X&&!B&&!iA){let Ue;if($e!=null&&(typeof $e.byteLength=="number"?Ue=$e.byteLength:typeof $e.size=="number"?Ue=$e.size:typeof $e=="string"&&(Ue=typeof i=="function"?new i().encode($e).byteLength:$e.length)),typeof Ue=="number"&&Ue>b)throw new de("maxContentLength size of "+b+" exceeded",de.ERR_BAD_RESPONSE,m,Ge)}return!iA&&je&&je(),await new Promise((Ue,yA)=>{po(Ue,yA,{data:$e,headers:Ct.from(ue.headers),status:ue.status,statusText:ue.statusText,config:m,request:Ge})})}catch(Fe){if(je&&je(),Se&&Se.aborted&&Se.reason instanceof de){let hA=Se.reason;throw hA.config=m,Ge&&(hA.request=Ge),Fe!==hA&&Object.defineProperty(hA,"cause",{__proto__:null,value:Fe,writable:!0,enumerable:!1,configurable:!0}),hA}if(rA)throw Ge&&!rA.request&&(rA.request=Ge),rA;if(Fe instanceof de)throw Ge&&!Fe.request&&(Fe.request=Ge),Fe;if(Fe&&Fe.name==="TypeError"&&/Load failed|fetch/i.test(Fe.message)){let hA=new de("Network Error",de.ERR_NETWORK,m,Ge,Fe&&Fe.response);throw Object.defineProperty(hA,"cause",{__proto__:null,value:Fe.cause||Fe,writable:!0,enumerable:!1,configurable:!0}),hA}throw de.from(Fe,Fe&&Fe.code,m,Ge,Fe&&Fe.response)}}},zse=new Map,Ww=n=>{let r=n&&n.env||{},{fetch:o,Request:i,Response:e}=r,a=[i,e,o],A=a.length,t=A,s,g,c=zse;for(;t--;)s=a[t],g=c.get(s),g===void 0&&c.set(s,g=t?new Map:Vse(r)),c=g;return g},u3e=Ww();var Zw={http:sU,xhr:lU,fetch:{get:Ww}};J.forEach(Zw,(n,r)=>{if(n){try{Object.defineProperty(n,"name",{__proto__:null,value:r})}catch{}Object.defineProperty(n,"adapterName",{__proto__:null,value:r})}});var dU=n=>`- ${n}`,Zse=n=>J.isFunction(n)||n===null||n===!1;function Xse(n,r){n=J.isArray(n)?n:[n];let{length:o}=n,i,e,a={};for(let A=0;A`adapter ${s} `+(g===!1?"is not supported by the environment":"is not available in the build")),t=o?A.length>1?`since : @@ -178,24 +178,24 @@ ${a.join(` `,r);ethis.#S(r,o)).then(()=>this.#v(o,e,"DONE")).catch(s=>this.#d(r,o,e,s)).finally(()=>this.#I.delete(o));let a=this.#n.get(i),A=this.#i.claimReply({key:i,actor:YB(r),messageId:o,text:aC(r)??"",addressed:r?.message?.chat_type==="p2p"||Array.isArray(r?.message?.mentions)&&r.message.mentions.length>0,hasPendingQuestion:!!a,questionCompletion:a?.submitting||a?.claimedReplyMessageId?a.queue:null,isQuestionPending:()=>this.#n.has(i),send:t=>this.#b(r.message.chat_id,t)});if(A){let t=A.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#o.lastMessageAt=new Date().toISOString(),this.#o.messagesReceived+=1,!0)),s;return s=t.then(()=>this.#v(o,e,"DONE")).catch(g=>this.#d(r,o,e,g)).finally(()=>{this.#I.delete(o),this.#a.delete(s)}),this.#a.add(s),s}if(a&&YB(r)!==a.actor)return this.#C(r,o,i,e);if(a?.submitting||a?.claimedReplyMessageId)return this.#C(r,o,i,e);if(a){Sue(r,a)&&(a.claimedReplyMessageId=o);let s=(a.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#y(r,o,i,a,e));a.queue=s;let g=()=>{a.claimedReplyMessageId===o&&(a.claimedReplyMessageId=null),a.queue===s&&(a.queue=null)},c;return c=s.then(()=>(g(),this.#v(o,e,"DONE")),l=>(g(),this.#d(r,o,e,l))).finally(()=>{g(),this.#I.delete(o),this.#a.delete(c)}),this.#a.add(c),c}return this.#C(r,o,i,e)}#C(r,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,finalize:t=!0}={}){let g=(this.#g.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,i,{alreadyRecorded:A})),c=t?g.then(()=>this.#v(o,e,"DONE")).catch(p=>this.#d(r,o,e,p)):g,l;return l=c.finally(()=>{a&&this.#I.delete(o),this.#g.get(i)===l&&this.#g.delete(i)}),this.#g.set(i,l),l}async#d(r,o,i,e){if(this.#h?.aborted){await this.#k(o,i);return}this.#p.error?.("[dsh-feishu] message handling failed:",e?.message??String(e)),this.#o.lastError=e?.message??String(e),await this.#v(o,i,"ERROR"),await this.#b(r.message.chat_id,Za(e)??"\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002\u5982\u679C\u95EE\u9898\u6301\u7EED\uFF0C\u8BF7\u5728 DeepSeek Harness \u7684\u98DE\u4E66\u63D2\u4EF6\u9875\u9762\u68C0\u67E5\u8FDE\u63A5\u72B6\u6001\u3002").catch(()=>{})}async waitForIdle(){await Promise.allSettled([...this.#g.values(),...[...this.#n.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#a])}async#Q(r,o,{alreadyRecorded:i=!1}={}){this.#h?.throwIfAborted();let e=r.message.message_id;if(!i){if(this.#r.hasSeen(e))return;await this.#r.markSeen(e),this.#o.lastMessageAt=new Date().toISOString(),this.#o.messagesReceived+=1}let a=S1(r,this.#e),A=a.content,t=Mr(a),s=r.message.message_type==="text"&&!t?A:null;if(!A&&!t){await this.#b(r.message.chat_id,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002");return}if(s==="/help"){await this.#b(r.message.chat_id,mue);return}if(s==="/new"){await this.#r.clearSession(o),await this.#b(r.message.chat_id,"\u5DF2\u5F00\u542F\u5168\u65B0 Harness \u4F1A\u8BDD\u3002");return}if(s==="/status"){await this.#t.ensureRunning({signal:this.#h}),await this.#b(r.message.chat_id,"\u98DE\u4E66\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002");return}let g=s===null?null:await ti(A,this.#t,o);if(g){for(let l of g.messages??[g.message])await this.#b(r.message.chat_id,l);return}let c=s===null?null:await Ai(s,this.#t,this.#r,o,{signal:this.#h});if(c){await this.#b(r.message.chat_id,c.message);return}this.#p.info?.(`[dsh-feishu] processing ${r.message.chat_type} message ${e}`);try{await this.#B(r,o,a),this.#o.messagesReplied+=1,this.#o.lastReplyAt=new Date().toISOString(),this.#o.lastError=null}finally{await this.#F(o),await this.#i.closeRoute(o)}}#u(r,o){return{timeoutMs:this.#l,signal:this.#h,onInteraction:i=>this.#f(i,{key:o,actor:YB(r),chatId:r.message.chat_id,requiresMention:r.message.chat_type!=="p2p"}),onInteractionResolved:i=>this.#D(i)}}async#B(r,o,i){let e=r.message.chat_id,a=r.message.message_id,A=i.content,t=Mr(i)?await Wa(i,{signal:this.#h}):void 0;if(!this.#A?.stream){let{answer:c}=await ha({harness:this.#t,state:this.#r,key:o,text:A,content:t,createOptions:{signal:this.#h},existsOptions:{signal:this.#h},askOptions:this.#u(r,o)});for(let l of HB(c))await this.#b(e,l);this.#o.streamFallbacks=(this.#o.streamFallbacks??0)+1;return}let s=!1,g="";try{await this.#A.stream(e,{markdown:async c=>{s=!0;let l={...this.#u(r,o),onUpdate:async p=>{await c.setContent(this.#T(p)),this.#o.streamUpdates=(this.#o.streamUpdates??0)+1}};({answer:g}=await ha({harness:this.#t,state:this.#r,key:o,text:A,content:t,createOptions:{signal:this.#h},existsOptions:{signal:this.#h},askOptions:l})),await c.setContent(g)}},{replyTo:a}),this.#o.streamResponses=(this.#o.streamResponses??0)+1}catch(c){if(this.#o.streamErrors=(this.#o.streamErrors??0)+1,g){this.#p.warn?.("[dsh-feishu] native stream failed after generation; sending final text:",c.message);for(let p of HB(g))await this.#b(e,p);this.#o.streamFallbacks=(this.#o.streamFallbacks??0)+1;return}if(s)throw c;this.#p.warn?.("[dsh-feishu] native stream unavailable; using text fallback:",c.message);let{answer:l}=await ha({harness:this.#t,state:this.#r,key:o,text:A,content:t,createOptions:{signal:this.#h},existsOptions:{signal:this.#h},askOptions:this.#u(r,o)});for(let p of HB(l))await this.#b(e,p);this.#o.streamFallbacks=(this.#o.streamFallbacks??0)+1}}async#y(r,o,i,e,a){this.#h?.throwIfAborted();let A=this.#n.get(i),t=e.claimedReplyMessageId===o;if(!A||A!==e||A.submitting)return this.#N(r,i)?this.#S(r,o):t&&(!A||A!==e)?this.#S(r,o):this.#C(r,o,i,a,{releaseMessageId:!1,finalize:!1});if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#o.lastMessageAt=new Date().toISOString(),this.#o.messagesReceived+=1;let s=aC(r);if(!s){await this.#b(r.message.chat_id,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002");return}let g=this.#n.get(i);if(!g||g!==e||g.submitting){if(this.#N(r,i)){await this.#b(r.message.chat_id,KB).catch(()=>{});return}if(t&&(!g||g!==e)){await this.#b(r.message.chat_id,KB);return}return this.#C(r,o,i,a,{releaseMessageId:!1,alreadyRecorded:!0,finalize:!1})}if(g.chatId=r.message.chat_id,g.needsPresentation){try{await this.#m(g)}catch{this.#o.lastError="\u98DE\u4E66\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#p.error?.("[dsh-feishu] failed to retry an interaction question"),g.interaction.reconnect?.()}return}let c=g.questions[g.index];if(c){if(g.answers.push(ei(c,s)),g.index+=1,g.index{});return}g.submitting=!1,g.answers.pop(),g.index-=1,this.#o.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#p.error?.("[dsh-feishu] failed to answer a Harness interaction"),await this.#b(r.message.chat_id,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#f(r,{key:o,actor:i,chatId:e,requiresMention:a}){if(await this.#i.handleRequested(r,{key:o,actor:i,requiresMention:a,send:c=>this.#b(e,c)})||r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#p.warn?.("[dsh-feishu] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.respond({ok:!1,error:{code:"cancelled",message:"Feishu safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#b(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002").catch(()=>{});return}let s=this.#n.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#m(s);return}if(this.#E.has(t))return;if(s){await r.respond({ok:!1,error:{code:"cancelled",message:"Feishu is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,key:o,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,questionMessageIds:new Set,inactive:!1};this.#n.set(o,g),this.#E.set(g.interactionId,o),await this.#m(g)}async#D(r){if(await this.#i.handleResolved(r))return;let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#E.get(o);if(!i)return;let e=this.#n.get(i);e&&this.#w(i,e),this.#M(i,o)}async#m(r){let o=r.questions[r.index];if(!o)return;let i=await this.#b(r.chatId,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention}));i&&(r.questionMessageIds.add(i),r.inactive&&this.#w(r.key,r)),r.needsPresentation=!1}#w(r,o){let i=Date.now()+yue;for(let e of o.questionMessageIds??[])this.#s.set(e,{key:r,expiresAt:i})}#N(r,o){let i=Date.now();for(let[e,a]of this.#s)a.expiresAt<=i&&this.#s.delete(e);for(let e of[r?.message?.parent_id,r?.message?.root_id]){let a=this.#s.get(e);if(a?.key===o&&a.expiresAt>i)return!0}return!1}async#S(r,o){this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#o.lastMessageAt=new Date().toISOString(),this.#o.messagesReceived+=1,await this.#b(r.message.chat_id,KB).catch(()=>{}))}#O(r,o){let i=this.#n.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#n.delete(r),this.#E.delete(i.interactionId),i.inactive=!0,i)}#M(r,o){return this.#O(r,o)!==null}async#F(r){let o=this.#O(r);if(!(!o||o.kind!=="question")){this.#w(r,o);try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Feishu interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#p.warn?.("[dsh-feishu] failed to cancel a pending Harness interaction")}}}#T(r){return r.type==="text"&&r.text?r.text:r.type==="tool"?r.name==="web_search"?"_\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\u5E76\u6574\u7406\u4FE1\u606F\u2026_":`_\u6B63\u5728\u4F7F\u7528 ${r.name||"\u5DE5\u5177"}\u2026_`:`_${r.text||"\u6B63\u5728\u5904\u7406\u2026"}_`}async#L(r,o){if(!this.#A?.addReaction)return null;try{let i=await this.#A.addReaction(r,o);return this.#o.reactionsAdded=(this.#o.reactionsAdded??0)+1,i}catch(i){return this.#o.reactionErrors=(this.#o.reactionErrors??0)+1,this.#p.warn?.(`[dsh-feishu] unable to add ${o} reaction:`,i.message),null}}async#k(r,o){let i=await o;if(i&&this.#A?.removeReaction)try{await this.#A.removeReaction(r,i),this.#o.reactionsRemoved=(this.#o.reactionsRemoved??0)+1}catch(e){this.#o.reactionErrors=(this.#o.reactionErrors??0)+1,this.#p.warn?.("[dsh-feishu] unable to remove processing reaction:",e.message)}}async#v(r,o,i){await this.#k(r,o),await this.#L(r,i)}async#b(r,o){let i=await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:r,msg_type:"text",content:JSON.stringify({text:o})}});if(i?.code&&i.code!==0)throw new Error(`Feishu send failed: ${i.msg||i.code}`);return YI(i?.data?.message_id)}};var O1="stream_md",wue="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026";function jg(n,r){if(r?.code&&r.code!==0)throw new Error(`${n} failed: ${r.msg||r.code}`);return r}function Oue(n){let r=String(n??"").replace(/\s+/g," ").trim();return r.length<=50?r:`${r.slice(0,49)}\u2026`}function Mue(n){return{schema:"2.0",config:{streaming_mode:!0,summary:{content:"\u6B63\u5728\u751F\u6210\u2026"},streaming_config:{print_frequency_ms:{default:70},print_step:{default:1},print_strategy:"fast"}},body:{elements:[{tag:"markdown",element_id:O1,content:n}]}}}var jB=class{#e;#A;constructor({client:r,initialText:o=wue}){this.#e=r,this.#A=o}async stream(r,o,i={}){if(typeof o?.markdown!="function")throw new Error("Feishu stream requires a markdown producer");let e=null,A=jg("Feishu card.create",await this.#e.cardkit.v1.card.create({data:{type:"card_json",data:JSON.stringify(Mue(this.#A))}}))?.data?.card_id;if(!A)throw new Error("Feishu card.create returned no card_id");try{e=await this.#t(r,A,i.replyTo);let t=0,s=this.#A,g={messageId:e,setContent:async l=>{let p=String(l??"")||"\u2026";if(p===s)return;if(p.length>28e3)throw new Error("Feishu stream content exceeds 28000 characters");let B=await this.#e.cardkit.v1.cardElement.content({path:{card_id:A,element_id:O1},data:{content:p,sequence:++t,uuid:`content_${A}_${t}`}});jg("Feishu cardElement.content",B),s=p}};await o.markdown(g);let c=await this.#e.cardkit.v1.card.settings({path:{card_id:A},data:{settings:JSON.stringify({config:{streaming_mode:!1,summary:{content:Oue(s)||"\u56DE\u7B54\u5B8C\u6210"}}}),sequence:++t,uuid:`settings_${A}_${t}`}});return jg("Feishu card.settings",c),{messageId:e}}catch(t){throw e&&await this.#r(e),t}}async#t(r,o,i){let e=JSON.stringify({type:"card",data:{card_id:o}}),a=i?await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"interactive",content:e}}):await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:r,msg_type:"interactive",content:e}});jg("Feishu message send",a);let A=a?.data?.message_id;if(!A)throw new Error("Feishu message send returned no message_id");return A}async#r(r){try{let o=await this.#e.im.v1.message.delete({path:{message_id:r}});jg("Feishu message delete",o)}catch(o){console.warn("[bridge] unable to recall a failed streaming card:",o.message)}}async addReaction(r,o){let e=jg("Feishu reaction.create",await this.#e.im.v1.messageReaction.create({path:{message_id:r},data:{reaction_type:{emoji_type:o}}}))?.data?.reaction_id;if(!e)throw new Error("Feishu reaction.create returned no reaction_id");return e}async removeReaction(r,o){jg("Feishu reaction.delete",await this.#e.im.v1.messageReaction.delete({path:{message_id:r,reaction_id:o}}))}};var bue=15e3;function _ue(n,r){if(!n||typeof n.request!="function")return;let o=i=>({...i??{},timeout:i?.timeout??r});return{request:i=>n.request(o(i)),get:(i,e)=>n.get(i,o(e)),delete:(i,e)=>n.delete(i,o(e)),head:(i,e)=>n.head(i,o(e)),options:(i,e)=>n.options(i,o(e)),post:(i,e,a)=>n.post(i,e,o(a)),put:(i,e,a)=>n.put(i,e,o(a)),patch:(i,e,a)=>n.patch(i,e,o(a))}}function Nue({allowedSenderCount:n=1}={}){return{startedAt:null,ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1,messagesReceived:0,messagesReplied:0,messagesRejected:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,streamResponses:0,streamUpdates:0,streamFallbacks:0,streamErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,agentPreset:"standard",authorizationMode:"sender-open-id-allowlist",allowedSenderCount:n}}var JB=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i;#o=null;#c=null;#l=null;#p=null;#h=null;#C;constructor({lark:r,appId:o,appSecret:i,domain:e="feishu",ownerOpenId:a,ownerOpenIds:A,harness:t,state:s,replyTimeoutMs:g=6e5,connectTimeoutMs:c=15e3,requestTimeoutMs:l=bue,logger:p=console}){if(!r)throw new Error("FeishuRuntime requires the Feishu SDK");if(!o||!i)throw new Error("FeishuRuntime requires app credentials");let B=Array.isArray(A)?A:[a],Q=[...new Set(B.filter(f=>typeof f=="string"&&f))];if(Q.length===0)throw new Error("FeishuRuntime requires at least one owner open_id");if(!t)throw new Error("FeishuRuntime requires a Harness client");if(!s)throw new Error("FeishuRuntime requires a state store");if(!Number.isFinite(l)||l<=0)throw new TypeError("FeishuRuntime requestTimeoutMs must be a positive number");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=Q,this.#n=t,this.#E=s,this.#s=g,this.#I=c,this.#a=l,this.#i=p,this.#C=Nue({allowedSenderCount:Q.length})}get status(){return structuredClone(this.#C)}async start(){return this.#l&&this.#C.ready?this.status:this.#p?this.#p:(this.#p=this.#d().finally(()=>{this.#p=null}),this.#p)}async#d(){let r=new AbortController;this.#h=r;let{signal:o}=r;this.#C.startedAt=new Date().toISOString(),this.#C.feishuLongConnectionState="connecting",this.#C.lastError=null;try{await this.#n.ensureRunning({signal:o}),this.#C.harnessReachable=!0;let i=this.#r==="lark"?this.#e.Domain.Lark:this.#e.Domain.Feishu,e={appId:this.#A,appSecret:this.#t,domain:i},a=_ue(this.#e.defaultHttpInstance,this.#a);a&&(e.httpInstance=a),this.#o=new this.#e.Client(e);let A=new jB({client:this.#o,initialText:"\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026"});this.#c=new xB({client:this.#o,channel:A,harness:this.#n,state:this.#E,status:this.#C,allowedSenderOpenIds:new Set(this.#g),replyTimeoutMs:this.#s,signal:o,logger:this.#i});let t=new this.#e.EventDispatcher({}).register({"im.message.receive_v1":l=>(this.#c.accept(l),{}),"im.message.reaction.created_v1":()=>({}),"im.message.reaction.deleted_v1":()=>({})}),s,g,c=new Promise((l,p)=>{let B=!1,Q=setTimeout(()=>{B||(B=!0,p(new Error(`Feishu WebSocket handshake timed out after ${this.#I}ms`)))},this.#I);s=()=>{B||(B=!0,clearTimeout(Q),l())},g=f=>{B||(B=!0,clearTimeout(Q),p(f))}});return this.#l=new this.#e.WSClient({...e,loggerLevel:this.#e.LoggerLevel.info,handshakeTimeoutMs:15e3,onReady:()=>{this.#C.feishuLongConnectionState="connected",this.#C.ready=!0,this.#C.lastError=null,s()},onError:l=>{this.#C.feishuLongConnectionState="failed",this.#C.ready=!1,this.#C.lastError=l?.message??String(l),this.#i.error("[dsh-feishu] Feishu long connection failed:",this.#C.lastError),g(l)},onReconnecting:()=>{this.#C.feishuLongConnectionState="reconnecting",this.#C.ready=!1},onReconnected:()=>{this.#C.feishuLongConnectionState="connected",this.#C.ready=!0,this.#C.lastError=null}}),await this.#l.start({eventDispatcher:t}).catch(l=>{g(l)}),await c,this.status}catch(i){throw this.#C.ready=!1,this.#C.feishuLongConnectionState="failed",this.#C.lastError=i?.message??String(i),await this.stop({preserveError:!0}),i}}async sendConnectionTest(r){if(!this.#C.ready||!this.#o){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}if(typeof r!="string"||!r.trim())throw new TypeError("Feishu connection test text is required");let o=async(e,a,A)=>{let t=await this.#o.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:A})}});if(t?.code&&t.code!==0)throw new Error(`Feishu connection test failed: ${t.msg||t.code}`)},i=this.#g.find(e=>e!=="*");return i?(await o("open_id",i,r),{sent:!0}):Xn({state:this.#E,text:r,channelLabel:"\u98DE\u4E66\u673A\u5668\u4EBA",send:async(e,a)=>{let A=typeof e?.chatId=="string"?e.chatId.trim():"";if(!A)throw kt("\u98DE\u4E66\u673A\u5668\u4EBA");await o("chat_id",A,a)}})}async stop({preserveError:r=!1}={}){let o=r?this.#C.lastError:null,i=this.#h;return this.#h=null,i?.abort(new DOMException("Feishu runtime stopped","AbortError")),this.#C.ready=!1,this.#l&&(this.#l.close({force:!0}),this.#l=null),this.#c&&(await this.#c.waitForIdle(),this.#c=null),this.#o=null,this.#C.feishuLongConnectionState=r?"failed":"idle",this.#C.lastError=o,this.status}};var qB=class extends qt{constructor(r){super({...r,rpcIdPrefix:"feishu",logPrefix:"dsh-feishu"})}};import{createHash as Tue}from"node:crypto";import{mkdir as Rue,readFile as kue,rename as vue,unlink as Pue,writeFile as Gue}from"node:fs/promises";import{dirname as Fue}from"node:path";var WB="DSH_FEISHU_APP_SECRET";function Do(n){return typeof n=="string"&&n.trim()?n.trim():null}function M1(n){let r=Do(n);return r&&/^[A-Za-z0-9_-]{1,128}$/.test(r)?r:null}function b1(n){return`bot_${Tue("sha256").update(n).digest("hex").slice(0,24)}`}function Lue(n){let r=Array.isArray(n.ownerOpenIds)?n.ownerOpenIds:[n.ownerOpenId];return[...new Set(r.map(Do).filter(Boolean))]}function VB(n,{legacy:r=!1}={}){if(!n||typeof n!="object")return null;let o=Do(n.appId),i=Lue(n);if(!o||i.length===0)return null;let e=M1(n.id)??(r?b1(o):null),a=Do(n.secretRef)??(r?WB:null);if(!e||!a||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))return null;let A=n.domain==="lark"?"lark":"feishu";return Object.freeze({id:e,appId:o,secretRef:a,ownerOpenIds:Object.freeze(i),domain:A,botName:Do(n.botName),botOpenId:Do(n.botOpenId),activated:n.activated??null,deletionPending:n.deletionPending===!0,connectedAt:Do(n.connectedAt),createdAt:Do(n.createdAt)??Do(n.connectedAt)})}function Uue(n){if(!n||typeof n!="object")return null;if(n.version===2&&Array.isArray(n.bots)){let o=n.bots.map(A=>VB(A));if(o.some(A=>A===null))throw new Error("dsh-feishu config contains an invalid bot entry");let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.id)||e.has(A.secretRef)||a.has(A.appId))throw new Error("dsh-feishu config contains duplicate bot identities");i.add(A.id),e.add(A.secretRef),a.add(A.appId)}return{value:Object.freeze({version:2,bots:Object.freeze(o)}),migrated:!1}}let r=VB(n,{legacy:!0});return r?{value:Object.freeze({version:2,bots:Object.freeze([r])}),migrated:!0}:null}var zB=class{#e;#A=Object.freeze({version:2,bots:Object.freeze([])});#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=JSON.parse(await kue(this.#e,"utf8")),o=Uue(r);if(!o)throw new Error("dsh-feishu config is incomplete or invalid");this.#A=o.value,o.migrated&&await this.#n(this.#A)}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=Object.freeze({version:2,bots:Object.freeze([])})}return this}get(){let r=this.#A.bots[0];if(!r)return null;let o=structuredClone(r);return o.ownerOpenId=o.ownerOpenIds[0],o}list(){return structuredClone(this.#A.bots)}getBot(r){let o=this.#A.bots.find(i=>i.id===r);return o?structuredClone(o):null}async save(r){let o={...r};o.id||(o.id=b1(Do(o.appId)??"invalid")),o.secretRef||(o.secretRef=WB);let i=VB(o);if(!i)throw new Error("Refusing to persist incomplete dsh-feishu configuration");return await this.#r([i]),this.get()}async saveBot(r){let o=VB(r);if(!o)throw new Error("Refusing to persist incomplete dsh-feishu bot configuration");return this.#g(i=>{if(i.find(t=>t.secretRef===o.secretRef&&t.id!==o.id))throw new Error("Refusing to share a credential reference between Feishu bots");if(i.find(t=>t.appId===o.appId&&t.id!==o.id))throw new Error("Refusing to persist the same Feishu app twice");let A=i.findIndex(t=>t.id===o.id);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async removeBot(r){if(!M1(r))throw new TypeError("Invalid Feishu bot id");return this.#g(o=>{let i=o.findIndex(a=>a.id===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await Pue(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=Object.freeze({version:2,bots:Object.freeze([])})});this.#t=r.then(()=>{},()=>{}),await r}async#r(r){let o=Object.freeze({version:2,bots:Object.freeze([...r])}),i=this.#t.then(async()=>{await this.#n(o),this.#A=o});this.#t=i.then(()=>{},()=>{}),await i}async#g(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#n(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#n(r){await Rue(Fue(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await Gue(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await vue(o,this.#e)}};import{randomUUID as k1}from"node:crypto";var ON=new Set(["starting","qr_ready","polling","slow_down","domain_switched","saving"]),Hue=new Set(["polling","slow_down","domain_switched"]),Sa=Object.freeze({IDLE:"idle",STARTING:"starting",QR_READY:"qr_ready",POLLING:"polling",SLOW_DOWN:"slow_down",DOMAIN_SWITCHED:"domain_switched",SAVING:"saving",SUCCEEDED:"succeeded",EXPIRED:"expired",CANCELLED:"cancelled",ERROR:"error"});function _1(n){return["access_denied","expired_token","abort"].includes(n?.code)?n.code:"registration_failed"}function MN(n){let r=_1(n);return{code:r,message:{access_denied:"Registration was denied.",abort:"Registration was cancelled.",expired_token:"The registration QR code expired."}[r]??"Unable to register the Feishu app."}}function Kue(n){let r=Number(n);if(!Number.isFinite(r)||r<=0)throw new TypeError("registerApp onQRCodeReady returned an invalid expireIn");return r}function Yue(n){if(n!==void 0){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError("registerApp returned invalid user_info");return{...n}}}var iC=class{#e;#A;#t;#r;#g;#n=0;#E=null;#s;constructor({registerApp:r,onCredentials:o,now:i=Date.now,setTimeout:e=globalThis.setTimeout,clearTimeout:a=globalThis.clearTimeout}={}){if(typeof r!="function")throw new TypeError("RegistrationManager requires a registerApp function");if(typeof o!="function")throw new TypeError("RegistrationManager requires an onCredentials function");if(typeof i!="function"||typeof e!="function"||typeof a!="function")throw new TypeError("RegistrationManager clock dependencies must be functions");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#s=this.#a(null,Sa.IDLE)}start(r={}){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError("Registration options must be an object");this.#u();let o={id:++this.#n,controller:new AbortController,qrCodeUrl:null,expiresAt:null,pollIntervalSeconds:null,expiryTimer:null};this.#E=o,this.#s=this.#a(o,Sa.STARTING);let i={...r,signal:o.controller.signal,onQRCodeReady:a=>this.#o(o,a),onStatusChange:a=>this.#c(o,a)};return Promise.resolve().then(()=>this.#e(i)).then(a=>this.#l(o,a),a=>this.#p(o,a)),this.status()}status(){this.#h();let r={...this.#s};r.error&&(r.error={...r.error});let o=this.#E;return o&&o.expiresAt!==null&&ON.has(r.state)&&(r.remainingSeconds=Math.max(0,Math.ceil((o.expiresAt-this.#t())/1e3))),r}cancel(){let r=this.#E;return r?(this.#d(r,Sa.CANCELLED,{error:{code:"abort",message:"Registration was cancelled."}}),r.controller.abort(),this.status()):this.status()}#I(r){return this.#E===r}#a(r,o,i={}){let e={state:o,attempt:r?.id??this.#n,updatedAt:this.#t(),...i};return r?.qrCodeUrl&&ON.has(o)&&(e.qrCodeUrl=r.qrCodeUrl,e.expiresAt=r.expiresAt),r?.pollIntervalSeconds!==null&&ON.has(o)&&(e.pollIntervalSeconds=r.pollIntervalSeconds),e}#i(r,o,i={}){this.#I(r)&&(this.#s=this.#a(r,o,i))}#o(r,o){if(!this.#I(r))return;if(typeof o?.url!="string"||!o.url)throw new TypeError("registerApp onQRCodeReady returned an invalid URL");let i=Kue(o.expireIn);r.qrCodeUrl=o.url,r.expiresAt=this.#t()+i*1e3,this.#Q(r),r.expiryTimer=this.#r(()=>this.#C(r),i*1e3),r.expiryTimer?.unref?.(),this.#i(r,Sa.QR_READY)}#c(r,o){!this.#I(r)||!Hue.has(o?.status)||(o.status===Sa.SLOW_DOWN&&Number.isFinite(Number(o.interval))&&(r.pollIntervalSeconds=Number(o.interval)),this.#i(r,o.status))}async#l(r,o){if(!this.#I(r))return;let i=o?.client_id,e=o?.client_secret;if(typeof i!="string"||!i||typeof e!="string"||!e){this.#d(r,Sa.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}let a;try{a=Yue(o.user_info)}catch{this.#d(r,Sa.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}this.#Q(r),r.qrCodeUrl=null,r.expiresAt=null,r.pollIntervalSeconds=null,this.#i(r,Sa.SAVING);try{await this.#A({client_id:i,client_secret:e,user_info:a})}catch{this.#I(r)&&this.#d(r,Sa.ERROR,{error:{code:"credentials_callback_failed",message:"Unable to store the Feishu credentials."}});return}this.#I(r)&&this.#d(r,Sa.SUCCEEDED)}#p(r,o){if(!this.#I(r))return;let i=_1(o);if(i==="expired_token"){this.#d(r,Sa.EXPIRED,{error:MN(o)});return}if(i==="abort"){this.#d(r,Sa.CANCELLED,{error:MN(o)});return}this.#d(r,Sa.ERROR,{error:MN(o)})}#h(){let r=this.#E;r&&r.expiresAt!==null&&this.#t()>=r.expiresAt&&this.#C(r)}#C(r){this.#I(r)&&(this.#d(r,Sa.EXPIRED,{error:{code:"expired_token",message:"The registration QR code expired."}}),r.controller.abort())}#d(r,o,i={}){this.#I(r)&&(this.#Q(r),this.#s=this.#a(r,o,i),this.#E=null)}#Q(r){r.expiryTimer!==null&&(this.#g(r.expiryTimer),r.expiryTimer=null)}#u(){let r=this.#E;r&&(this.#Q(r),this.#E=null,r.controller.abort())}};var N1=Object.freeze(["im:message.p2p_msg:readonly","im:message.group_at_msg:readonly","im:message:readonly","im:message:send_as_bot","im:message.reactions:write_only","im:message:recall","cardkit:card:write"]);var bN=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),T1=new Set([...bN,"saving"]),xue="*";function v1(){return{ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1}}function ZB(n){return n?n.status:v1()}function XB(n){return n.ready===!0&&n.feishuLongConnectionState==="connected"&&n.harnessReachable===!0}function P1(n){return n.length>12?`${n.slice(0,8)}\u2022\u2022\u2022\u2022${n.slice(-4)}`:"cli_\u2022\u2022\u2022\u2022"}function jue(n){return{name:n.botName,appIdMasked:P1(n.appId),activated:n.activated,domain:n.domain}}function Jue({connected:n,error:r,connection:o}){return n?"connected":r||o.feishuLongConnectionState==="failed"?"error":"disconnected"}function que(){return`bot_${k1().replaceAll("-","")}`}function Vue(){return`reg_${k1().replaceAll("-","")}`}function R1(n){return`DSH_FEISHU_APP_SECRET_${n.slice(4).toUpperCase()}`}var oC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Map;#c=null;#l=Promise.resolve();#p=new Map;#h=1;#C=!1;constructor({registerApp:r,verifyApp:o,credentials:i,configStore:e,createRuntime:a,deleteState:A=async()=>{},createBotId:t=que,createRegistrationId:s=Vue}){if(typeof r!="function")throw new Error("registerApp is required");if(typeof o!="function")throw new Error("verifyApp is required");if(!i)throw new Error("credentials service is required");if(!e||typeof e.list!="function")throw new Error("multi-bot config store is required");if(typeof a!="function")throw new Error("createRuntime is required");if(typeof A!="function")throw new Error("deleteState must be a function");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s}async initialize(){if(this.#C)return this.status();let r=this.#r.list(),o=!1;return await Promise.allSettled(r.map(i=>this.#S(i.id,async()=>{let e=ZB(this.#I.get(i.id));if(XB(e)||e.feishuLongConnectionState==="connecting"||e.feishuLongConnectionState==="reconnecting")return;if(o=!0,i.deletionPending){this.#a.set(i.id,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"});return}let a;try{a=await this.#t.resolve(i.secretRef)}catch{this.#a.set(i.id,{code:"missing_credentials",message:"\u65E0\u6CD5\u8BFB\u53D6\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u3002"});return}if(!a?.value){this.#a.set(i.id,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"});return}try{await this.#B(i,a.value),this.#a.delete(i.id)}catch{this.#a.set(i.id,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}}))),o&&this.#M(),this.status()}startRegistration(){this.#w();let r=this.#s();if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(r)||this.#i.has(r))throw new Error("Registration id generator returned an invalid or duplicate id");let o={id:r,manager:null,botId:null,createdNew:!1,cancelled:!1};return o.manager=new iC({registerApp:this.#e,onCredentials:i=>this.#N(()=>this.#u(o,i))}),this.#i.set(r,o),this.#c=r,this.#O(),o.manager.start({source:"deepseek-harness",createOnly:!0,appPreset:{name:"{user} \u7684\u5317\u6C47\u661F\u6CB3 AI \u52A9\u624B",desc:"\u8FDE\u63A5\u98DE\u4E66\u4E0E DeepSeek Harness\uFF0C\u5728\u804A\u5929\u4E2D\u4F7F\u7528\u4F01\u4E1A AI \u52A9\u624B\u3002"},addons:{preset:!1,scopes:{tenant:[...N1]},events:{items:{tenant:["im.message.receive_v1"]}}}}),this.#M(),this.registrationStatus(r)}hasRegistration(r){return this.#i.has(r)}registrationStatus(r){let o=this.#i.get(r);return o?this.#d({registration:o,selectedBotId:o.botId}):null}async cancelRegistration(r=this.#c){let o=this.#i.get(r);return o?T1.has(o.manager.status().state)?(o.cancelled=!0,o.manager.cancel(),await this.#N(async()=>{o.createdNew&&o.botId&&this.#o.get(o.botId)===o.id&&this.#r.getBot(o.botId)&&await this.#S(o.botId,()=>this.#f(o.botId))}),this.#M(),this.registrationStatus(r)??this.status()):this.registrationStatus(r):this.status()}status(r){return this.#d({registration:this.#i.get(this.#c)??null,selectedBotId:r})}async bindCredentials({appId:r,appSecret:o,domain:i="feishu"}={}){this.#w();let e=typeof r=="string"?r.trim():"",a=typeof o=="string"?o.trim():"",A=i==="lark"?"lark":"feishu";if(!e||!a)throw new TypeError("Feishu App ID and App Secret are required");return this.#N(async()=>{this.#w();let t=await this.#A({appId:e,appSecret:a,domain:A});this.#w();let s=this.#r.list().find(Q=>Q.appId===e),g=s?.id??this.#E();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??R1(g),l=await this.#t.resolve(c).catch(()=>{}),p={...s,id:g,appId:e,secretRef:c,ownerOpenIds:s?.ownerOpenIds?.length?s.ownerOpenIds:[xue],domain:A,botName:t.name,botOpenId:t.openId,activated:t.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()};await this.#t.set(c,a);let B;try{B=await this.#r.saveBot(p)}catch(Q){throw await this.#D(c,l),Q}return await this.#S(g,async()=>{try{await this.#B(B,a),this.#a.delete(g)}catch{this.#a.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u7ED1\u5B9A\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"})}}),this.#M(),this.status(g)})}async reconnectBot(r){return this.#w(),this.#S(r,async()=>{let o=this.#m(r);if(o.deletionPending)return this.#a.set(r,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"}),this.status(r);if(XB(ZB(this.#I.get(r))))return this.status(r);let i;try{i=await this.#t.resolve(o.secretRef)}catch{i=null}if(!i?.value)return this.#a.set(r,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"}),this.#M(),this.status(r);try{await this.#B(o,i.value),this.#a.delete(r)}catch{this.#a.set(r,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}return this.#M(),this.status(r)})}async sendConnectionTest(r){return this.#w(),this.#S(r,async()=>{let o=this.#m(r),i=this.#I.get(r);if(!XB(ZB(i))||typeof i.sendConnectionTest!="function"){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return i.sendConnectionTest(Yr(`${o.botName}\uFF08${P1(o.appId)}\uFF09`,"\u98DE\u4E66\u673A\u5668\u4EBA"))})}async disconnectBot(r){return this.#w(),this.#S(r,async()=>(this.#m(r),await this.#y(r),this.#a.delete(r),this.#M(),this.status(r)))}async deleteBot(r){return this.#w(),this.#N(()=>this.#S(r,async()=>(this.#m(r),await this.#f(r),this.#M(),this.status())))}async reconnect(){let r=this.#r.list()[0];return r?this.reconnectBot(r.id):this.status()}async disconnect(){let r=this.#r.list()[0];return r?this.deleteBot(r.id):this.status()}async close(){if(!this.#C){this.#C=!0;for(let r of this.#i.values())T1.has(r.manager.status().state)&&(r.cancelled=!0,r.manager.cancel());await this.#l,await Promise.allSettled([...this.#p.values()]),await Promise.allSettled([...this.#I.keys()].map(r=>this.#y(r)))}}#d({registration:r,selectedBotId:o}={}){let i=this.#r.list().map(l=>{let p=ZB(this.#I.get(l.id)),B=XB(p),Q=this.#a.get(l.id)??null;return{botId:l.id,phase:Jue({connected:B,error:Q,connection:p}),connected:B,configured:!0,bot:jue(l),connection:p,error:Q}}),e=r?this.#Q(r):{state:"idle",attempt:0,updatedAt:Date.now()},a=bN.has(e.state),A=e.state==="saving",t=!!r&&(a||A),s=i.find(l=>l.botId===o)??(t?null:i[0]??null),g=i.some(l=>l.connected),c=s?.phase??"unconfigured";return a?c="registering":A?c="connecting":e.state==="error"&&!s&&(c="error"),{schemaVersion:2,revision:this.#h,phase:c,connected:s?.connected??!1,configured:i.length>0,bot:s?.bot??null,connection:s?.connection??v1(),error:s?.error??e.error??null,registration:e,bots:i,totals:{configured:i.length,connected:i.filter(l=>l.connected).length},anyConnected:g}}#Q(r){return{...r.manager.status(),attempt:r.id,...r.botId?{botId:r.botId}:{}}}async#u(r,o){if(r.cancelled)throw new Error("Registration was cancelled");let i=o.client_id,e=o.client_secret,a=o.user_info?.open_id,A=o.user_info?.tenant_brand==="lark"?"lark":"feishu";if(!a)throw new Error("Feishu registration returned no owner open_id");let t=await this.#A({appId:i,appSecret:e,domain:A});if(r.cancelled)throw new Error("Registration was cancelled");let s=this.#r.list().find(f=>f.appId===i),g=s?.id??this.#E();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??R1(g),l=this.#o.get(g),p=await this.#t.resolve(c).catch(()=>{});await this.#t.set(c,e);let B;try{B=await this.#r.saveBot({...s,id:g,appId:i,secretRef:c,ownerOpenIds:[...new Set([...s?.ownerOpenIds??[],a])],domain:A,botName:t.name,botOpenId:t.openId,activated:t.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()}),r.botId=g,r.createdNew=!s,this.#o.set(g,r.id)}catch(f){try{await this.#D(c,p)}catch(y){throw new Error("Unable to restore the Feishu credential after a config failure.",{cause:y})}throw f}if(r.cancelled)throw r.createdNew?await this.#S(g,()=>this.#f(g)):(await this.#r.saveBot(s),await this.#D(c,p),l?this.#o.set(g,l):this.#o.delete(g)),new Error("Registration was cancelled");let Q=!1;try{if(await this.#S(g,()=>this.#B(B,e)),r.cancelled)throw r.createdNew?await this.#S(g,()=>this.#f(g)):(await this.#r.saveBot(s),await this.#D(c,p),l?this.#o.set(g,l):this.#o.delete(g),p?.value&&!s.deletionPending?await this.#S(g,()=>this.#B(s,p.value)):await this.#S(g,()=>this.#y(g))),Q=!0,new Error("Registration was cancelled");this.#a.delete(g),this.#M()}catch(f){if(r.cancelled)throw!Q&&r.createdNew&&this.#r.getBot(g)?await this.#S(g,()=>this.#f(g)):!Q&&s&&(await this.#r.saveBot(s),await this.#D(c,p),l?this.#o.set(g,l):this.#o.delete(g),!this.#C&&p?.value&&!s.deletionPending?await this.#S(g,()=>this.#B(s,p.value)):await this.#S(g,()=>this.#y(g))),this.#M(),f;if(s&&p?.value)try{throw await this.#r.saveBot(s),await this.#D(c,p),l?this.#o.set(g,l):this.#o.delete(g),s.deletionPending?(await this.#S(g,()=>this.#y(g)),this.#a.set(g,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"})):(await this.#S(g,()=>this.#B(s,p.value)),this.#a.delete(g)),this.#M(),f}catch(y){throw y===f?f:(this.#a.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u8FDE\u63A5\u66F4\u65B0\u5931\u8D25\uFF0C\u4E14\u539F\u8FDE\u63A5\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002"}),this.#M(),new Error("Unable to restore the previous Feishu bot connection.",{cause:y}))}throw this.#a.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#M(),f}}async#B(r,o){await this.#y(r.id);let i=await this.#g({botId:r.id,config:r,appSecret:o});this.#I.set(r.id,i);try{await i.start()}catch(e){throw this.#I.get(r.id)===i&&this.#I.delete(r.id),await i.stop({preserveError:!0}).catch(()=>{}),e}}async#y(r){let o=this.#I.get(r);this.#I.delete(r),o&&await o.stop()}async#f(r){let o=this.#r.getBot(r);if(o){o.deletionPending||(o=await this.#r.saveBot({...o,deletionPending:!0})),await this.#y(r);try{await this.#t.unset(o.secretRef)}catch(i){throw this.#a.set(r,{code:"credential_removal_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu credential.",{cause:i})}try{await this.#n({botId:r,config:o})}catch(i){throw this.#a.set(r,{code:"state_cleanup_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u7684\u672C\u5730\u4F1A\u8BDD\u6570\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu bot session state.",{cause:i})}await this.#r.removeBot(r),this.#a.delete(r),this.#o.delete(r)}}async#D(r,o){o?.value?await this.#t.set(r,o.value):await this.#t.unset(r)}#m(r){let o=this.#r.getBot(r);if(!o)throw new Error("Unknown Feishu bot");return o}#w(){if(this.#C)throw new Error("The Feishu controller is closed")}#N(r){let o=this.#l.then(r,r);return this.#l=o.then(()=>{},()=>{}),o}#S(r,o){let e=(this.#p.get(r)??Promise.resolve()).then(o,o),a=e.then(()=>{},()=>{});return this.#p.set(r,a),a.finally(()=>{this.#p.get(r)===a&&this.#p.delete(r)}),e}#O(){if(!(this.#i.size<=32))for(let[r,o]of this.#i){if(r===this.#c)continue;let i=o.manager.status().state;if(!bN.has(i)&&i!=="saving"&&this.#i.delete(r),this.#i.size<=32)break}}#M(){this.#h+=1}};import{mkdir as zue,readFile as Wue,rename as Zue,writeFile as Xue}from"node:fs/promises";import{dirname as $ue}from"node:path";var eBe=Object.freeze({version:1,sessions:{},seenMessageIds:[]}),$B=class{#e;#A=structuredClone(eBe);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=JSON.parse(await Wue(this.#e,"utf8"));this.#A={version:1,sessions:r.sessions&&typeof r.sessions=="object"?r.sessions:{},seenMessageIds:Array.isArray(r.seenMessageIds)?r.seenMessageIds.slice(-1e3):[]}}catch(r){if(r?.code!=="ENOENT")throw r;await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}snapshot(){return structuredClone(this.#A)}async#r(){let r=JSON.stringify(this.#A,null,2)+` -`;this.#t=this.#t.then(async()=>{await zue($ue(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await Xue(o,r,{encoding:"utf8",mode:384}),await Zue(o,this.#e)}),await this.#t}};function rBe(n,r){if(r!==void 0)return new URL(r);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-feishu requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function aBe(n){let r=Bs(n.dshHome??process.env.DSH_HOME??xI(ABe(),".dsh")),o=Bs(n.dataDir??xI(r,"integrations","dsh-feishu"));return{root:o,config:Bs(n.configPath??xI(o,"config.json")),legacyState:Bs(n.statePath??xI(o,"state.json")),bots:Bs(n.botsDir??xI(o,"bots")),workspaces:Bs(n.workspacesPath??xI(o,"workspaces.json"))}}async function _N(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-feishu requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-feishu requires ctx.webServer");let i=o.lark??yN,e=o.Controller??oC,a=o.ConfigStore??zB,A=o.StateStore??$B,t=o.HarnessClient??qB,s=o.FeishuRuntime??JB,g=o.verifyFeishuApp??y1,c=o.createConnectionSupervisor??mN,l=typeof n.logger=="function"?n.logger("dsh-feishu"):n.logger??console,p=aBe(r),B=await new a(p.config).load(),Q=Bs(r.workspace??process.cwd()),f=o.WorkspaceStore??Cr,y=o.workspaces??await new f(p.workspaces,{defaultWorkspace:Q}).load(),m=typeof B.list=="function",R=()=>m?B.list():[],k=R();m&&await y.reconcile(k.map(b=>b.id)),await Promise.all(k.map(b=>y.ensure(b.id)));let G=typeof B.removeBot=="function"?Jr(B,{workspaces:y,method:"removeBot",botIdFromRemoved:b=>b.id}):B,K=new Map,x=b=>!b.id||!b.secretRef||b.secretRef===WB?p.legacyState:Bs(p.bots,b.id,"state.json"),H=async b=>{let L=b.id??"__legacy__",X=K.get(L);return X||(X=await new A(x(b)).load(),K.set(L,X)),X},q=async b=>{let L=R().find(X=>X.id===b);if(!L)throw new Error("Unknown Feishu bot");return H(L)},j=zr(n,o.commandExecutor),F=new t({baseUrl:rBe(n.webServer,r.harnessBaseUrl),workspace:Q,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...j?{commandExecutor:j}:{}}),T=new e({registerApp:b=>i.registerApp(b),verifyApp:g,credentials:n.credentials,configStore:G,createRuntime:async({botId:b,config:L,appSecret:X})=>{let pe=await H(L),me=b??L.id??L.appId;await y.ensure(me);let qe=qr(F,{botId:me,workspaces:y,state:pe});return new s({lark:i,appId:L.appId,appSecret:X,domain:L.domain,ownerOpenIds:L.ownerOpenIds??[L.ownerOpenId],harness:qe.harness,state:qe.state,replyTimeoutMs:r.replyTimeoutMs??6e5,logger:{error:(...Se)=>l.error?.(`[${b??L.id}]`,...Se),warn:(...Se)=>l.warn?.(`[${b??L.id}]`,...Se),info:(...Se)=>l.info?.(`[${b??L.id}]`,...Se),debug:(...Se)=>l.debug?.(`[${b??L.id}]`,...Se)}})},deleteState:async({botId:b,config:L})=>{K.delete(b);try{await tBe(x(L))}catch(X){if(X?.code!=="ENOENT")throw X}}}),V=Vr(T,{workspaces:y,stateFor:q}),U=c({controller:V,harness:F,logger:l,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:V,ready:U.ready,async close(){await U.close(),await V.close(),F.stopManagedProcess()}}}import iBe from"qrcode";var NN="/feishu",rr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete",setWorkspace:"bot.workspace.set",testConnection:"connection.test",disconnect:"connection.disconnect"});var Jg=Object.freeze({reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete"}),U1=Object.freeze([...new Set([...Object.values(rr),...Object.values(Jg)])]),oBe=new Set(["idle","starting","qr_ready","polling","slow_down","domain_switched","saving","succeeded","expired","cancelled","error"]),nBe=/^[A-Za-z0-9_-]{1,128}$/,G1=Object.freeze({abort:"Registration was cancelled.",access_denied:"Registration was denied.",expired_token:"The registration QR code expired.",invalid_credentials:"Feishu returned invalid app credentials.",credentials_callback_failed:"Unable to activate the Feishu connection.",registration_failed:"Unable to register the Feishu app.",connection_failed:"The bot was created, but its connection could not be started.",credential_removal_failed:"Unable to remove the Feishu credentials.",state_cleanup_failed:"Unable to remove the bot session data. Please retry.",deletion_pending:"Bot deletion is incomplete. Retry removal to finish cleanup.",missing_credentials:"The bot credentials are missing. Delete it and scan again."}),sBe=Object.freeze({idle:"pending",starting:"pending",qr_ready:"pending",polling:"pending",slow_down:"pending",domain_switched:"pending",saving:"connecting",succeeded:"connected",expired:"expired",cancelled:"failed",error:"failed"});function gBe(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let r=Object.getPrototypeOf(n);return r===Object.prototype||r===null}function yn(n,r){return gBe(n)&&Reflect.ownKeys(n).every(o=>typeof o=="string"&&r.has(o))}function nC(n){return Number.isFinite(n)?n:void 0}function Qs(n){return typeof n=="string"&&nBe.test(n)}function F1(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function RN(n){if(!n||typeof n!="object")return null;let r=typeof n.code=="string"&&Object.hasOwn(G1,n.code)?n.code:"registration_failed";return{code:r,message:G1[r]}}function qg(n){if(!n||typeof n!="object")return{state:"idle",attempt:0};let r=oBe.has(n.state)?n.state:"error",o=Qs(n.attempt)?n.attempt:nC(n.attempt)??0,i={state:r,attempt:o},e=nC(n.updatedAt),a=nC(n.expiresAt),A=nC(n.remainingSeconds),t=nC(n.pollIntervalSeconds);e!==void 0&&(i.updatedAt=e),typeof n.qrCodeUrl=="string"&&n.qrCodeUrl.length>0&&(i.qrCodeUrl=n.qrCodeUrl),a!==void 0&&(i.expiresAt=a),A!==void 0&&(i.remainingSeconds=A),t!==void 0&&(i.pollIntervalSeconds=t),Qs(n.botId)&&(i.botId=n.botId);let s=RN(n.error);return s&&(i.error=s),i}function tQ(n){let r=n&&typeof n=="object"?n:{};return{connected:r.connected===!0||r.ready===!0&&r.feishuLongConnectionState==="connected"&&r.harnessReachable===!0,ready:r.ready===!0,harnessReachable:r.harnessReachable===!0}}function H1(n){let r=n&&typeof n=="object"?n:{},o={name:typeof r.name=="string"&&r.name.length>0?r.name:"\u98DE\u4E66\u673A\u5668\u4EBA"};return typeof r.avatarUrl=="string"&&(o.avatarUrl=r.avatarUrl),typeof r.appIdMasked=="string"&&(o.appIdMasked=r.appIdMasked),typeof r.tenantName=="string"&&(o.tenantName=r.tenantName),(r.domain==="feishu"||r.domain==="lark")&&(o.domain=r.domain),(typeof r.activated=="boolean"||typeof r.activated=="number")&&(o.activated=r.activated),o}function K1(n,r){return r?{status:"healthy",summary:"\u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38",lastCheckedAt:Date.now()}:n?.configured===!0?{status:"offline",summary:"\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",lastCheckedAt:Date.now()}:{status:"offline",summary:"\u5C1A\u672A\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA",lastCheckedAt:Date.now()}}function Y1(n,r,o){return o?"connected":n?.phase==="error"||r.state==="error"?"error":n?.phase==="connecting"||r.state==="saving"?"connecting":n?.phase==="registering"||["starting","qr_ready","polling","slow_down","domain_switched"].includes(r.state)?"provisioning":"disconnected"}async function x1(n){return iBe.toDataURL(n,{errorCorrectionLevel:"M",margin:1,width:320,type:"image/png"})}async function cBe(n,r){if(n.qrCodeUrl)return{attemptId:String(n.attempt),verificationUrl:n.qrCodeUrl,qrCodeDataUrl:await r(n.qrCodeUrl),expiresAt:n.expiresAt??Date.now()+5*6e4,pollIntervalMs:Math.max(800,Math.min(1e4,(n.pollIntervalSeconds??1.8)*1e3))}}function IBe(n){let r=n&&typeof n=="object"?n:{};if(!Qs(r.botId))return null;let o=tQ(r.connection),i=r.connected===!0||o.connected,e={state:"idle"},a={botId:r.botId,state:Y1(r,e,i),connected:i,configured:r.configured===!0,bot:H1(r.bot),health:K1(r,i)};typeof r.workspace=="string"&&r.workspace&&(a.workspace=r.workspace);let A=RN(r.error);return A&&(a.error=A),a}async function xi(n,{encodeQr:r=x1}={}){let o=n&&typeof n=="object"?n:{},i=qg(o.registration),e=tQ(o.connection),a=o.connected===!0||e.connected,A=await cBe(i,r),t=RN(o.error)??i.error??null,s=Array.isArray(o.bots)?o.bots.map(IBe).filter(Boolean):[],g={schemaVersion:o.schemaVersion===2?2:1,revision:Number.isSafeInteger(o.revision)&&o.revision>=0?o.revision:0,state:Y1(o,i,a),connected:a,configured:o.configured===!0,bot:H1(o.bot),health:K1(o,a),bots:s,totals:{configured:s.length||(o.configured===!0?1:0),connected:s.length?s.filter(c=>c.connected).length:a?1:0}};return A&&(g.provisioning=A),t&&(g.error=t),g}function eQ(n){return{ok:!1,error:{code:"bad-request",message:n,details:{issues:[]}}}}function AQ(){return{ok:!1,error:{code:"cancelled",message:"The Feishu request was cancelled.",details:{}}}}function lBe(){return{ok:!1,error:{code:"internal",message:"The Feishu integration operation failed.",details:{}}}}function EBe(n,r){return n===rr.status?yn(r,new Set)?null:"This endpoint accepts an empty payload only.":n===rr.testConnection?yn(r,new Set)?null:"This endpoint accepts an empty payload only.":n===rr.beginProvisioning?yn(r,new Set(["locale","replaceAttemptId"]))?r.locale!==void 0&&r.locale!=="zh-CN"?"The provisioning locale must be zh-CN.":r.replaceAttemptId!==void 0&&!Qs(r.replaceAttemptId)?"replaceAttemptId must be a valid opaque id.":null:"Provisioning accepts locale and replaceAttemptId only.":n===rr.bindCredentials?yn(r,new Set(["appId","appSecret"]))&&F1(r.appId,256)&&F1(r.appSecret,1024)?null:"Credential binding requires App ID and App Secret.":n===rr.pollProvisioning||n===rr.cancelProvisioning?yn(r,new Set(["attemptId"]))&&Qs(r.attemptId)?null:"A single valid attemptId is required.":n===rr.disconnect?yn(r,new Set(["removeCredentials"]))&&r.removeCredentials===!0?null:"Disconnect requires removeCredentials=true.":n===Jg.reconnectBot?yn(r,new Set(["botId","sendTest"]))&&Qs(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"A valid botId and optional sendTest flag are required.":n===Jg.disconnectBot?yn(r,new Set(["botId"]))&&Qs(r.botId)?null:"A single valid botId is required.":n===Jg.deleteBot?yn(r,new Set(["botId","confirm"]))&&Qs(r.botId)&&r.confirm===!0?null:"Deleting a bot requires a valid botId and confirm=true.":n===rr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Feishu endpoint."}function pBe(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new Error("aborted"));return}let e=setTimeout(a,n);e.unref?.();function a(){r?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(r.reason??new Error("aborted"))}r?.addEventListener("abort",A,{once:!0})})}async function TN(n,r){return typeof n.registrationStatus=="function"?n.registrationStatus(r):n.status()}async function CBe(n,r,o,i){let e=r,a=Date.now()+15e3;for(;;){let A=qg(e?.registration);if(A.qrCodeUrl)return e;if(["error","expired","cancelled"].includes(A.state))throw new Error("Provisioning stopped before the QR code was ready.");if(Date.now()>=a)throw new Error("Provisioning QR code timed out.");if(await pBe(50,i),e=await TN(n,o),!e)throw new Error("The provisioning attempt is no longer active.")}}function L1(n,r){return String(qg(n?.registration).attempt)===r}function hBe(n){let r=qg(n?.registration);return r.state==="succeeded"?r.botId&&(n?.connected===!0||tQ(n?.connection).connected)?"connected":"connecting":sBe[r.state]??"failed"}function dBe(n){if(!n||typeof n.status!="function"||typeof n.startRegistration!="function"||typeof n.cancelRegistration!="function"||typeof n.disconnect!="function")throw new TypeError("A Feishu controller with status/start/cancel/disconnect is required")}function j1(n,{encodeQr:r=x1}={}){dBe(n);let o=new Map,i=new Map,e=a=>{let A=o.get(a);return A||(o.size>=32&&o.delete(o.keys().next().value),A=Promise.resolve().then(()=>r(a)),o.set(a,A)),A};return async(a,A,t)=>{if(t?.aborted)return AQ();if(!U1.includes(a))return eQ("Unknown Feishu endpoint.");let s=EBe(a,A);if(s)return eQ(s);try{let g;if(a===rr.status)g=await xi(await n.status(),{encodeQr:e});else if(a===rr.beginProvisioning){A.replaceAttemptId&&await n.cancelRegistration(A.replaceAttemptId);let c=await n.startRegistration({locale:A.locale}),l=String(qg(c?.registration).attempt),p=await CBe(n,c,l,t);if(g=(await xi(p,{encodeQr:e})).provisioning,!g)throw new Error("Provisioning did not produce a QR code.");i.set(l,g.verificationUrl)}else if(a===rr.pollProvisioning){let c=await TN(n,A.attemptId);if(!c||!L1(c,A.attemptId))return eQ("The provisioning attempt is no longer active.");let l=qg(c.registration),p=await xi(c,{encodeQr:e});if(g={status:hBe(c),...l.botId?{botId:l.botId}:{},...p.provisioning?{provisioning:p.provisioning}:{},...l.botId&&p.connected?{connection:p}:{},...p.error?{message:p.error.message}:{}},["connected","expired","failed"].includes(g.status)){let B=i.get(A.attemptId);B&&o.delete(B),i.delete(A.attemptId)}}else if(a===rr.cancelProvisioning){let c=await TN(n,A.attemptId);if(!c||!L1(c,A.attemptId))return eQ("The provisioning attempt is no longer active.");let l=typeof n.registrationStatus=="function",p=qg(c.registration);!l&&p.state==="saving"?await n.disconnect():await n.cancelRegistration(A.attemptId);let B=i.get(A.attemptId);B&&o.delete(B),i.delete(A.attemptId),g={status:"failed",message:"Registration was cancelled."}}else if(a===rr.bindCredentials){if(typeof n.bindCredentials!="function")throw new Error("Credential binding is unavailable");g=await xi(await n.bindCredentials(A),{encodeQr:e})}else if(a===rr.testConnection){let c=await n.status(),p=c?.connected===!0||tQ(c?.connection).connected||typeof n.reconnect!="function"?c:await n.reconnect();g=await xi(p,{encodeQr:e})}else if(a===rr.disconnect)g=await xi(await n.disconnect(),{encodeQr:e});else if(a===Jg.reconnectBot){if(typeof n.reconnectBot!="function")throw new Error("Multi-bot reconnect is unavailable");let c=await n.reconnectBot(A.botId);if(t?.aborted)return AQ();if(g=await xi(c,{encodeQr:e}),A.sendTest===!0){let l=null;if(!(c?.bots?.some(B=>B?.botId===A.botId&&B.connected===!0)===!0))l=new Error("Feishu bot is not connected"),l.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let B=new Error("Connection test is unavailable");throw B.code="test-target-unavailable",B}await n.sendConnectionTest(A.botId)}catch(B){l=B}g={...g,testMessage:Ot(l)}}}else if(a===Jg.disconnectBot){if(typeof n.disconnectBot!="function")throw new Error("Multi-bot disconnect is unavailable");g=await xi(await n.disconnectBot(A.botId),{encodeQr:e})}else if(a===rr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");g=await xi(await n.updateWorkspace(A.botId,A.workspace),{encodeQr:e})}else{if(typeof n.deleteBot!="function")throw new Error("Multi-bot delete is unavailable");g=await xi(await n.deleteBot(A.botId),{encodeQr:e})}return t?.aborted?AQ():{ok:!0,value:g}}catch(g){let c=Xr(g);return t?.aborted?AQ():c?{ok:!1,error:{...c,details:{}}}:lBe()}}}function rQ(n,r,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(NN,j1(r,o),{authority:Wr(i)})}function uBe(n,r){if(r?.controller)return r.controller;if(typeof r?.createController=="function")return r.createController();if(typeof r?.createProvisioningManager=="function")return OD(r)}async function J1(n,r={}){let o=uBe(n,r);if(o)return rQ(n,o,r.rpcOptions,r.rpcAuthority);let i=await _N(n,r),e=rQ(n,i.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await i.close()},"dsh-feishu: close controller and live connection"),e}import{unlink as zBe}from"node:fs/promises";import{homedir as WBe}from"node:os";import{join as cC,resolve as Wg}from"node:path";import{createHash as BBe}from"node:crypto";import{mkdir as QBe,readFile as fBe,rename as yBe,unlink as mBe,writeFile as SBe}from"node:fs/promises";import{dirname as DBe}from"node:path";var kN=Object.freeze({version:1,bots:Object.freeze([])});function fs(n){return typeof n=="string"&&n.trim()?n.trim():null}function q1(n){let r=fs(n);return r&&/^qq_[a-f0-9]{24}$/.test(r)?r:null}function wBe(n){let r=fs(n);return r&&/^DSH_QQBOT_APP_SECRET_[A-F0-9]{24}$/.test(r)?r:null}function iQ(n){let r=fs(n);if(!r)throw new TypeError("appId is required");let o=BBe("sha256").update(r).digest("hex").slice(0,24);return{botId:`qq_${o}`,secretRef:`DSH_QQBOT_APP_SECRET_${o.toUpperCase()}`}}function vN(n){let r=fs(n)??"";return r.length<=10?r?`${r.slice(0,3)}\u2022\u2022\u2022`:"QQ\u673A\u5668\u4EBA":`${r.slice(0,6)}\u2022\u2022\u2022\u2022${r.slice(-4)}`}function V1(n){if(!n||typeof n!="object")return null;let r=fs(n.appId),o=fs(n.ownerUserOpenid),i=q1(n.botId),e=wBe(n.secretRef);if(!r||!o||!i||!e)return null;let a=iQ(r);return a.botId!==i||a.secretRef!==e?null:Object.freeze({botId:i,appId:r,secretRef:e,ownerUserOpenid:o,createdAt:fs(n.createdAt)??new Date().toISOString(),connectedAt:fs(n.connectedAt)})}function OBe(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let r=n.bots.map(V1);if(r.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of r){if(o.has(a.botId)||i.has(a.appId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.appId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(r)})}var aQ=class{#e;#A=kN;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=OBe(JSON.parse(await fBe(this.#e,"utf8")));if(!r)throw new Error("dsh-im QQ config contains invalid bot data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=kN}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByAppId(r){let o=this.#A.bots.find(i=>i.appId===r);return o?structuredClone(o):null}async save(r){let o=V1(r);if(!o)throw new Error("Refusing to persist incomplete QQ bot data");return this.#r(i=>{let e=i.find(t=>t.appId===o.appId&&t.botId!==o.botId),a=i.find(t=>t.secretRef===o.secretRef&&t.botId!==o.botId);if(e||a)throw new Error("Duplicate QQ bot identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!q1(r))throw new TypeError("Invalid QQ bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await mBe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=kN});this.#t=r.then(()=>{},()=>{}),await r}async#r(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(r){await QBe(DBe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await SBe(o,`${JSON.stringify(r,null,2)} +`;this.#t=this.#t.then(async()=>{await zue($ue(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await Xue(o,r,{encoding:"utf8",mode:384}),await Zue(o,this.#e)}),await this.#t}};function rBe(n,r){if(r!==void 0)return new URL(r);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-feishu requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function aBe(n){let r=Bs(n.dshHome??process.env.DSH_HOME??xI(ABe(),".dsh")),o=Bs(n.dataDir??xI(r,"integrations","dsh-feishu"));return{root:o,config:Bs(n.configPath??xI(o,"config.json")),legacyState:Bs(n.statePath??xI(o,"state.json")),bots:Bs(n.botsDir??xI(o,"bots")),workspaces:Bs(n.workspacesPath??xI(o,"workspaces.json"))}}async function _N(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-feishu requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-feishu requires ctx.webServer");let i=o.lark??yN,e=o.Controller??oC,a=o.ConfigStore??zB,A=o.StateStore??$B,t=o.HarnessClient??qB,s=o.FeishuRuntime??JB,g=o.verifyFeishuApp??y1,c=o.createConnectionSupervisor??mN,l=typeof n.logger=="function"?n.logger("dsh-feishu"):n.logger??console,p=aBe(r),B=await new a(p.config).load(),Q=Bs(r.workspace??process.cwd()),f=o.WorkspaceStore??Cr,y=o.workspaces??await new f(p.workspaces,{defaultWorkspace:Q}).load(),m=typeof B.list=="function",R=()=>m?B.list():[],k=R();m&&await y.reconcile(k.map(b=>b.id)),await Promise.all(k.map(b=>y.ensure(b.id)));let G=typeof B.removeBot=="function"?Jr(B,{workspaces:y,method:"removeBot",botIdFromRemoved:b=>b.id}):B,K=new Map,x=b=>!b.id||!b.secretRef||b.secretRef===WB?p.legacyState:Bs(p.bots,b.id,"state.json"),H=async b=>{let L=b.id??"__legacy__",X=K.get(L);return X||(X=await new A(x(b)).load(),K.set(L,X)),X},q=async b=>{let L=R().find(X=>X.id===b);if(!L)throw new Error("Unknown Feishu bot");return H(L)},j=zr(n,o.commandExecutor),F=new t({baseUrl:rBe(n.webServer,r.harnessBaseUrl),workspace:Q,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...j?{commandExecutor:j}:{}}),T=new e({registerApp:b=>i.registerApp(b),verifyApp:g,credentials:n.credentials,configStore:G,createRuntime:async({botId:b,config:L,appSecret:X})=>{let pe=await H(L),me=b??L.id??L.appId;await y.ensure(me);let qe=qr(F,{botId:me,workspaces:y,state:pe});return new s({lark:i,appId:L.appId,appSecret:X,domain:L.domain,ownerOpenIds:L.ownerOpenIds??[L.ownerOpenId],harness:qe.harness,state:qe.state,replyTimeoutMs:r.replyTimeoutMs??6e5,logger:{error:(...Se)=>l.error?.(`[${b??L.id}]`,...Se),warn:(...Se)=>l.warn?.(`[${b??L.id}]`,...Se),info:(...Se)=>l.info?.(`[${b??L.id}]`,...Se),debug:(...Se)=>l.debug?.(`[${b??L.id}]`,...Se)}})},deleteState:async({botId:b,config:L})=>{K.delete(b);try{await tBe(x(L))}catch(X){if(X?.code!=="ENOENT")throw X}}}),V=Vr(T,{workspaces:y,stateFor:q}),U=c({controller:V,harness:F,logger:l,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:V,ready:U.ready,async close(){await U.close(),await V.close(),F.stopManagedProcess()}}}import iBe from"qrcode";var NN="/feishu",rr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete",setWorkspace:"bot.workspace.set",testConnection:"connection.test",disconnect:"connection.disconnect"});var Jg=Object.freeze({reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete"}),U1=Object.freeze([...new Set([...Object.values(rr),...Object.values(Jg)])]),oBe=new Set(["idle","starting","qr_ready","polling","slow_down","domain_switched","saving","succeeded","expired","cancelled","error"]),nBe=/^[A-Za-z0-9_-]{1,128}$/,G1=Object.freeze({abort:"Registration was cancelled.",access_denied:"Registration was denied.",expired_token:"The registration QR code expired.",invalid_credentials:"Feishu returned invalid app credentials.",credentials_callback_failed:"Unable to activate the Feishu connection.",registration_failed:"Unable to register the Feishu app.",connection_failed:"The bot was created, but its connection could not be started.",credential_removal_failed:"Unable to remove the Feishu credentials.",state_cleanup_failed:"Unable to remove the bot session data. Please retry.",deletion_pending:"Bot deletion is incomplete. Retry removal to finish cleanup.",missing_credentials:"The bot credentials are missing. Delete it and scan again."}),sBe=Object.freeze({idle:"pending",starting:"pending",qr_ready:"pending",polling:"pending",slow_down:"pending",domain_switched:"pending",saving:"connecting",succeeded:"connected",expired:"expired",cancelled:"failed",error:"failed"});function gBe(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let r=Object.getPrototypeOf(n);return r===Object.prototype||r===null}function yn(n,r){return gBe(n)&&Reflect.ownKeys(n).every(o=>typeof o=="string"&&r.has(o))}function nC(n){return Number.isFinite(n)?n:void 0}function Qs(n){return typeof n=="string"&&nBe.test(n)}function F1(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function RN(n){if(!n||typeof n!="object")return null;let r=typeof n.code=="string"&&Object.hasOwn(G1,n.code)?n.code:"registration_failed";return{code:r,message:G1[r]}}function qg(n){if(!n||typeof n!="object")return{state:"idle",attempt:0};let r=oBe.has(n.state)?n.state:"error",o=Qs(n.attempt)?n.attempt:nC(n.attempt)??0,i={state:r,attempt:o},e=nC(n.updatedAt),a=nC(n.expiresAt),A=nC(n.remainingSeconds),t=nC(n.pollIntervalSeconds);e!==void 0&&(i.updatedAt=e),typeof n.qrCodeUrl=="string"&&n.qrCodeUrl.length>0&&(i.qrCodeUrl=n.qrCodeUrl),a!==void 0&&(i.expiresAt=a),A!==void 0&&(i.remainingSeconds=A),t!==void 0&&(i.pollIntervalSeconds=t),Qs(n.botId)&&(i.botId=n.botId);let s=RN(n.error);return s&&(i.error=s),i}function tQ(n){let r=n&&typeof n=="object"?n:{};return{connected:r.connected===!0||r.ready===!0&&r.feishuLongConnectionState==="connected"&&r.harnessReachable===!0,ready:r.ready===!0,harnessReachable:r.harnessReachable===!0}}function H1(n){let r=n&&typeof n=="object"?n:{},o={name:typeof r.name=="string"&&r.name.length>0?r.name:"\u98DE\u4E66\u673A\u5668\u4EBA"};return typeof r.avatarUrl=="string"&&(o.avatarUrl=r.avatarUrl),typeof r.appIdMasked=="string"&&(o.appIdMasked=r.appIdMasked),typeof r.tenantName=="string"&&(o.tenantName=r.tenantName),(r.domain==="feishu"||r.domain==="lark")&&(o.domain=r.domain),(typeof r.activated=="boolean"||typeof r.activated=="number")&&(o.activated=r.activated),o}function K1(n,r){return r?{status:"healthy",summary:"\u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38",lastCheckedAt:Date.now()}:n?.configured===!0?{status:"offline",summary:"\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",lastCheckedAt:Date.now()}:{status:"offline",summary:"\u5C1A\u672A\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA",lastCheckedAt:Date.now()}}function Y1(n,r,o){return o?"connected":n?.phase==="error"||r.state==="error"?"error":n?.phase==="connecting"||r.state==="saving"?"connecting":n?.phase==="registering"||["starting","qr_ready","polling","slow_down","domain_switched"].includes(r.state)?"provisioning":"disconnected"}async function x1(n){return iBe.toDataURL(n,{errorCorrectionLevel:"M",margin:1,width:320,type:"image/png"})}async function cBe(n,r){if(n.qrCodeUrl)return{attemptId:String(n.attempt),verificationUrl:n.qrCodeUrl,qrCodeDataUrl:await r(n.qrCodeUrl),expiresAt:n.expiresAt??Date.now()+5*6e4,pollIntervalMs:Math.max(800,Math.min(1e4,(n.pollIntervalSeconds??1.8)*1e3))}}function IBe(n){let r=n&&typeof n=="object"?n:{};if(!Qs(r.botId))return null;let o=tQ(r.connection),i=r.connected===!0||o.connected,e={state:"idle"},a={botId:r.botId,state:Y1(r,e,i),connected:i,configured:r.configured===!0,bot:H1(r.bot),health:K1(r,i)};typeof r.workspace=="string"&&r.workspace&&(a.workspace=r.workspace);let A=RN(r.error);return A&&(a.error=A),a}async function xi(n,{encodeQr:r=x1}={}){let o=n&&typeof n=="object"?n:{},i=qg(o.registration),e=tQ(o.connection),a=o.connected===!0||e.connected,A=await cBe(i,r),t=RN(o.error)??i.error??null,s=Array.isArray(o.bots)?o.bots.map(IBe).filter(Boolean):[],g={schemaVersion:o.schemaVersion===2?2:1,revision:Number.isSafeInteger(o.revision)&&o.revision>=0?o.revision:0,state:Y1(o,i,a),connected:a,configured:o.configured===!0,bot:H1(o.bot),health:K1(o,a),bots:s,totals:{configured:s.length||(o.configured===!0?1:0),connected:s.length?s.filter(c=>c.connected).length:a?1:0}};return A&&(g.provisioning=A),t&&(g.error=t),g}function eQ(n){return{ok:!1,error:{code:"bad-request",message:n,details:{issues:[]}}}}function AQ(){return{ok:!1,error:{code:"cancelled",message:"The Feishu request was cancelled.",details:{}}}}function lBe(){return{ok:!1,error:{code:"internal",message:"The Feishu integration operation failed.",details:{}}}}function EBe(n,r){return n===rr.status?yn(r,new Set)?null:"This endpoint accepts an empty payload only.":n===rr.testConnection?yn(r,new Set)?null:"This endpoint accepts an empty payload only.":n===rr.beginProvisioning?yn(r,new Set(["locale","replaceAttemptId"]))?r.locale!==void 0&&r.locale!=="zh-CN"?"The provisioning locale must be zh-CN.":r.replaceAttemptId!==void 0&&!Qs(r.replaceAttemptId)?"replaceAttemptId must be a valid opaque id.":null:"Provisioning accepts locale and replaceAttemptId only.":n===rr.bindCredentials?yn(r,new Set(["appId","appSecret"]))&&F1(r.appId,256)&&F1(r.appSecret,1024)?null:"Credential binding requires App ID and App Secret.":n===rr.pollProvisioning||n===rr.cancelProvisioning?yn(r,new Set(["attemptId"]))&&Qs(r.attemptId)?null:"A single valid attemptId is required.":n===rr.disconnect?yn(r,new Set(["removeCredentials"]))&&r.removeCredentials===!0?null:"Disconnect requires removeCredentials=true.":n===Jg.reconnectBot?yn(r,new Set(["botId","sendTest"]))&&Qs(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"A valid botId and optional sendTest flag are required.":n===Jg.disconnectBot?yn(r,new Set(["botId"]))&&Qs(r.botId)?null:"A single valid botId is required.":n===Jg.deleteBot?yn(r,new Set(["botId","confirm"]))&&Qs(r.botId)&&r.confirm===!0?null:"Deleting a bot requires a valid botId and confirm=true.":n===rr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Feishu endpoint."}function pBe(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new Error("aborted"));return}let e=setTimeout(a,n);e.unref?.();function a(){r?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(r.reason??new Error("aborted"))}r?.addEventListener("abort",A,{once:!0})})}async function TN(n,r){return typeof n.registrationStatus=="function"?n.registrationStatus(r):n.status()}async function CBe(n,r,o,i){let e=r,a=Date.now()+15e3;for(;;){let A=qg(e?.registration);if(A.qrCodeUrl)return e;if(["error","expired","cancelled"].includes(A.state))throw new Error("Provisioning stopped before the QR code was ready.");if(Date.now()>=a)throw new Error("Provisioning QR code timed out.");if(await pBe(50,i),e=await TN(n,o),!e)throw new Error("The provisioning attempt is no longer active.")}}function L1(n,r){return String(qg(n?.registration).attempt)===r}function hBe(n){let r=qg(n?.registration);return r.state==="succeeded"?r.botId&&(n?.connected===!0||tQ(n?.connection).connected)?"connected":"connecting":sBe[r.state]??"failed"}function dBe(n){if(!n||typeof n.status!="function"||typeof n.startRegistration!="function"||typeof n.cancelRegistration!="function"||typeof n.disconnect!="function")throw new TypeError("A Feishu controller with status/start/cancel/disconnect is required")}function j1(n,{encodeQr:r=x1}={}){dBe(n);let o=new Map,i=new Map,e=a=>{let A=o.get(a);return A||(o.size>=32&&o.delete(o.keys().next().value),A=Promise.resolve().then(()=>r(a)),o.set(a,A)),A};return async(a,A,t)=>{if(t?.aborted)return AQ();if(!U1.includes(a))return eQ("Unknown Feishu endpoint.");let s=EBe(a,A);if(s)return eQ(s);try{let g;if(a===rr.status)g=await xi(await n.status(),{encodeQr:e});else if(a===rr.beginProvisioning){A.replaceAttemptId&&await n.cancelRegistration(A.replaceAttemptId);let c=await n.startRegistration({locale:A.locale}),l=String(qg(c?.registration).attempt),p=await CBe(n,c,l,t);if(g=(await xi(p,{encodeQr:e})).provisioning,!g)throw new Error("Provisioning did not produce a QR code.");i.set(l,g.verificationUrl)}else if(a===rr.pollProvisioning){let c=await TN(n,A.attemptId);if(!c||!L1(c,A.attemptId))return eQ("The provisioning attempt is no longer active.");let l=qg(c.registration),p=await xi(c,{encodeQr:e});if(g={status:hBe(c),...l.botId?{botId:l.botId}:{},...p.provisioning?{provisioning:p.provisioning}:{},...l.botId&&p.connected?{connection:p}:{},...p.error?{message:p.error.message}:{}},["connected","expired","failed"].includes(g.status)){let B=i.get(A.attemptId);B&&o.delete(B),i.delete(A.attemptId)}}else if(a===rr.cancelProvisioning){let c=await TN(n,A.attemptId);if(!c||!L1(c,A.attemptId))return eQ("The provisioning attempt is no longer active.");let l=typeof n.registrationStatus=="function",p=qg(c.registration);!l&&p.state==="saving"?await n.disconnect():await n.cancelRegistration(A.attemptId);let B=i.get(A.attemptId);B&&o.delete(B),i.delete(A.attemptId),g={status:"failed",message:"Registration was cancelled."}}else if(a===rr.bindCredentials){if(typeof n.bindCredentials!="function")throw new Error("Credential binding is unavailable");g=await xi(await n.bindCredentials(A),{encodeQr:e})}else if(a===rr.testConnection){let c=await n.status(),p=c?.connected===!0||tQ(c?.connection).connected||typeof n.reconnect!="function"?c:await n.reconnect();g=await xi(p,{encodeQr:e})}else if(a===rr.disconnect)g=await xi(await n.disconnect(),{encodeQr:e});else if(a===Jg.reconnectBot){if(typeof n.reconnectBot!="function")throw new Error("Multi-bot reconnect is unavailable");let c=await n.reconnectBot(A.botId);if(t?.aborted)return AQ();if(g=await xi(c,{encodeQr:e}),A.sendTest===!0){let l=null;if(!(c?.bots?.some(B=>B?.botId===A.botId&&B.connected===!0)===!0))l=new Error("Feishu bot is not connected"),l.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let B=new Error("Connection test is unavailable");throw B.code="test-target-unavailable",B}await n.sendConnectionTest(A.botId)}catch(B){l=B}g={...g,testMessage:Ot(l)}}}else if(a===Jg.disconnectBot){if(typeof n.disconnectBot!="function")throw new Error("Multi-bot disconnect is unavailable");g=await xi(await n.disconnectBot(A.botId),{encodeQr:e})}else if(a===rr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");g=await xi(await n.updateWorkspace(A.botId,A.workspace),{encodeQr:e})}else{if(typeof n.deleteBot!="function")throw new Error("Multi-bot delete is unavailable");g=await xi(await n.deleteBot(A.botId),{encodeQr:e})}return t?.aborted?AQ():{ok:!0,value:g}}catch(g){let c=Xr(g);return t?.aborted?AQ():c?{ok:!1,error:{...c,details:{}}}:lBe()}}}function rQ(n,r,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(NN,j1(r,o),{authority:Wr(i)})}function uBe(n,r){if(r?.controller)return r.controller;if(typeof r?.createController=="function")return r.createController();if(typeof r?.createProvisioningManager=="function")return OD(r)}async function J1(n,r={}){let o=uBe(n,r);if(o)return rQ(n,o,r.rpcOptions,r.rpcAuthority);let i=await _N(n,r),e=rQ(n,i.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await i.close()},"dsh-feishu: close controller and live connection"),e}import{unlink as zBe}from"node:fs/promises";import{homedir as WBe}from"node:os";import{join as cC,resolve as Wg}from"node:path";import{createHash as BBe}from"node:crypto";import{mkdir as QBe,readFile as fBe,rename as yBe,unlink as mBe,writeFile as SBe}from"node:fs/promises";import{dirname as DBe}from"node:path";var kN=Object.freeze({version:1,bots:Object.freeze([])});function fs(n){return typeof n=="string"&&n.trim()?n.trim():null}function q1(n){let r=fs(n);return r&&/^qq_[a-f0-9]{24}$/.test(r)?r:null}function wBe(n){let r=fs(n);return r&&/^DSH_QQBOT_APP_SECRET_[A-F0-9]{24}$/.test(r)?r:null}function iQ(n){let r=fs(n);if(!r)throw new TypeError("appId is required");let o=BBe("sha256").update(r).digest("hex").slice(0,24);return{botId:`qq_${o}`,secretRef:`DSH_QQBOT_APP_SECRET_${o.toUpperCase()}`}}function vN(n){let r=fs(n)??"";return r.length<=10?r?`${r.slice(0,3)}\u2022\u2022\u2022`:"QQ\u673A\u5668\u4EBA":`${r.slice(0,6)}\u2022\u2022\u2022\u2022${r.slice(-4)}`}function V1(n){if(!n||typeof n!="object")return null;let r=fs(n.appId),o=fs(n.ownerUserOpenid),i=q1(n.botId),e=wBe(n.secretRef);if(!r||!o||!i||!e)return null;let a=iQ(r);return a.botId!==i||a.secretRef!==e?null:Object.freeze({botId:i,appId:r,secretRef:e,ownerUserOpenid:o,createdAt:fs(n.createdAt)??new Date().toISOString(),connectedAt:fs(n.connectedAt)})}function OBe(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let r=n.bots.map(V1);if(r.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of r){if(o.has(a.botId)||i.has(a.appId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.appId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(r)})}var aQ=class{#e;#A=kN;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=OBe(JSON.parse(await fBe(this.#e,"utf8")));if(!r)throw new Error("dsh-im QQ config contains invalid bot data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=kN}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByAppId(r){let o=this.#A.bots.find(i=>i.appId===r);return o?structuredClone(o):null}async save(r){let o=V1(r);if(!o)throw new Error("Refusing to persist incomplete QQ bot data");return this.#r(i=>{let e=i.find(t=>t.appId===o.appId&&t.botId!==o.botId),a=i.find(t=>t.secretRef===o.secretRef&&t.botId!==o.botId);if(e||a)throw new Error("Duplicate QQ bot identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!q1(r))throw new TypeError("Invalid QQ bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await mBe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=kN});this.#t=r.then(()=>{},()=>{}),await r}async#r(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(r){await QBe(DBe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await SBe(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await yBe(o,this.#e)}};var oQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"qq",logPrefix:"dsh-qq"})}};import{randomUUID as MBe}from"node:crypto";var z1=new Set(["starting","pending","refreshing","connecting"]),Vg=new Set(["connected","failed","cancelled"]),bBe=5*6e4;function zg(n){return typeof n=="string"&&n.trim()?n.trim():null}function ji(n,r){return Object.freeze({code:n,message:r})}function nQ(n){return n?{attemptId:n.id,status:n.state,qrRevision:n.qrRevision,pollIntervalMs:1e3,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var sC=class{#e;#A;#t;#r;#g;#n;#E=new Map;#s=new Map;#I=new Map;#a=null;#i=new Map;#o=0;#c=!1;constructor({qrAuth:r,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!r||typeof r.start!="function")throw new TypeError("QQ QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("QqController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("QqController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A}async initialize(){if(this.#c)return this.status();for(let r of this.#t.list())await this.#u(r.botId,async()=>{if(this.#c||this.#E.get(r.botId)?.status?.ready)return;let o=await this.#d(r.secretRef);if(!o){this.#s.set(r.botId,ji("missing-secret","QQ \u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002"));return}try{await this.#h(r,o),this.#s.delete(r.botId)}catch(i){this.#s.set(r.botId,ji("connection-failed","QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#n.warn?.(`[dsh-im:qq] bot ${r.botId} failed to initialize:`,i)}finally{this.#B()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("QQ controller is closed");this.#a&&await this.cancelProvisioning(this.#a);let r,o,i=new Promise((a,A)=>{r=a,o=A}),e={id:MBe(),state:"starting",createdAt:Date.now(),expiresAt:null,qrRevision:0,verificationUrl:null,controller:new AbortController,dispose:null,task:null,error:null,botId:null};this.#I.set(e.id,e),this.#a=e.id,this.#B();try{return e.dispose=this.#e.start({onQrDisplayed:a=>{if(e.controller.signal.aborted||Vg.has(e.state))return;let A=zg(a);A&&(e.verificationUrl=A,e.qrRevision+=1,e.expiresAt=Date.now()+bBe,e.state="pending",this.#B(),r())},onQrExpired:()=>{e.controller.signal.aborted||Vg.has(e.state)||(e.state="refreshing",e.verificationUrl=null,e.expiresAt=null,this.#B())},onSuccess:a=>{e.controller.signal.aborted||Vg.has(e.state)||(e.task=this.#l(e,a))},onFailure:a=>{e.controller.signal.aborted||Vg.has(e.state)||(e.state="failed",e.error=ji("qr-connect-failed","QQ \u626B\u7801\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"),this.#a===e.id&&(this.#a=null),this.#B(),o(a))}},{signal:e.controller.signal}),await i,nQ(e)}catch(a){throw e.controller.signal.aborted?(e.state="cancelled",e.error=ji("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):Vg.has(e.state)||(e.state="failed",e.error=ji("qr-start-failed","\u65E0\u6CD5\u751F\u6210 QQ \u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),this.#a===e.id&&(this.#a=null),this.#B(),a}}registrationStatus(r){return nQ(this.#I.get(r))}async bindCredentials({appId:r,appSecret:o}={}){if(this.#c)throw new Error("QQ controller is closed");let i=zg(r),e=zg(o);if(!i||!e)throw new TypeError("QQ AppID and AppSecret are required");if(this.#a&&await this.cancelProvisioning(this.#a),this.#c)throw new Error("QQ controller is closed");let a=iQ(i);return await this.#u(a.botId,async()=>{if(this.#c)throw new Error("QQ controller is closed");let A=this.#t.getByAppId(i),t=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#c)throw new Error("QQ controller is closed");let s={botId:a.botId,appId:i,secretRef:a.secretRef,ownerUserOpenid:A?.ownerUserOpenid??"*",createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#Q(a.secretRef,t),g}try{await this.#h(s,e),this.#s.delete(a.botId)}catch(g){this.#s.set(a.botId,ji("connection-failed","QQ \u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:qq] bot ${a.botId} credential connection failed:`,g)}this.#B()}),this.status()}async cancelProvisioning(r){let o=this.#I.get(r);return o?(Vg.has(o.state)||(o.controller.abort(),o.dispose?.(),await o.task?.catch(()=>{}),Vg.has(o.state)||(o.state="cancelled"),o.error??=ji("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#a===o.id&&(this.#a=null),this.#B(),nQ(o)):null}async reconnectBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown QQ bot");return await this.#u(r,async()=>{let i=await this.#d(o.secretRef);if(!i)throw new Error("QQ bot secret is missing");try{await this.#h(o,i),this.#s.delete(r)}catch(e){throw this.#s.set(r,ji("connection-failed","QQ \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#B()}}),this.status()}async sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown QQ bot");return this.#u(r,async()=>{let i=this.#E.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error("QQ\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(Yr(`QQ \u673A\u5668\u4EBA\uFF08${vN(o.appId)}\uFF09`)),{sent:!0}})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown QQ bot");return await this.#u(r,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#C(r);try{await this.#A.unset(o.secretRef),await this.#t.remove(r)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the QQ bot safely.",{cause:e})}await this.#g({botId:r,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:qq] bot ${r} state cleanup failed:`,e)}),this.#s.delete(r),this.#B()}),this.status()}status(){let r=this.#t.list().map(e=>{let a=this.#E.get(e.botId)?.status??null,A=a?.ready===!0&&a.qqConnectionState==="connected"&&a.harnessReachable===!0,t=A?"connected":a?.qqConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||a?.qqConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:"QQ\u673A\u5668\u4EBA",appIdMasked:vN(e.appId)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"QQ WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":t==="error"?"QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"QQ \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},error:structuredClone(this.#s.get(e.botId)??null)}}),o=r.filter(e=>e.connected).length,i=this.#a?this.#I.get(this.#a):null;return{schemaVersion:1,revision:this.#o,state:i&&z1.has(i.state)?"provisioning":r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o},...i&&z1.has(i.state)?{provisioning:nQ(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#a&&await this.cancelProvisioning(this.#a),await Promise.allSettled([...this.#i.values()]),await Promise.allSettled([...this.#E.keys()].map(r=>this.#C(r))))}async#l(r,o){try{r.state="connecting",r.verificationUrl=null,r.expiresAt=null,this.#B();let i=Array.isArray(o)?o[0]:null,e=zg(i?.appId),a=zg(i?.appSecret),A=zg(i?.userOpenid);if(!e||!a||!A)throw new Error("QQ authorization returned incomplete credentials");r.botId=await this.#p(r,{appId:e,appSecret:a,ownerUserOpenid:A}),r.state="connected",r.error=null}catch(i){r.controller.signal.aborted?(r.state="cancelled",r.error=ji("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=ji("activation-failed","QQ \u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u63A5\u5165\u914D\u7F6E\u3002"),this.#n.error?.("[dsh-im:qq] provisioning failed:",i))}finally{r.dispose?.(),this.#a===r.id&&(this.#a=null),this.#B()}}async#p(r,{appId:o,appSecret:i,ownerUserOpenid:e}){let a=iQ(o),A=this.#t.getByAppId(o),t=await this.#A.resolve(a.secretRef).catch(()=>{}),s={botId:a.botId,appId:o,secretRef:a.secretRef,ownerUserOpenid:e,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#u(a.botId,async()=>{await this.#A.set(a.secretRef,i);try{if(r.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(s)}catch(g){throw await this.#Q(a.secretRef,t),g}try{if(r.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#h(s,i),this.#s.delete(a.botId)}catch(g){if(r.controller.signal.aborted)throw await this.#C(a.botId),A?await this.#t.save(A).catch(()=>{}):await this.#t.remove(a.botId).catch(()=>null)&&await this.#g({botId:a.botId,config:s}).catch(l=>{this.#n.warn?.("[dsh-im:qq] cancelled bot state cleanup failed:",l)}),await this.#Q(a.secretRef,t),g;this.#s.set(a.botId,ji("connection-failed","QQ \u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:qq] bot ${a.botId} activation connection failed:`,g)}return this.#B(),a.botId})}async#h(r,o){if(this.#c)throw new Error("QQ controller is closed");if(await this.#C(r.botId),this.#c)throw new Error("QQ controller is closed");let i=await this.#r({botId:r.botId,config:r,appSecret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid QQ runtime");this.#E.set(r.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#E.delete(r.botId),e}}async#C(r){let o=this.#E.get(r);this.#E.delete(r),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:qq] bot ${r} failed to stop cleanly:`,i)})}async#d(r){let o=await this.#A.resolve(r).catch(()=>{});return zg(o?.value)}async#Q(r,o){o?.value?await this.#A.set(r,o.value).catch(()=>{}):await this.#A.unset(r).catch(()=>{})}#u(r,o){let a=(this.#i.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(r)===a&&this.#i.delete(r)});return this.#i.set(r,a),a}#B(){this.#o+=1}};import{QQBot as PBe,typingIndicator as GBe}from"@tencent-connect/qqbot-nodejs";var sQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",_Be=Object.freeze([".myqcloud.com",".qpic.cn",".qq.com",".qq.com.cn",".tencentcos.com",".ugcimg.cn"]),NBe=/\.(?:gif|jpe?g|png|webp)$/i,TBe=["QQ \u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` `);function RBe(n){return`${n.kind}:${n.kind==="group"?n.groupOpenid:n.senderId}`}function gQ(n){return typeof n?.content=="string"?n.content.trim():""}function W1(n){let r=Ei(n?.content_type??n?.contentType);return r?r.split(";",1)[0].trim().toLowerCase():null}function Z1(n){return W1(n)?.startsWith("image/")===!0||NBe.test(Ei(n?.filename)??"")}function PN(n){return Array.isArray(n?.attachments)&&n.attachments.some(Z1)}function kBe(n,{fetchImpl:r=fetch}={}){if(typeof r!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.attachments??[]){if(!Z1(i))continue;let e=Ei(i?.url),a=Ei(i?.filename)??void 0,A=W1(i),t=Number(i?.size);o.push({...a?{name:a}:{},...A?.startsWith("image/")?{mediaType:A}:{},...Number.isFinite(t)&&t>=0?{size:t}:{},load:({signal:s,maxBytes:g})=>{if(!e)throw new Error("QQ image attachment has no download URL");return za(e,{fetchImpl:r,signal:s,maxBytes:g,allowedHosts:_Be})}})}return{content:gQ(n),images:o}}function Ei(n){return typeof n=="string"&&n.trim()?n.trim():null}function vBe(n,r){return r.questions[r.index]&&Ei(n?.senderId)===r.actor&&(n.kind!=="group"||n.rawEventType==="GROUP_AT_MESSAGE_CREATE")&&!PN(n)&&Ei(gQ(n))}function GN(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var cQ=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=new Map;#i=new Map;#o=new Map;#c=new Set;#l=new Set;#p;constructor({bot:r,ownerUserOpenid:o,harness:i,state:e,status:a=GN(),logger:A=console,replyTimeoutMs:t=6e5,signal:s,fetchImpl:g=fetch}){if(!r||typeof r.sendText!="function")throw new TypeError("QQ bot client is required");if(!o)throw new TypeError("QQ scanner identity is required");if(!i||!e)throw new TypeError("Harness client and state store are required");if(typeof g!="function")throw new TypeError("fetchImpl must be a function");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#p=new Ca({label:"qq",logger:A})}get status(){return structuredClone(this.#g)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Ei(r?.messageId),i=Ei(r?.senderId);if(!o||!i||r?.senderIsBot===!0||!["c2c","group"].includes(r?.kind)||this.#r.hasSeen(o)||this.#c.has(o))return Promise.resolve();let e=RBe(r);this.#c.add(o),r.kind==="c2c"&&(this.#A==="*"||i===this.#A)&&r.replyTarget?.scope==="c2c"&&Ei(r.replyTarget.targetId)===i&&Va(this.#r,r.replyTarget);let a=this.#i.get(e),A=this.#p.claimReply({key:e,actor:i,messageId:o,text:PN(r)?"":gQ(r),addressed:r.kind!=="group"||r.rawEventType==="GROUP_AT_MESSAGE_CREATE",hasPendingQuestion:!!a,questionCompletion:a?.submitting||a?.claimedReplyMessageId?a.queue:null,isQuestionPending:()=>this.#i.has(e),send:t=>this.#e.sendText(r.replyTarget,t)});if(A){let t;return t=A.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#c.delete(o),this.#l.delete(t)}),this.#l.add(t),t}if(a&&i!==a.actor)return this.#h(r,o,e);if(a?.submitting||a?.claimedReplyMessageId)return this.#h(r,o,e);if(a){vBe(r,a)&&(a.claimedReplyMessageId=o);let s=(a.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#d(r,o,e,a)).catch(g=>this.#w(r,o,g)).finally(()=>{this.#c.delete(o),a.claimedReplyMessageId===o&&(a.claimedReplyMessageId=null),a.queue===s&&(a.queue=null)});return a.queue=s,s}return this.#h(r,o,e)}#h(r,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1}={}){let t=(this.#a.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#C(r,i,{alreadyRecorded:a})).finally(()=>{e&&this.#c.delete(o),this.#a.get(i)===t&&this.#a.delete(i)});return this.#a.set(i,t),t}async waitForIdle(){await Promise.allSettled([...this.#a.values(),...[...this.#i.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#l])}async#C(r,o,{alreadyRecorded:i=!1}={}){if(this.#s?.aborted)return;let e=Ei(r?.messageId),a=Ei(r?.senderId);if(!e||!a||r.senderIsBot===!0||!["c2c","group"].includes(r.kind))return;if(!i){if(this.#r.hasSeen(e))return;this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}if(this.#A!=="*"&&a!==this.#A){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}if(r.kind==="group"&&r.rawEventType!=="GROUP_AT_MESSAGE_CREATE")return;let A=r.replyTarget,t=kBe(r,{fetchImpl:this.#I}),s=t.content,g=Mr(t),c=null;try{if(!s&&!g){await this.#e.sendText(A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002"),await this.#r.markSeen(e);return}let l=s.toLowerCase();if(!g&&l==="/help"){await this.#e.sendText(A,TBe),await this.#r.markSeen(e);return}if(!g&&l==="/status"){await this.#t.ensureRunning({signal:this.#s}),await this.#e.sendText(A,"QQ \u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#r.markSeen(e);return}if(!g&&l==="/new"){await this.#r.clearSession(o),await this.#e.sendText(A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#r.markSeen(e);return}let p=g?null:await ti(s,this.#t,o);if(p){for(let m of p.messages??[p.message])await this.#e.sendText(A,m);await this.#r.markSeen(e);return}let B=g?null:await Ai(s,this.#t,this.#r,o,{signal:this.#s});if(B){await this.#e.sendText(A,B.message),await this.#r.markSeen(e);return}let Q=g?await Wa(t,{signal:this.#s}):void 0,f=!1;if(r.kind==="c2c"&&A?.msgId&&typeof this.#e.openStream=="function")try{c=this.#e.openStream({target:A})}catch(m){this.#n.warn?.("[dsh-im:qq] unable to start a QQ stream; using a text reply:",m)}let y;try{({answer:y}=await ha({harness:this.#t,state:this.#r,key:o,...g?{content:Q}:{text:s},createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#E,signal:this.#s,onUpdate:c?async m=>{let R=m.type==="text"?m.text:m.type==="tool"?`\u6B63\u5728\u4F7F\u7528${m.name}\u2026`:m.text;R&&await c.update(R)}:void 0,onInteraction:m=>this.#Q(m,{key:o,actor:a,target:A,requiresMention:r.kind==="group"}),onInteractionResolved:m=>this.#u(m)}}))}finally{await Promise.allSettled([this.#m(o),this.#p.closeRoute(o)])}if(c)try{await c.update(y),await c.complete(),f=!0}catch(m){c.cancel?.(),this.#n.warn?.("[dsh-im:qq] QQ stream finalization failed; using a text reply:",m)}f||await this.#e.sendText(A,y),await this.#r.markSeen(e),this.#g.messagesReplied+=1,this.#g.lastReplyAt=new Date().toISOString(),this.#g.lastError=null}catch(l){if(c?.cancel?.(),this.#s?.aborted)return;this.#g.lastError=l?.message??String(l),this.#n.error?.("[dsh-im:qq] failed to process an inbound message:",l);try{await this.#e.sendText(A,Za(l)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),await this.#r.markSeen(e)}catch(p){this.#n.error?.("[dsh-im:qq] failed to send the safe error reply:",p)}}}async#d(r,o,i,e){this.#s?.throwIfAborted();let a=this.#i.get(i),A=e.claimedReplyMessageId===o;if(!a||a!==e||a.submitting)return A&&(!a||a!==e)?this.#y(r,o):this.#h(r,o,i,{releaseMessageId:!1});if(this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),r.kind==="group"&&r.rawEventType!=="GROUP_AT_MESSAGE_CREATE"))return;let t=Ei(gQ(r));if(!t||PN(r)){await this.#e.sendText(r.replyTarget,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002");return}let s=this.#i.get(i);if(!s||s!==e||s.submitting){if(A&&(!s||s!==e)){await this.#e.sendText(r.replyTarget,sQ);return}return this.#h(r,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}if(s.target=r.replyTarget,s.needsPresentation){try{await this.#B(s)}catch{this.#g.lastError="QQ \u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#n.error?.("[dsh-im:qq] failed to retry an interaction question"),s.interaction.reconnect?.();return}let c=this.#i.get(i);if(!c||c!==e||c.submitting){if(A&&(!c||c!==e)){await this.#e.sendText(r.replyTarget,sQ).catch(()=>{});return}return this.#h(r,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}}let g=s.questions[s.index];if(g){if(s.answers.push(ei(g,t)),s.index+=1,s.index{});return}if(this.#i.get(i)!==s)return;s.submitting=!1,s.answers.pop(),s.index-=1,this.#g.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#n.error?.("[dsh-im:qq] failed to answer a Harness interaction"),await this.#e.sendText(s.target,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#Q(r,{key:o,actor:i,target:e,requiresMention:a}){if(r?.kind==="approval")return this.#p.handleRequested(r,{key:o,actor:i,requiresMention:a,send:c=>this.#e.sendText(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r?.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#n.warn?.("[dsh-im:qq] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.respond({ok:!1,error:{code:"cancelled",message:"QQ safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#e.sendText(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002").catch(()=>{});return}let s=this.#i.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#B(s);return}if(this.#o.has(t))return;if(s){await r.respond({ok:!1,error:{code:"cancelled",message:"QQ is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,presentationPromise:null,submitting:!1,needsPresentation:!0};this.#i.set(o,g),this.#o.set(t,o),await this.#B(g)}async#u(r){if(r?.kind==="approval"){await this.#p.handleResolved(r);return}let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#o.get(o);i&&this.#D(i,o)}#B(r){if(!r.needsPresentation)return Promise.resolve();if(r.presentationPromise)return r.presentationPromise;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=this.#e.sendText(r.target,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})).then(()=>{r.needsPresentation=!1}).finally(()=>{r.presentationPromise===i&&(r.presentationPromise=null)});return r.presentationPromise=i,i}async#y(r,o){this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),await this.#e.sendText(r.replyTarget,sQ).catch(()=>{}))}#f(r,o){let i=this.#i.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#i.delete(r),this.#o.delete(i.interactionId),i)}#D(r,o){return this.#f(r,o)!==null}async#m(r){let o=this.#f(r);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The QQ interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#n.warn?.("[dsh-im:qq] failed to cancel a pending Harness interaction")}}async#w(r,o,i){this.#s?.aborted||(this.#g.lastError=i?.message??String(i),this.#n.error?.("[dsh-im:qq] failed to process an interaction reply:",i),this.#r.hasSeen(o)||await this.#r.markSeen(o).catch(()=>{}),await this.#e.sendText(r.replyTarget,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002").catch(()=>{}))}};function FBe(){let n=new Error("QQ WebSocket did not become ready in time");return n.code="connect-timeout",n}function LBe(){return{startedAt:null,ready:!1,qqConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...GN()}}var gC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=LBe();#i=null;#o=null;#c=null;#l=null;#p=null;constructor({config:r,appSecret:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,createBot:s=c=>new PBe(c),typingMiddleware:g=GBe}){if(!r||!o||!i||!e)throw new TypeError("QqRuntime requires config, app secret, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}get status(){return structuredClone(this.#a)}async sendConnectionTest(r){if(!this.#a.ready||!this.#i)throw kt("QQ\u673A\u5668\u4EBA");let o=typeof this.#e.ownerUserOpenid=="string"?this.#e.ownerUserOpenid.trim():"",i=OE(this.#r),e=i?.scope==="c2c"&&typeof i.targetId=="string"?i.targetId.trim():"",a=e?{scope:"c2c",targetId:e}:o&&o!=="*"?{scope:"c2c",targetId:o}:null;if(!a)throw kt("QQ\u673A\u5668\u4EBA");return await this.#i.sendText(a,r),{sent:!0}}async start(){return this.#a.ready&&this.#i?this.status:this.#p?this.#p:(this.#p=this.#h().finally(()=>{this.#p=null}),this.#p)}async#h(){await this.stop(),this.#a.startedAt=new Date().toISOString(),this.#a.qqConnectionState="connecting",this.#a.lastError=null,await this.#t.ensureRunning(),this.#a.harnessReachable=!0;let r={error:(...p)=>this.#g.error?.(...p),warn:(...p)=>this.#g.warn?.(...p),info:(...p)=>this.#g.info?.(...p),debug:()=>{}},o=this.#s({appId:this.#e.appId,appSecret:this.#A,accountId:this.#e.botId,logger:r,transport:"websocket",tokenPrefetch:"sync"});if(!o||typeof o.start!="function"||typeof o.stop!="function")throw new TypeError("QQ bot factory returned an invalid client");let i=new AbortController;this.#c=i,this.#i=o,this.#o=new cQ({bot:o,ownerUserOpenid:this.#e.ownerUserOpenid,harness:this.#t,state:this.#r,status:this.#a,logger:this.#g,replyTimeoutMs:this.#n,signal:i.signal}),o.use?.(this.#I({keepAlive:!0,predicate:p=>this.#e.ownerUserOpenid==="*"||p?.message?.senderId===this.#e.ownerUserOpenid}));let e,a,A=new Promise((p,B)=>{e=p,a=B}),t=()=>{let p=Date.now();this.#a.ready=!0,this.#a.qqConnectionState="connected",this.#a.lastCheckedAt=p,this.#a.lastConnectedAt=p,this.#a.lastError=null,e()},s=p=>{this.#a.ready?(this.#a.lastError=p?.message??String(p),this.#g.warn?.(`[dsh-im:qq] bot ${this.#e.botId} connection error:`,p)):a(p)},g=(p,B)=>{let Q=this.#o?.accept(B);Q&&Q.catch(f=>{i.signal.aborted||this.#g.error?.(`[dsh-im:qq] bot ${this.#e.botId} message handling failed:`,f)})};o.on("ready",t),o.on("resumed",t),o.on("error",s),o.on("message",g);let c=Promise.resolve().then(()=>o.start(i.signal));this.#l=c,c.catch(p=>{i.signal.aborted||(a(p),this.#a.ready=!1,this.#a.qqConnectionState="failed",this.#a.lastError=p?.message??String(p),this.#g.error?.(`[dsh-im:qq] bot ${this.#e.botId} connection stopped:`,p))});let l;try{return await Promise.race([A,new Promise((p,B)=>{l=setTimeout(()=>B(FBe()),this.#E)})]),this.#a.ready=!0,this.#a.qqConnectionState="connected",this.#a.lastCheckedAt=Date.now(),this.#a.lastConnectedAt=Date.now(),this.status}catch(p){throw this.#a.ready=!1,this.#a.qqConnectionState="failed",this.#a.lastError=p?.message??String(p),await this.stop(),p}finally{clearTimeout(l)}}async stop(){let r=this.#i,o=this.#o,i=this.#l;this.#c?.abort(),this.#c=null,this.#i=null,this.#o=null,this.#l=null;try{r?.stop()}catch(e){this.#g.warn?.(`[dsh-im:qq] bot ${this.#e.botId} failed to stop cleanly:`,e)}return await Promise.race([i?.catch(()=>{})??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),await o?.waitForIdle(),this.#a.ready=!1,this.#a.qqConnectionState="idle",this.status}};import{startQrConnect as UBe}from"@tencent-connect/qqbot-connector";var IQ=class{#e;#A;constructor({start:r=UBe,source:o="deepseek-harness"}={}){if(typeof r!="function")throw new TypeError("QQ QR connector is required");this.#e=r,this.#A=o}start(r,{signal:o}={}){if(!r||typeof r.onSuccess!="function"||typeof r.onFailure!="function")throw new TypeError("QQ QR callbacks are required");return this.#e(r,{displayQrCodeToConsole:!1,source:this.#A,signal:o})}};import{mkdir as HBe,readFile as KBe,rename as YBe,unlink as xBe,writeFile as jBe}from"node:fs/promises";import{dirname as JBe}from"node:path";var lQ=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function qBe(n){if(!n||typeof n!="object")return structuredClone(lQ);let r={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(r[o]=i);return{version:1,sessions:r,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var EQ=class{#e;#A=structuredClone(lQ);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{this.#A=qBe(JSON.parse(await KBe(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(lQ),await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}snapshot(){return structuredClone(this.#A)}async remove(){try{await xBe(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(lQ)}async#r(){let r=`${JSON.stringify(this.#A,null,2)} -`,o=this.#t.then(async()=>{await HBe(JBe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await jBe(i,r,{encoding:"utf8",mode:384}),await YBe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var X1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function VBe(n){if(!Array.isArray(n)||n.length===0)return[...X1];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...X1]}var pQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=VBe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-im QQ requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function XBe(n){let r=Wg(n.dshHome??process.env.DSH_HOME??cC(WBe(),".dsh")),o=Wg(n.dataDir??cC(r,"integrations","dsh-qq"));return{config:Wg(n.configPath??cC(o,"config.json")),bots:Wg(n.botsDir??cC(o,"bots")),workspaces:Wg(n.workspacesPath??cC(o,"workspaces.json"))}}async function LN(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-im QQ requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im QQ requires ctx.webServer");let i=o.ConfigStore??aQ,e=o.StateStore??EQ,a=o.HarnessClient??oQ,A=o.Controller??sC,t=o.Runtime??gC,s=o.QrAuth??IQ,g=o.createConnectionSupervisor??FN,c=typeof n.logger=="function"?n.logger("dsh-im:qq"):n.logger??console,l=XBe(r),p=await new i(l.config).load(),B=Wg(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(T=>T.botId)),await Promise.all(y.map(T=>f.ensure(T.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=o.qrAuth??new s({source:r.qrSource??"deepseek-harness"}),k=new Map,G=T=>Wg(l.bots,T,"state.json"),K=async T=>{let V=k.get(T);return V||(V=await new e(G(T)).load(),k.set(T,V)),V},x=zr(n,o.commandExecutor),H=new a({baseUrl:ZBe(n.webServer,r.harnessBaseUrl),workspace:B,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...x?{commandExecutor:x}:{}}),q=new A({qrAuth:R,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:T,config:V,appSecret:U})=>{let b=await K(T);await f.ensure(T);let L=qr(H,{botId:T,workspaces:f,state:b});return new t({config:V,appSecret:U,harness:L.harness,state:L.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,logger:{error:(...X)=>c.error?.(`[${T}]`,...X),warn:(...X)=>c.warn?.(`[${T}]`,...X),info:(...X)=>c.info?.(`[${T}]`,...X),debug:(...X)=>c.debug?.(`[${T}]`,...X)}})},deleteState:async({botId:T})=>{let V=k.get(T);if(k.delete(T),V&&typeof V.remove=="function")await V.remove();else try{await zBe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=Vr(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import $Be from"qrcode";var e3="/qq",_r=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),A3=Object.freeze(Object.values(_r)),eQe=new Set(["appSecret","app_secret","secretRef","ownerUserOpenid","userOpenid","verificationUrl"]);function KN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function jI(n,r){return KN(n)&&Object.keys(n).every(o=>r.includes(o))}function UN(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function $1(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function AQe(n,r){return KN(r)?n===_r.status?jI(r,[])?null:"connection.status does not accept fields.":n===_r.beginProvisioning?jI(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[_r.pollProvisioning,_r.cancelProvisioning].includes(n)?jI(r,["attemptId"])&&UN(r.attemptId)?null:`${n} requires an attemptId.`:n===_r.bindCredentials?jI(r,["appId","appSecret"])&&$1(r.appId,256)&&$1(r.appSecret,1024)?null:"bot.bind-credentials requires AppID and AppSecret.":n===_r.reconnectBot?jI(r,["botId","sendTest"])&&UN(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and accepts only sendTest=true.":n===_r.deleteBot?jI(r,["botId","confirm"])&&UN(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===_r.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown QQ endpoint.":"Payload must be an object."}function JI(n){if(Array.isArray(n))return n.map(JI);if(!KN(n))return n;let r={};for(let[o,i]of Object.entries(n))eQe.has(o)||(r[o]=JI(i));return r}async function tQe(n){return $Be.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function HN(n,r){return!n||typeof n.verificationUrl!="string"?JI(n):JI({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function IC(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await HN(o.provisioning,r)),JI(o)}function t3(n,{encodeQr:r=tQe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete QQ 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(()=>r(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(!A3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown QQ endpoint."}};let t=AQe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===_r.status)s=await IC(await n.status(),i);else if(e===_r.beginProvisioning)s=await HN(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 HN(g,i)}else if(e===_r.cancelProvisioning)s=JI(await n.cancelProvisioning(a.attemptId));else if(e===_r.bindCredentials)s=await IC(await n.bindCredentials(a),i);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."}};let c;if(a.sendTest===!0)if(!(g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("QQ\u673A\u5668\u4EBA"));else{let p=null;try{await n.sendConnectionTest(a.botId)}catch(B){p=B}c=Ot(p)}s=await IC({...g,...c?{testMessage:c}:{}},i)}else if(e===_r.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await IC(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await IC(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=Xr(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"qq-operation-failed",message:"QQ \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function CQ(n,r,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(e3,t3(r,o),{authority:Wr(i)})}async function r3(n,r={}){if(r?.controller)return CQ(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await LN(n,r,r.internals),i=CQ(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close QQ bot connections"),i}import{unlink as kQe}from"node:fs/promises";import{resolve as l3}from"node:path";import{createHash as rQe}from"node:crypto";import{mkdir as aQe,readFile as iQe,rename as oQe,unlink as nQe,writeFile as sQe}from"node:fs/promises";import{dirname as gQe}from"node:path";var YN=Object.freeze({version:1,bots:Object.freeze([])}),a3=/^slack_[a-f0-9]{24}$/,cQe=/^DSH_SLACK_BOT_TOKEN_[A-F0-9]{24}$/,IQe=/^DSH_SLACK_APP_TOKEN_[A-F0-9]{24}$/;function pi(n){return typeof n=="string"&&n.trim()?n.trim():null}function xN(n){let r=pi(n);if(!r)throw new TypeError("platformId is required");let o=rQe("sha256").update(r).digest("hex").slice(0,24),i=o.toUpperCase();return{botId:`slack_${o}`,botTokenRef:`DSH_SLACK_BOT_TOKEN_${i}`,appTokenRef:`DSH_SLACK_APP_TOKEN_${i}`}}function jN(n){let r=pi(n)??"",[o,i]=r.split(":");return o&&i?`${o.slice(0,5)}\u2022\u2022\u2022 \xB7 ${i.slice(0,5)}\u2022\u2022\u2022`:r?`${r.slice(0,6)}\u2022\u2022\u2022\u2022`:"Slack\u673A\u5668\u4EBA"}var hQ=class{#e;#A=YN;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=this.#g(JSON.parse(await iQe(this.#e,"utf8")));if(!r)throw new Error("dsh-im Slack config contains invalid bot data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=YN}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByPlatformId(r){let o=this.#A.bots.find(i=>i.platformId===r);return o?structuredClone(o):null}async save(r){let o=this.#r(r);if(!o)throw new Error("Refusing to persist incomplete Slack bot data");return this.#n(i=>{if(i.find(A=>A.botId!==o.botId&&(A.platformId===o.platformId||A.botTokenRef===o.botTokenRef||A.appTokenRef===o.appTokenRef)))throw new Error("Duplicate Slack bot identity");let a=i.findIndex(A=>A.botId===o.botId);return a===-1?i.push(o):i[a]=o,structuredClone(o)})}async remove(r){if(!a3.test(r))throw new TypeError("Invalid Slack bot id");return this.#n(o=>{let i=o.findIndex(e=>e.botId===r);return i===-1?null:structuredClone(o.splice(i,1)[0])})}async clear(){let r=this.#t.then(async()=>{try{await nQe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=YN});this.#t=r.then(()=>{},()=>{}),await r}#r(r){if(!r||typeof r!="object")return null;let o=pi(r.botId),i=pi(r.platformId),e=pi(r.botTokenRef),a=pi(r.appTokenRef),A=pi(r.name);if(!o||!i||!e||!a||!A||!a3.test(o)||!cQe.test(e)||!IQe.test(a))return null;let t=xN(i);return t.botId!==o||t.botTokenRef!==e||t.appTokenRef!==a?null:Object.freeze({botId:o,platformId:i,botTokenRef:e,appTokenRef:a,name:A,username:pi(r.username),teamId:pi(r.teamId),teamName:pi(r.teamName),createdAt:pi(r.createdAt)??new Date().toISOString(),connectedAt:pi(r.connectedAt)})}#g(r){if(!r||r.version!==1||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.botTokenRef)||a.has(A.appTokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.botTokenRef),a.add(A.appTokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#n(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await aQe(gQe(this.#e),{recursive:!0,mode:448});let A=`${this.#e}.tmp`;await sQe(A,`${JSON.stringify(a,null,2)} -`,{encoding:"utf8",mode:384}),await oQe(A,this.#e),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}};var lQe="https://slack.com/api/",uQ="files.slack.com",EQe="slack.com",i3="/files-pri/",pQe=Object.freeze([uQ]);function mn(n){return typeof n=="string"&&n.trim()?n.trim():null}function CQe(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function hQe(n){return Number.isInteger(n)&&n>=300&&n<400}async function dQe(n){try{await n?.body?.cancel?.()}catch{}}function uQe(n){let r=new URL(n);if(r.protocol!=="https:")throw new Error("Image download URL must use HTTPS");if(r.username||r.password||r.port&&r.port!=="443")throw new Error("Image download URL is not hosted by the messaging platform");if(r.hostname===EQe&&r.pathname.startsWith(i3)&&(r.hostname=uQ),r.hostname!==uQ||!r.pathname.startsWith(i3))throw new Error("Image download URL is not hosted by the messaging platform");return r.hash="",r}function BQe(n,r){let o=n?.headers?.get?.("location");if(!o)return null;try{return new URL(o,r)}catch{return null}}function QQe(n){let r=n?.headers?.get?.("x-oauth-scopes");return r==null?null:new Set(r.split(",").map(o=>o.trim()).filter(Boolean))}function fQe(n){return n?.protocol==="https:"&&!n.username&&!n.password&&(!n.port||n.port==="443")&&n.hostname.endsWith(".slack.com")&&n.hostname!==uQ&&n.pathname==="/"&&n.searchParams.has("redir")}function yQe(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),r?.addEventListener("abort",()=>{clearTimeout(e),i(r.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function Zg(n,r){let o=mn(n);if(!o||!/^[A-Z][A-Z0-9]{4,30}$/i.test(o))throw new TypeError(`Invalid Slack ${r}`);return o}function dQ(n,r){let o=mn(n);if(!o)throw new TypeError(`Slack ${r} is required`);return o}function lC(n,{trim:r=!0}={}){let o=typeof n=="string"?n:"",i=r?o.trim():o;if(!i)throw new TypeError("Slack message text is required");return i.replace(/<@([A-Z0-9]+)>/gi,"@$1").replace(/]*)?>/gi,"@$1")}function mQe(n,r,o){let i=mn(r?.error)??"unknown_error",e=new Error(`Slack ${n} failed: ${i.replaceAll("_"," ")}`);return["invalid_auth","not_authed","token_revoked","account_inactive"].includes(i)?e.code=o==="app"?"slack-invalid-app-token":"slack-invalid-bot-token":i==="missing_scope"?e.code="slack-missing-scope":i==="method_not_supported_for_channel_type"||i==="channel_type_not_supported"||i==="deprecated_endpoint"?e.code="slack-stream-unavailable":e.code=`slack-${i}`,e}function o3(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())}function n3(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())}var EC=class{#e;#A;#t;#r;#g=null;constructor({botToken:r,appToken:o,fetchImpl:i=fetch,baseUrl:e=lQe}){if(r!==void 0&&!o3(r))throw new TypeError("Slack Bot Token is invalid");if(o!==void 0&&!n3(o))throw new TypeError("Slack App Token is invalid");if(!r&&!o)throw new TypeError("SlackApi requires a token");if(typeof i!="function")throw new TypeError("SlackApi requires fetch");this.#e=r?.trim(),this.#A=o?.trim(),this.#t=i,this.#r=new URL(e)}authTest(r={}){return this.#n("auth.test",{...r,tokenKind:"bot"})}openConnection(r={}){return this.#n("apps.connections.open",{...r,tokenKind:"app",body:void 0})}postMessage({channelId:r,text:o,threadTs:i,signal:e}){return this.#n("chat.postMessage",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),text:lC(o),...i?{thread_ts:mn(i)}:{},mrkdwn:!0,link_names:!1,unfurl_links:!1,unfurl_media:!1}})}updateMessage({channelId:r,ts:o,text:i,signal:e}){return this.#n("chat.update",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),ts:dQ(o,"message timestamp"),text:lC(i),parse:"none",link_names:!1}})}startStream({channelId:r,threadTs:o,recipientTeamId:i,recipientUserId:e,markdownText:a,signal:A}){return this.#n("chat.startStream",{tokenKind:"bot",signal:A,body:{channel:Zg(r,"channel id"),thread_ts:dQ(o,"thread timestamp"),...i?{recipient_team_id:Zg(i,"team id")}:{},...e?{recipient_user_id:Zg(e,"user id")}:{},...mn(a)?{markdown_text:lC(a)}:{}}})}appendStream({channelId:r,ts:o,markdownText:i,signal:e}){return this.#n("chat.appendStream",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),ts:dQ(o,"stream timestamp"),markdown_text:lC(i,{trim:!1})}})}stopStream({channelId:r,ts:o,markdownText:i,signal:e}){return this.#n("chat.stopStream",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),ts:dQ(o,"stream timestamp"),...mn(i)?{markdown_text:lC(i,{trim:!1})}:{}}})}async downloadFile({url:r,signal:o,maxBytes:i}){if(!this.#e)throw new TypeError("Slack bot token is required for file download");let e=uQe(r);return za(e,{fetchImpl:async(A,t)=>{let s=await this.#t(A,t);if(!hQe(s?.status))return s;let g=BQe(s,A);if(this.#g&&!this.#g.has("files:read")||fQe(g))throw await dQe(s),new XA("slack-file-access-required","Slack redirected a private file request to the workspace because file access was not granted","Slack \u672A\u6388\u6743\u673A\u5668\u4EBA\u8BFB\u53D6\u8BE5\u6587\u4EF6\u3002\u8BF7\u4E3A\u5E94\u7528\u6DFB\u52A0 files:read \u540E\u91CD\u65B0\u5B89\u88C5\uFF0C\u518D\u91CD\u65B0\u53D1\u9001\u56FE\u7247\u3002");return s},headers:{authorization:`Bearer ${this.#e}`},signal:o,maxBytes:i,allowedHosts:pQe})}async#n(r,{tokenKind:o,body:i,signal:e,timeoutMs:a=15e3,retry:A=!0}){let t=o==="app"?this.#A:this.#e;if(!t)throw new TypeError(`Slack ${o} token is required for ${r}`);let s;try{s=await this.#t(new URL(r,this.#r),{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":i===void 0?"application/x-www-form-urlencoded;charset=utf-8":"application/json;charset=utf-8","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.2.2)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:CQe(e,a),redirect:"error"})}catch(c){throw c?.name==="AbortError"||c?.name==="TimeoutError"?c:new Error(`Slack ${r} transport failed`)}if(o==="bot"){let c=QQe(s);c&&(this.#g=c)}let g;try{g=await s.json()}catch{throw new Error(`Slack ${r} returned invalid JSON`)}if(s.status===429&&A){let c=Number(s.headers.get("retry-after"))||1;return await yQe(Math.min(1e4,Math.max(100,c*1e3)),e),this.#n(r,{tokenKind:o,body:i,signal:e,timeoutMs:a,retry:!1})}if(!s.ok||g?.ok!==!0)throw mQe(r,g,o);return g}};async function s3({botToken:n,appToken:r},o={}){if(!o3(n)){let t=new TypeError("Slack Bot Token \u5FC5\u987B\u4EE5 xoxb- \u5F00\u5934\u3002");throw t.code="slack-invalid-bot-token",t}if(!n3(r)){let t=new TypeError("Slack App Token \u5FC5\u987B\u4EE5 xapp- \u5F00\u5934\u3002");throw t.code="slack-invalid-app-token",t}let i=new EC({botToken:n,appToken:r,...o}),[e,a]=await Promise.all([i.authTest(),i.openConnection()]);if(!e?.team_id||!e?.user_id||!e?.bot_id)throw new Error("Slack Bot Token \u6CA1\u6709\u8FD4\u56DE\u5B8C\u6574\u7684\u673A\u5668\u4EBA\u8EAB\u4EFD\u3002");let A;try{A=new URL(a?.url)}catch{A=null}if(!A||A.protocol!=="wss:"){let t=new Error("Slack App Token \u65E0\u6CD5\u521B\u5EFA Socket Mode \u8FDE\u63A5\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u542F\u7528 Socket Mode \u548C connections:write\u3002");throw t.code="slack-socket-mode",t}return{platformId:`${e.team_id}:${e.user_id}`,name:mn(e.user)??"DeepSeek Harness",username:mn(e.user),teamId:String(e.team_id),teamName:mn(e.team)}}var JN=Object.freeze({key:"slack",label:"Slack",connectionLabel:" Socket Mode \u957F\u8FDE\u63A5"}),BQ=class extends lo{constructor(r){super({descriptor:JN,...r})}};function Sn(n){return typeof n=="string"&&n.trim()?n.trim():null}function QQ(n,r){return Object.freeze({code:n,message:r})}var pC=class{#e;#A;#t;#r;#g;#n;#E=new Map;#s=new Map;#I=new Map;#a=0;#i=!1;constructor({credentials:r,configStore:o,inspectCredentials:i=s3,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!r||typeof r.resolve!="function"||typeof r.set!="function"||typeof r.unset!="function")throw new TypeError("Slack requires the DSH credential provider");if(!o||typeof o.list!="function"||typeof o.save!="function"||typeof o.remove!="function")throw new TypeError("Slack requires a config store");if(typeof i!="function"||typeof e!="function")throw new TypeError("Slack controller dependencies are incomplete");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A}async initialize(){if(this.#i)return this.status();for(let r of this.#A.list())await this.#h(r.botId,async()=>{if(this.#i||this.#E.get(r.botId)?.status?.ready)return;let o=await this.#l(r);if(!o){this.#s.set(r.botId,QQ("missing-token","Slack\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002"));return}try{await this.#o(r,o),this.#s.delete(r.botId)}catch(i){this.#s.set(r.botId,QQ("connection-failed","Slack Socket Mode \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#n.warn?.(`[dsh-im:slack] bot ${r.botId} failed to initialize:`,i)}finally{this.#C()}});return this.status()}async bindCredentials({botToken:r,appToken:o}={}){if(this.#i)throw new Error("Slack controller is closed");let i=Sn(r),e=Sn(o);if(!i||!e)throw new TypeError("Slack Bot Token and App Token are required");let a=await this.#t({botToken:i,appToken:e}),A=Sn(a?.platformId),t=Sn(a?.name);if(!A||!t)throw new Error("Slack returned an invalid bot identity");let s=xN(A);return await this.#h(s.botId,async()=>{if(this.#i)throw new Error("Slack controller is closed");let g=this.#A.getByPlatformId(A),c=await this.#e.resolve(s.botTokenRef).catch(()=>{}),l=await this.#e.resolve(s.appTokenRef).catch(()=>{}),p={...s,platformId:A,name:t,username:Sn(a.username),teamId:Sn(a.teamId),teamName:Sn(a.teamName),createdAt:g?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};try{await this.#e.set(s.botTokenRef,i),await this.#e.set(s.appTokenRef,e),await this.#A.save(p)}catch(B){throw await Promise.all([this.#p(s.botTokenRef,c),this.#p(s.appTokenRef,l)]),B}try{await this.#o(p,{botToken:i,appToken:e}),this.#s.delete(s.botId)}catch(B){this.#s.set(s.botId,QQ("connection-failed","Slack\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0CSocket Mode \u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:slack] bot ${s.botId} credential connection failed:`,B)}this.#C()}),this.status()}async reconnectBot(r){let o=this.#A.get(r);if(!o)throw new Error("Unknown Slack bot");return await this.#h(r,async()=>{let i=await this.#l(o);if(!i)throw new Error("Slack bot credentials are missing");try{await this.#o(o,i),this.#s.delete(r)}catch(e){throw this.#s.set(r,QQ("connection-failed","Slack Socket Mode \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u68C0\u67E5\u4E24\u4E2A Token\u3002")),e}finally{this.#C()}}),this.status()}async sendConnectionTest(r){let o=this.#A.get(r);if(!o)throw new Error("Unknown Slack bot");return this.#h(r,async()=>{let i=this.#E.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(Yr(`${o.name}\uFF08${jN(o.platformId)}\uFF09`,"Slack\u673A\u5668\u4EBA")),{sent:!0}})}async deleteBot(r){let o=this.#A.get(r);if(!o)throw new Error("Unknown Slack bot");return await this.#h(r,async()=>{let i=await this.#e.resolve(o.botTokenRef).catch(()=>{}),e=await this.#e.resolve(o.appTokenRef).catch(()=>{});await this.#c(r);try{await this.#e.unset(o.botTokenRef),await this.#e.unset(o.appTokenRef),await this.#A.remove(r)}catch(a){throw await Promise.all([this.#p(o.botTokenRef,i),this.#p(o.appTokenRef,e)]),i?.value&&e?.value&&await this.#o(o,{botToken:i.value,appToken:e.value}).catch(()=>{}),new Error("Unable to remove the Slack bot safely.",{cause:a})}await this.#g({botId:r,config:o}).catch(a=>{this.#n.warn?.(`[dsh-im:slack] bot ${r} state cleanup failed:`,a)}),this.#s.delete(r),this.#C()}),this.status()}status(){let r=this.#A.list().map(i=>{let e=this.#E.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#s.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,teamName:i.teamName,idMasked:jN(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?`Slack${JN.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?"Slack\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"Slack\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},error:structuredClone(this.#s.get(i.botId)??null)}}),o=r.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#a,state:r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o}}}async close(){this.#i||(this.#i=!0,await Promise.allSettled([...this.#I.values()]),await Promise.allSettled([...this.#E.keys()].map(r=>this.#c(r))))}async#o(r,{botToken:o,appToken:i}){if(this.#i)throw new Error("Slack controller is closed");if(await this.#c(r.botId),this.#i)throw new Error("Slack controller is closed");let e=await this.#r({botId:r.botId,config:r,botToken:o,appToken:i});if(!e||typeof e.start!="function"||typeof e.stop!="function")throw new TypeError("createRuntime returned an invalid Slack runtime");this.#E.set(r.botId,e);try{await e.start()}catch(a){throw await e.stop().catch(()=>{}),this.#E.delete(r.botId),a}}async#c(r){let o=this.#E.get(r);this.#E.delete(r),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:slack] bot ${r} failed to stop cleanly:`,i)})}async#l(r){let[o,i]=await Promise.all([this.#e.resolve(r.botTokenRef).catch(()=>{}),this.#e.resolve(r.appTokenRef).catch(()=>{})]),e=Sn(o?.value),a=Sn(i?.value);return e&&a?{botToken:e,appToken:a}:null}async#p(r,o){o?.value?await this.#e.set(r,o.value).catch(()=>{}):await this.#e.unset(r).catch(()=>{})}#h(r,o){let a=(this.#I.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#I.get(r)===a&&this.#I.delete(r)});return this.#I.set(r,a),a}#C(){this.#a+=1}};var fQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"slack",logPrefix:"dsh-slack"})}};var g3=Object.freeze([1e3,3e3,5e3,1e4,3e4]),VN=38e3,c3=11e3,SQe=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function qN(n,r,o){if(typeof n.addEventListener=="function")n.addEventListener(r,o);else if(typeof n.on=="function")n.on(r,o);else throw new TypeError("Slack WebSocket does not support events")}function DQe(n){let r=n?.data??n;return typeof r=="string"?r:Buffer.isBuffer(r)?r.toString("utf8"):r instanceof ArrayBuffer?Buffer.from(r).toString("utf8"):ArrayBuffer.isView(r)?Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):null}function wQe(n){let r=new URL(n);if(r.protocol!=="wss:")throw new Error("Slack returned an insecure Socket Mode URL");return r.href}function OQe(n){return typeof n=="string"?n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"):""}function MQe(n,r){return OQe(n).replace(new RegExp(`<@${r}>`,"gi"),"").trim()}function bQe(n,r){let o=typeof n?.mimetype=="string"?n.mimetype.toLowerCase():"",i=typeof n?.url_private_download=="string"&&n.url_private_download?n.url_private_download:n?.url_private;return!SQe.has(o)||typeof i!="string"||!i?null:{name:typeof n.name=="string"?n.name:void 0,mediaType:o,size:Number.isSafeInteger(n.size)&&n.size>=0?n.size:void 0,load:e=>r(i,e)}}function _Qe(n,r,{loadFile:o=async()=>{throw new Error("Slack file downloader is unavailable")}}={}){let i=n?.event;if(!i||!n?.event_id||!i.channel||!i.user||!i.ts)return null;let e=i.type==="message"&&i.channel_type==="im",a=i.type==="app_mention";if(!e&&!a||i.subtype&&i.subtype!=="file_share"||i.bot_id||i.app_id)return null;let A=String(i.thread_ts??i.ts);return{messageId:String(n.event_id),senderId:String(i.user),senderIsBot:String(i.user)===String(r),kind:e?"direct":"group",conversationId:e?String(i.channel):`${i.channel}:${A}`,content:MQe(i.text??"",r),images:Array.isArray(i.files)?i.files.map(t=>bQe(t,o)).filter(Boolean):[],addressed:e||a,replyTarget:{channelId:String(i.channel),threadTs:A,recipientUserId:String(i.user),recipientTeamId:String(i.user_team??n.team_id??"")},connectionTestTarget:{channelId:String(i.channel)}}}function NQe(n){return typeof n=="string"&&/^正在使用.+…$/.test(n.trim())}async function I3(n,r,o,i,e){if(i)for(let a=0;a{let f=ii(Q,VN)[0]??"";if(!f||!f.startsWith(A))return;let y=f.slice(A.length);y&&(await I3(n,r,a,y,o),A=f)},B=()=>{l||c||s!==null||g||!t||(s=setTimeout(()=>{s=null;let Q=t;t="",g=p(Q).catch(f=>{c=!0,i.warn?.("[dsh-im:slack] streaming append failed:",f)}).finally(()=>{g=null,B()})},350),s?.unref?.())};return{update(Q){l||c||typeof Q!="string"||!Q.trim()||NQe(Q)||(t=Q,B())},async finish(Q){if(l)throw new Error("Slack message stream is already closed");l=!0,s!==null&&clearTimeout(s),s=null,t="",await g?.catch(()=>{});let f=ii(Q,VN),y=f[0]??"\u5904\u7406\u5B8C\u6210\u3002";!c&&y.startsWith(A)?(await I3(n,r,a,y.slice(A.length),o),await n.stopStream({channelId:r.channelId,ts:a,signal:o})):(await n.stopStream({channelId:r.channelId,ts:a,signal:o}).catch(()=>{}),await n.updateMessage({channelId:r.channelId,ts:a,text:y,signal:o}));for(let m of f.slice(1))await n.postMessage({channelId:r.channelId,threadTs:r.threadTs,text:m,signal:o})},cancel(){l=!0,t="",s!==null&&clearTimeout(s),s=null,n.stopStream({channelId:r.channelId,ts:a,signal:o}).catch(()=>{})}}}var zN=class{#e;#A;#t;constructor({api:r,signal:o,logger:i}){this.#e=r,this.#A=o,this.#t=i}async sendText(r,o){let i=ii(o,VN),e=null;for(let a of i)e=await this.#e.postMessage({channelId:r.channelId,threadTs:r.threadTs,text:a,signal:this.#A});return e}openStream(r){return TQe({api:this.#e,target:r,signal:this.#A,logger:this.#t})}};function RQe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var CC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i=RQe();#o=null;#c=null;#l=null;#p=null;#h=null;#C=null;#d=0;#Q=0;#u=!0;#B=null;constructor({config:r,botToken:o,appToken:i,harness:e,state:a,logger:A=console,replyTimeoutMs:t=6e5,connectTimeoutMs:s=2e4,createApi:g=l=>new EC(l),createWebSocket:c=l=>new WebSocket(l)}){if(!r||!o||!i||!e||!a)throw new TypeError("SlackRuntime requires config, both tokens, Harness, and state");if(typeof c!="function")throw new TypeError("SlackRuntime requires WebSocket");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#a=c}get status(){return structuredClone(this.#i)}async sendConnectionTest(r){if(!this.#i.ready||!this.#c){let o=new Error("Slack bot is not connected");throw o.code="test-target-unavailable",o}return this.#c.sendConnectionTest(r)}async start(){return this.#i.ready&&this.#p?this.status:this.#B?this.#B:(this.#B=this.#y().finally(()=>{this.#B=null}),this.#B)}async#y(){await this.stop(),this.#u=!1,this.#d=0,this.#i.startedAt=new Date().toISOString(),this.#i.connectionState="connecting",this.#i.lastError=null,await this.#r.ensureRunning(),this.#i.harnessReachable=!0;let r=new AbortController;this.#l=r;let o=this.#I({botToken:this.#A,appToken:this.#t});this.#o=o;try{let i=await o.authTest({signal:r.signal});if(`${i?.team_id}:${i?.user_id}`!==this.#e.platformId)throw new Error("Slack Bot Token identity does not match the saved bot");let e=new zN({api:o,signal:r.signal,logger:this.#n});this.#c=new BQ({bot:e,harness:this.#r,state:this.#g,status:this.#i,logger:this.#n,replyTimeoutMs:this.#E,signal:r.signal});let a;try{await Promise.race([this.#f(),new Promise((A,t)=>{a=setTimeout(()=>t(new Error("Slack Socket Mode did not become ready in time")),this.#s),a?.unref?.()})])}finally{clearTimeout(a)}return this.status}catch(i){throw this.#i.ready=!1,this.#i.connectionState="failed",this.#i.lastError=i?.message??String(i),await this.stop(),i}}async#f(){if(this.#u)throw new Error("Slack runtime is stopped");let r=await this.#o.openConnection({signal:this.#l?.signal});return this.#D(r?.url)}#D(r){if(this.#u)return Promise.reject(new Error("Slack runtime is stopped"));let o=++this.#Q,i=this.#a(wQe(r));this.#p=i;let e=!1;return new Promise((a,A)=>{let t=s=>{if(e||o!==this.#Q)return;e=!0,this.#h=s?.connection_info?.app_id??null,this.#d=0;let g=Date.now();this.#i.ready=!0,this.#i.connectionState="connected",this.#i.lastCheckedAt=g,this.#i.lastConnectedAt=g,this.#i.lastError=null,a()};qN(i,"message",s=>{if(o!==this.#Q||this.#u)return;let g=DQe(s);if(!g)return;let c;try{c=JSON.parse(g)}catch{this.#n.warn?.("[dsh-im:slack] ignored malformed Socket Mode JSON");return}if(c.type==="hello"){t(c);return}if(c.envelope_id&&i.readyState===1&&(i.send(JSON.stringify({envelope_id:c.envelope_id})),this.#i.lastCheckedAt=Date.now()),c.type==="disconnect"){i.close(4e3,"Slack requested reconnect");return}if(c.type!=="events_api"||c.payload?.type!=="event_callback"||this.#h&&c.payload.api_app_id&&c.payload.api_app_id!==this.#h)return;let l=_Qe(c.payload,this.#e.platformId.split(":")[1],{loadFile:(B,Q)=>this.#o.downloadFile({url:B,...Q})}),p=this.#c;l&&p&&p.accept(l).catch(B=>{o!==this.#Q||this.#u||this.#n.error?.(`[dsh-im:slack] bot ${this.#e.botId} message handling failed:`,B)})}),qN(i,"close",(s={})=>{if(o!==this.#Q)return;if(this.#p===i&&(this.#p=null),this.#u){e||A(new DOMException("Stopped","AbortError"));return}let g=Number(s.code)||0,c=new Error(`Slack Socket Mode closed (${g||"unknown"})`);this.#i.ready=!1,this.#i.connectionState="connecting",this.#i.lastError=c.message,e||(e=!0,A(c)),this.#m()}),qN(i,"error",()=>{o!==this.#Q||this.#u||(this.#i.lastError="Slack Socket Mode WebSocket error")})})}#m(){if(this.#u||this.#C!==null)return;let r=g3[Math.min(this.#d,g3.length-1)];this.#d+=1,this.#C=setTimeout(()=>{this.#C=null,this.#f().catch(o=>{this.#u||(this.#n.warn?.("[dsh-im:slack] Socket Mode reconnect failed:",o),this.#m())})},r),this.#C?.unref?.()}async stop(){this.#u=!0,this.#Q+=1,this.#l?.abort(),this.#l=null,this.#C!==null&&clearTimeout(this.#C),this.#C=null;let r=this.#p,o=this.#c;this.#p=null,this.#c=null,this.#o=null,this.#h=null;try{r&&r.readyState<2&&r.close(1e3,"Plugin stopped")}catch(i){this.#n.warn?.(`[dsh-im:slack] bot ${this.#e.botId} failed to close Socket Mode:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#i.ready=!1,this.#i.connectionState="idle",this.status}};var yQ=class extends Eo{};async function WN(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-im slack requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im slack requires ctx.webServer");let i=o.ConfigStore??hQ,e=o.StateStore??yQ,a=o.HarnessClient??fQ,A=o.Controller??pC,t=o.Runtime??CC,s=o.createConnectionSupervisor??eI,g=typeof n.logger=="function"?n.logger("dsh-im:slack"):n.logger??console,c=yD(r,"slack"),l=await new i(c.config).load(),p=l3(r.workspace??process.cwd()),B=o.WorkspaceStore??Cr,Q=o.workspaces??await new B(c.workspaces,{defaultWorkspace:p}).load(),f=l.list();await Q.reconcile(f.map(j=>j.botId)),await Promise.all(f.map(j=>Q.ensure(j.botId)));let y=typeof l.remove=="function"?Jr(l,{workspaces:Q}):l,m=new Map,R=j=>l3(c.bots,j,"state.json"),k=async j=>{let F=m.get(j);return F||(F=await new e(R(j)).load(),m.set(j,F)),F},G=zr(n,o.commandExecutor),K=new a({baseUrl:fD(n.webServer,r.harnessBaseUrl),workspace:p,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...G?{commandExecutor:G}:{}}),x=new A({credentials:n.credentials,configStore:y,logger:g,...o.inspectCredentials?{inspectCredentials:o.inspectCredentials}:{},createRuntime:async({botId:j,config:F,botToken:T,appToken:V})=>{let U=await k(j);await Q.ensure(j);let b=qr(K,{botId:j,workspaces:Q,state:U});return new t({config:F,botToken:T,appToken:V,harness:b.harness,state:b.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,logger:{error:(...L)=>g.error?.(`[${j}]`,...L),warn:(...L)=>g.warn?.(`[${j}]`,...L),info:(...L)=>g.info?.(`[${j}]`,...L),debug:(...L)=>g.debug?.(`[${j}]`,...L)}})},deleteState:async({botId:j})=>{let F=m.get(j);if(m.delete(j),F&&typeof F.remove=="function")await F.remove();else try{await kQe(R(j))}catch(T){if(T?.code!=="ENOENT")throw T}}}),H=Vr(x,{workspaces:Q,stateFor:k}),q=s({channel:"slack",controller:H,harness:K,logger:g,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:H,ready:q.ready,async close(){await q.close(),await H.close(),K.stopManagedProcess()}}}var p3="/slack",Ji=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),C3=Object.freeze(Object.values(Ji)),vQe=new Set(["token","botToken","appToken","botTokenRef","appTokenRef","tokenRef","platformId","secret","secretRef"]);function XN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function mQ(n,r){return XN(n)&&Object.keys(n).every(o=>r.includes(o))}function E3(n){return typeof n=="string"&&/^slack_[a-f0-9]{24}$/.test(n)}function PQe(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function GQe(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function FQe(n,r){return XN(r)?n===Ji.status?mQ(r,[])?null:"connection.status does not accept fields.":n===Ji.bindCredentials?mQ(r,["botToken","appToken"])&&PQe(r.botToken)&&GQe(r.appToken)?null:"bot.bind-credentials requires xoxb Bot Token and xapp App Token.":n===Ji.reconnectBot?mQ(r,["botId","sendTest"])&&E3(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===Ji.deleteBot?mQ(r,["botId","confirm"])&&E3(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Ji.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Slack endpoint.":"Payload must be an object."}function ZN(n){if(Array.isArray(n))return n.map(ZN);if(!XN(n))return n;let r={};for(let[o,i]of Object.entries(n))vQe.has(o)||(r[o]=ZN(i));return r}function LQe(n){let r=Xr(n);return r||(n?.code==="slack-invalid-bot-token"?{code:"invalid-bot-token",message:"Slack Bot Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xoxb- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-invalid-app-token"?{code:"invalid-app-token",message:"Slack App Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xapp- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-missing-scope"?{code:"missing-scope",message:"Slack \u5E94\u7528\u6743\u9650\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u65B0\u5BFC\u5165 Manifest \u5E76\u5B89\u88C5\u5230\u5DE5\u4F5C\u533A\u3002"}:n?.code==="slack-socket-mode"?{code:"socket-mode-unavailable",message:n.message}:{code:"slack-operation-failed",message:"Slack \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"})}function h3(n){for(let r of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[r]!="function")throw new TypeError(`A complete Slack controller is required (${r})`);return async(r,o,i)=>{if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!C3.includes(r))return{ok:!1,error:{code:"bad-request",message:"Unknown Slack endpoint."}};let e=FQe(r,o);if(e)return{ok:!1,error:{code:"bad-request",message:e}};try{let a;if(r===Ji.status)a=await n.status();else if(r===Ji.bindCredentials)a=await n.bindCredentials(o);else if(r===Ji.reconnectBot){if(a=await n.reconnectBot(o.botId),i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(o.sendTest===!0){let A=null;try{if(a?.bots?.find(t=>t?.botId===o.botId)?.connected!==!0){let t=new Error("Bot is not connected");throw t.code="test-target-unavailable",t}if(typeof n.sendConnectionTest!="function"){let t=new Error("Connection test is unavailable");throw t.code="test-target-unavailable",t}await n.sendConnectionTest(o.botId)}catch(t){A=t}a={...a,testMessage:Ot(A)}}}else if(r===Ji.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");a=await n.updateWorkspace(o.botId,o.workspace)}else a=await n.deleteBot(o.botId);return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:ZN(a)}}catch(a){return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:LQe(a)}}}}function SQ(n,r,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(p3,h3(r),{authority:Wr(o)})}async function d3(n,r={}){if(r?.controller)return SQ(n,r.controller,r.rpcAuthority);let o=await WN(n,r,r.internals??{}),i=SQ(n,o.controller,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Slack bot connections"),i}var u3=Object.freeze({botPrefix:"telegram",tokenRefPrefix:"DSH_TELEGRAM_BOT_TOKEN"});function B3(n){return PE(n,u3)}function Q3(n){return kd(n,"Telegram\u673A\u5668\u4EBA")}var DQ=class extends Zc{constructor(r){super(r,{channel:"Telegram",...u3})}};var wQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"telegram",logPrefix:"dsh-telegram"})}};var UQe="https://api.telegram.org/",HQe=Object.freeze(["api.telegram.org"]);function hC(n){return typeof n=="string"&&n.trim()?n.trim():null}function KQe(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function YQe(n){return typeof n=="string"&&/^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(n.trim())}var dC=class{#e;#A;#t;constructor({token:r,fetchImpl:o=fetch,baseUrl:i=UQe}){if(!YQe(r))throw new TypeError("Telegram Bot Token is invalid");if(typeof o!="function")throw new TypeError("TelegramApi requires fetch");this.#e=r.trim(),this.#A=o,this.#t=new URL(i)}async getMe(r={}){return this.#r("getMe",{},r)}async getWebhookInfo(r={}){return this.#r("getWebhookInfo",{},r)}async getUpdates({offset:r,timeout:o=25,signal:i}={}){let e={timeout:o,limit:100,allowed_updates:["message"],...Number.isSafeInteger(r)?{offset:r}:{}};return this.#r("getUpdates",e,{signal:i,timeoutMs:Math.max(1e4,(o+10)*1e3)})}async getFile({fileId:r,signal:o}={}){let i=hC(r);if(!i||!/^[A-Za-z0-9_-]{1,512}$/.test(i))throw new TypeError("Telegram file id is invalid");return this.#r("getFile",{file_id:i},{signal:o})}async downloadFile({fileId:r,signal:o,maxBytes:i}={}){let e=await this.getFile({fileId:r,signal:o}),a=hC(e?.file_path);if(!a||a.startsWith("/")||a.includes("\\")||a.includes("?")||a.includes("#"))throw new Error("Telegram returned an invalid file path");let A;try{A=a.split("/").map(s=>decodeURIComponent(s))}catch{throw new Error("Telegram returned an invalid file path")}if(A.some(s=>!s||s==="."||s===".."))throw new Error("Telegram returned an invalid file path");let t=new URL(this.#t);return t.pathname=`/file/bot${this.#e}/${a}`,za(t,{fetchImpl:this.#A,signal:o,maxBytes:i,allowedHosts:HQe})}async sendMessage({chatId:r,text:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#r("sendMessage",{chat_id:r,text:o,link_preview_options:{is_disabled:!0},...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async editMessageText({chatId:r,messageId:o,text:i,signal:e}){return this.#r("editMessageText",{chat_id:r,message_id:o,text:i,link_preview_options:{is_disabled:!0}},{signal:e})}async sendChatAction({chatId:r,messageThreadId:o,signal:i}){return this.#r("sendChatAction",{chat_id:r,action:"typing",...o?{message_thread_id:o}:{}},{signal:i})}async#r(r,o,{signal:i,timeoutMs:e=15e3}={}){let a=new URL(this.#t);a.pathname=`${a.pathname.replace(/\/$/,"")}/bot${this.#e}/${r}`;let A;try{A=await this.#A(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),signal:KQe(i,e),redirect:"error"})}catch(s){throw s?.name==="AbortError"||s?.name==="TimeoutError"?s:new Error(`Telegram ${r} transport failed`)}let t;try{t=await A.json()}catch{throw new Error(`Telegram ${r} returned invalid JSON`)}if(!A.ok||t?.ok!==!0){let s=hC(t?.description),g=new Error(s??`Telegram ${r} failed`);throw g.code=Number.isInteger(t?.error_code)?`telegram-${t.error_code}`:"telegram-api-error",g}return t.result}};async function f3(n,r={}){let i=await new dC({token:n,...r}).getMe();if(!i?.id||i?.is_bot!==!0)throw new Error("Telegram token does not belong to a bot");return{platformId:String(i.id),name:hC([i.first_name,i.last_name].filter(Boolean).join(" "))??"Telegram\u673A\u5668\u4EBA",username:hC(i.username)}}var $N=Object.freeze({key:"telegram",label:"Telegram",connectionLabel:" Bot API \u957F\u8F6E\u8BE2"}),OQ=class extends lo{constructor(r){super({descriptor:$N,...r})}};var uC=class extends Xc{constructor(r){super({...r,descriptor:$N,inspectToken:r.inspectToken??f3,deriveIdentity:B3,maskPlatformId:Q3})}};function xQe(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jQe(n,r){return r?[[n?.text,n?.entities],[n?.caption,n?.caption_entities]].some(([o,i])=>typeof o=="string"&&Array.isArray(i)&&i.some(e=>e?.type!=="mention"||!Number.isInteger(e.offset)||!Number.isInteger(e.length)?!1:o.slice(e.offset,e.offset+e.length).toLowerCase()===`@${r.toLowerCase()}`)):!1}function JQe(n,r){return!r||typeof n!="string"?n:n.replace(new RegExp(`@${xQe(r)}\\b`,"ig"),"").trim()}var qQe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),VQe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]);function zQe(n){let r=n?.mime_type??n?.mimetype,o=typeof r=="string"?r.toLowerCase():"";if(qQe.has(o))return o;let i=typeof n?.file_name=="string"?n.file_name.toLowerCase():"";for(let[e,a]of VQe)if(i.endsWith(e))return a;return null}function m3(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function y3(n){return m3(n?.file_size)??(Number(n?.width)||0)*(Number(n?.height)||0)}function WQe(n,r){let o,i,e;if(Array.isArray(n?.photo)&&n.photo.length>0)o=n.photo.reduce((a,A)=>y3(A)>y3(a)?A:a),i="image/jpeg",e=`${o.file_unique_id??o.file_id??"telegram-photo"}.jpg`;else if(n?.document){let a=zQe(n.document);if(!a)return null;o=n.document,i=a,e=typeof o.file_name=="string"?o.file_name:void 0}return!o||typeof o.file_id!="string"?null:{name:e,mediaType:i,size:m3(o.file_size),load:a=>r(o.file_id,a)}}function ZQe(n,{botId:r,username:o,loadFile:i=async()=>{throw new Error("Telegram file downloader is unavailable")}}){let e=n?.message,a=e?.chat?.id,A=e?.from?.id,t=e?.message_id;if(!Number.isSafeInteger(n?.update_id)||a===void 0||A===void 0||!Number.isSafeInteger(t)||!["private","group","supergroup"].includes(e.chat?.type))return null;let s=e.chat.type==="private",g=s||String(e.reply_to_message?.from?.id??"")===String(r)||jQe(e,o),c=Number.isSafeInteger(e.message_thread_id)?e.message_thread_id:void 0,l=WQe(e,i);return{messageId:String(n.update_id),senderId:String(A),senderIsBot:e.from?.is_bot===!0,kind:s?"direct":"group",conversationId:c===void 0?String(a):`${a}:${c}`,content:JQe(e.text??e.caption??"",o),images:l?[l]:[],addressed:g,replyTarget:{chatId:a,replyToMessageId:t,messageThreadId:c},connectionTestTarget:{chatId:a,messageThreadId:c}}}var e0=class{#e;#A;constructor({api:r,signal:o}){this.#e=r,this.#A=o}async sendText(r,o){let i=ii(o,4e3),e=null;for(let[a,A]of i.entries())e=await this.#e.sendMessage({chatId:r.chatId,text:A,replyToMessageId:a===0?r.replyToMessageId:void 0,messageThreadId:r.messageThreadId,signal:this.#A});return e}sendTyping(r){return this.#e.sendChatAction({chatId:r.chatId,messageThreadId:r.messageThreadId,signal:this.#A})}async openStream(r){return Ld({limit:4e3,create:async i=>(await this.#e.sendMessage({chatId:r.chatId,text:i,replyToMessageId:r.replyToMessageId,messageThreadId:r.messageThreadId,signal:this.#A})).message_id,edit:(i,e)=>this.#e.editMessageText({chatId:r.chatId,messageId:i,text:e,signal:this.#A}),sendRemainder:i=>this.#e.sendMessage({chatId:r.chatId,text:i,messageThreadId:r.messageThreadId,signal:this.#A})}).start()}};function XQe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var BC=class{#e;#A;#t;#r;#g;#n;#E;#s=XQe();#I=null;#a=null;#i=null;#o=null;#c=null;constructor({config:r,token:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,createApi:t=s=>new dC(s)}){if(!r||!o||!i||!e)throw new TypeError("TelegramRuntime requires config, token, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t}get status(){return structuredClone(this.#s)}async sendConnectionTest(r){if(!this.#s.ready||!this.#a){let o=new Error("Telegram bot is not connected");throw o.code="test-target-unavailable",o}return this.#a.sendConnectionTest(r)}async start(){return this.#s.ready&&this.#o?this.status:this.#c?this.#c:(this.#c=this.#l().finally(()=>{this.#c=null}),this.#c)}async#l(){await this.stop(),this.#s.startedAt=new Date().toISOString(),this.#s.connectionState="connecting",this.#s.lastError=null,await this.#t.ensureRunning(),this.#s.harnessReachable=!0;let r=new AbortController;this.#i=r;let o=this.#E({token:this.#A});this.#I=o;try{let i=await o.getMe({signal:r.signal});if(String(i?.id??"")!==this.#e.platformId||i?.is_bot!==!0)throw new Error("Telegram token identity does not match the saved bot");let e=await o.getWebhookInfo({signal:r.signal});if(typeof e?.url=="string"&&e.url){let s=new Error("\u8BE5 Telegram \u673A\u5668\u4EBA\u5DF2\u914D\u7F6E Webhook\uFF0C\u8BF7\u5148\u5728\u539F\u670D\u52A1\u4E2D\u79FB\u9664 Webhook \u540E\u91CD\u8BD5\u3002");throw s.code="webhook-configured",s}let a=new e0({api:o,signal:r.signal});this.#a=new OQ({bot:a,harness:this.#t,state:this.#r,status:this.#s,logger:this.#g,replyTimeoutMs:this.#n,signal:r.signal});let A=this.#r.cursor();if(A===null){let s=await o.getUpdates({offset:-1,timeout:0,signal:r.signal});A=s.length>0?s.at(-1).update_id+1:0,await this.#r.setCursor(A)}let t=Date.now();return this.#s.ready=!0,this.#s.connectionState="connected",this.#s.lastCheckedAt=t,this.#s.lastConnectedAt=t,this.#o=this.#p(A,r.signal),this.#o.catch(s=>{r.signal.aborted||(this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=s?.message??String(s),this.#g.error?.(`[dsh-im:telegram] bot ${this.#e.botId} polling stopped:`,s))}),this.status}catch(i){throw this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=i?.message??String(i),await this.stop(),i}}async#p(r,o){let i=r;for(;!o.aborted;){let e=await this.#I.getUpdates({offset:i,timeout:25,signal:o});this.#s.lastCheckedAt=Date.now();for(let a of e){if(o.aborted)return;let A=ZQe(a,{botId:this.#e.platformId,username:this.#e.username,loadFile:(t,s)=>this.#I.downloadFile({fileId:t,...s})});A&&this.#a.accept(A).catch(t=>{o.aborted||this.#g.error?.(`[dsh-im:telegram] bot ${this.#e.botId} message handling failed:`,t)}),i=a.update_id+1,await this.#r.setCursor(i)}}}async stop(){let r=this.#o,o=this.#a;return this.#i?.abort(),this.#i=null,this.#o=null,this.#I=null,this.#a=null,await Promise.race([r?.catch(()=>{})??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#s.ready=!1,this.#s.connectionState="idle",this.status}};var MQ=class extends Eo{};function A0(n,r={},o={}){return Kd(n,r,o,{channel:"telegram",ConfigStore:DQ,StateStore:MQ,HarnessClient:wQ,Controller:uC,Runtime:BC})}var S3="/telegram",D3=ua,$Qe=Object.freeze(Object.values(D3));function bQ(n,r,o){return xd(n,r,{channel:"Telegram",rpcChannel:S3,authority:o})}async function w3(n,r={}){if(r?.controller)return bQ(n,r.controller,r.rpcAuthority);let o=await A0(n,r,r.internals??{}),i=bQ(n,o.controller,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Telegram bot connections"),i}import{unlink as Pfe}from"node:fs/promises";import{homedir as Gfe}from"node:os";import{join as mC,resolve as tc}from"node:path";import{createHash as efe}from"node:crypto";import{mkdir as Afe,readFile as tfe,rename as rfe,unlink as afe,writeFile as ife}from"node:fs/promises";import{dirname as ofe}from"node:path";var t0=Object.freeze({version:1,bots:Object.freeze([])});function Xg(n){return typeof n=="string"&&n.trim()?n.trim():null}function O3(n){let r=Xg(n);return r&&/^wecom_[a-f0-9]{24}$/.test(r)?r:null}function nfe(n){let r=Xg(n);return r&&/^DSH_WECOM_BOT_SECRET_[A-F0-9]{24}$/.test(r)?r:null}function NQ(n){let r=Xg(n);if(!r)throw new TypeError("Enterprise WeChat bot ID is required");let o=efe("sha256").update(r).digest("hex").slice(0,24);return{botId:`wecom_${o}`,secretRef:`DSH_WECOM_BOT_SECRET_${o.toUpperCase()}`}}function r0(n){let r=Xg(n)??"";return r?r.length<=10?`${r.slice(0,3)}\u2022\u2022\u2022`:`${r.slice(0,6)}\u2022\u2022\u2022\u2022${r.slice(-4)}`:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"}function M3(n){if(!n||typeof n!="object")return null;let r=O3(n.botId),o=Xg(n.remoteBotId),i=nfe(n.secretRef);if(!r||!o||!i)return null;let e=NQ(o);return e.botId!==r||e.secretRef!==i?null:Object.freeze({botId:r,remoteBotId:o,secretRef:i,createdAt:Xg(n.createdAt)??new Date().toISOString(),connectedAt:Xg(n.connectedAt)})}function sfe(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let r=n.bots.map(M3);if(r.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of r){if(o.has(a.botId)||i.has(a.remoteBotId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.remoteBotId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(r)})}var _Q=class{#e;#A=t0;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=sfe(JSON.parse(await tfe(this.#e,"utf8")));if(!r)throw new Error("dsh-im Enterprise WeChat config contains invalid bot data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=t0}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByRemoteBotId(r){let o=this.#A.bots.find(i=>i.remoteBotId===r);return o?structuredClone(o):null}async save(r){let o=M3(r);if(!o)throw new Error("Refusing to persist incomplete Enterprise WeChat bot data");return this.#r(i=>{let e=i.find(t=>t.remoteBotId===o.remoteBotId&&t.botId!==o.botId),a=i.find(t=>t.secretRef===o.secretRef&&t.botId!==o.botId);if(e||a)throw new Error("Duplicate Enterprise WeChat bot identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!O3(r))throw new TypeError("Invalid Enterprise WeChat bot ID");return this.#r(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await afe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=t0});this.#t=r.then(()=>{},()=>{}),await r}async#r(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(r){await Afe(ofe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await ife(o,`${JSON.stringify(r,null,2)} +`,o=this.#t.then(async()=>{await HBe(JBe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await jBe(i,r,{encoding:"utf8",mode:384}),await YBe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var X1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function VBe(n){if(!Array.isArray(n)||n.length===0)return[...X1];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...X1]}var pQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=VBe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-im QQ requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function XBe(n){let r=Wg(n.dshHome??process.env.DSH_HOME??cC(WBe(),".dsh")),o=Wg(n.dataDir??cC(r,"integrations","dsh-qq"));return{config:Wg(n.configPath??cC(o,"config.json")),bots:Wg(n.botsDir??cC(o,"bots")),workspaces:Wg(n.workspacesPath??cC(o,"workspaces.json"))}}async function LN(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-im QQ requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im QQ requires ctx.webServer");let i=o.ConfigStore??aQ,e=o.StateStore??EQ,a=o.HarnessClient??oQ,A=o.Controller??sC,t=o.Runtime??gC,s=o.QrAuth??IQ,g=o.createConnectionSupervisor??FN,c=typeof n.logger=="function"?n.logger("dsh-im:qq"):n.logger??console,l=XBe(r),p=await new i(l.config).load(),B=Wg(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(T=>T.botId)),await Promise.all(y.map(T=>f.ensure(T.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=o.qrAuth??new s({source:r.qrSource??"deepseek-harness"}),k=new Map,G=T=>Wg(l.bots,T,"state.json"),K=async T=>{let V=k.get(T);return V||(V=await new e(G(T)).load(),k.set(T,V)),V},x=zr(n,o.commandExecutor),H=new a({baseUrl:ZBe(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...x?{commandExecutor:x}:{}}),q=new A({qrAuth:R,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:T,config:V,appSecret:U})=>{let b=await K(T);await f.ensure(T);let L=qr(H,{botId:T,workspaces:f,state:b});return new t({config:V,appSecret:U,harness:L.harness,state:L.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,logger:{error:(...X)=>c.error?.(`[${T}]`,...X),warn:(...X)=>c.warn?.(`[${T}]`,...X),info:(...X)=>c.info?.(`[${T}]`,...X),debug:(...X)=>c.debug?.(`[${T}]`,...X)}})},deleteState:async({botId:T})=>{let V=k.get(T);if(k.delete(T),V&&typeof V.remove=="function")await V.remove();else try{await zBe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=Vr(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import $Be from"qrcode";var e3="/qq",_r=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),A3=Object.freeze(Object.values(_r)),eQe=new Set(["appSecret","app_secret","secretRef","ownerUserOpenid","userOpenid","verificationUrl"]);function KN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function jI(n,r){return KN(n)&&Object.keys(n).every(o=>r.includes(o))}function UN(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function $1(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function AQe(n,r){return KN(r)?n===_r.status?jI(r,[])?null:"connection.status does not accept fields.":n===_r.beginProvisioning?jI(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[_r.pollProvisioning,_r.cancelProvisioning].includes(n)?jI(r,["attemptId"])&&UN(r.attemptId)?null:`${n} requires an attemptId.`:n===_r.bindCredentials?jI(r,["appId","appSecret"])&&$1(r.appId,256)&&$1(r.appSecret,1024)?null:"bot.bind-credentials requires AppID and AppSecret.":n===_r.reconnectBot?jI(r,["botId","sendTest"])&&UN(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and accepts only sendTest=true.":n===_r.deleteBot?jI(r,["botId","confirm"])&&UN(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===_r.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown QQ endpoint.":"Payload must be an object."}function JI(n){if(Array.isArray(n))return n.map(JI);if(!KN(n))return n;let r={};for(let[o,i]of Object.entries(n))eQe.has(o)||(r[o]=JI(i));return r}async function tQe(n){return $Be.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function HN(n,r){return!n||typeof n.verificationUrl!="string"?JI(n):JI({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function IC(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await HN(o.provisioning,r)),JI(o)}function t3(n,{encodeQr:r=tQe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete QQ 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(()=>r(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(!A3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown QQ endpoint."}};let t=AQe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===_r.status)s=await IC(await n.status(),i);else if(e===_r.beginProvisioning)s=await HN(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 HN(g,i)}else if(e===_r.cancelProvisioning)s=JI(await n.cancelProvisioning(a.attemptId));else if(e===_r.bindCredentials)s=await IC(await n.bindCredentials(a),i);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."}};let c;if(a.sendTest===!0)if(!(g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("QQ\u673A\u5668\u4EBA"));else{let p=null;try{await n.sendConnectionTest(a.botId)}catch(B){p=B}c=Ot(p)}s=await IC({...g,...c?{testMessage:c}:{}},i)}else if(e===_r.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await IC(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await IC(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=Xr(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"qq-operation-failed",message:"QQ \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function CQ(n,r,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(e3,t3(r,o),{authority:Wr(i)})}async function r3(n,r={}){if(r?.controller)return CQ(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await LN(n,r,r.internals),i=CQ(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close QQ bot connections"),i}import{unlink as kQe}from"node:fs/promises";import{resolve as l3}from"node:path";import{createHash as rQe}from"node:crypto";import{mkdir as aQe,readFile as iQe,rename as oQe,unlink as nQe,writeFile as sQe}from"node:fs/promises";import{dirname as gQe}from"node:path";var YN=Object.freeze({version:1,bots:Object.freeze([])}),a3=/^slack_[a-f0-9]{24}$/,cQe=/^DSH_SLACK_BOT_TOKEN_[A-F0-9]{24}$/,IQe=/^DSH_SLACK_APP_TOKEN_[A-F0-9]{24}$/;function pi(n){return typeof n=="string"&&n.trim()?n.trim():null}function xN(n){let r=pi(n);if(!r)throw new TypeError("platformId is required");let o=rQe("sha256").update(r).digest("hex").slice(0,24),i=o.toUpperCase();return{botId:`slack_${o}`,botTokenRef:`DSH_SLACK_BOT_TOKEN_${i}`,appTokenRef:`DSH_SLACK_APP_TOKEN_${i}`}}function jN(n){let r=pi(n)??"",[o,i]=r.split(":");return o&&i?`${o.slice(0,5)}\u2022\u2022\u2022 \xB7 ${i.slice(0,5)}\u2022\u2022\u2022`:r?`${r.slice(0,6)}\u2022\u2022\u2022\u2022`:"Slack\u673A\u5668\u4EBA"}var hQ=class{#e;#A=YN;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=this.#g(JSON.parse(await iQe(this.#e,"utf8")));if(!r)throw new Error("dsh-im Slack config contains invalid bot data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=YN}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByPlatformId(r){let o=this.#A.bots.find(i=>i.platformId===r);return o?structuredClone(o):null}async save(r){let o=this.#r(r);if(!o)throw new Error("Refusing to persist incomplete Slack bot data");return this.#n(i=>{if(i.find(A=>A.botId!==o.botId&&(A.platformId===o.platformId||A.botTokenRef===o.botTokenRef||A.appTokenRef===o.appTokenRef)))throw new Error("Duplicate Slack bot identity");let a=i.findIndex(A=>A.botId===o.botId);return a===-1?i.push(o):i[a]=o,structuredClone(o)})}async remove(r){if(!a3.test(r))throw new TypeError("Invalid Slack bot id");return this.#n(o=>{let i=o.findIndex(e=>e.botId===r);return i===-1?null:structuredClone(o.splice(i,1)[0])})}async clear(){let r=this.#t.then(async()=>{try{await nQe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=YN});this.#t=r.then(()=>{},()=>{}),await r}#r(r){if(!r||typeof r!="object")return null;let o=pi(r.botId),i=pi(r.platformId),e=pi(r.botTokenRef),a=pi(r.appTokenRef),A=pi(r.name);if(!o||!i||!e||!a||!A||!a3.test(o)||!cQe.test(e)||!IQe.test(a))return null;let t=xN(i);return t.botId!==o||t.botTokenRef!==e||t.appTokenRef!==a?null:Object.freeze({botId:o,platformId:i,botTokenRef:e,appTokenRef:a,name:A,username:pi(r.username),teamId:pi(r.teamId),teamName:pi(r.teamName),createdAt:pi(r.createdAt)??new Date().toISOString(),connectedAt:pi(r.connectedAt)})}#g(r){if(!r||r.version!==1||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.botTokenRef)||a.has(A.appTokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.botTokenRef),a.add(A.appTokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#n(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await aQe(gQe(this.#e),{recursive:!0,mode:448});let A=`${this.#e}.tmp`;await sQe(A,`${JSON.stringify(a,null,2)} +`,{encoding:"utf8",mode:384}),await oQe(A,this.#e),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}};var lQe="https://slack.com/api/",uQ="files.slack.com",EQe="slack.com",i3="/files-pri/",pQe=Object.freeze([uQ]);function mn(n){return typeof n=="string"&&n.trim()?n.trim():null}function CQe(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function hQe(n){return Number.isInteger(n)&&n>=300&&n<400}async function dQe(n){try{await n?.body?.cancel?.()}catch{}}function uQe(n){let r=new URL(n);if(r.protocol!=="https:")throw new Error("Image download URL must use HTTPS");if(r.username||r.password||r.port&&r.port!=="443")throw new Error("Image download URL is not hosted by the messaging platform");if(r.hostname===EQe&&r.pathname.startsWith(i3)&&(r.hostname=uQ),r.hostname!==uQ||!r.pathname.startsWith(i3))throw new Error("Image download URL is not hosted by the messaging platform");return r.hash="",r}function BQe(n,r){let o=n?.headers?.get?.("location");if(!o)return null;try{return new URL(o,r)}catch{return null}}function QQe(n){let r=n?.headers?.get?.("x-oauth-scopes");return r==null?null:new Set(r.split(",").map(o=>o.trim()).filter(Boolean))}function fQe(n){return n?.protocol==="https:"&&!n.username&&!n.password&&(!n.port||n.port==="443")&&n.hostname.endsWith(".slack.com")&&n.hostname!==uQ&&n.pathname==="/"&&n.searchParams.has("redir")}function yQe(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),r?.addEventListener("abort",()=>{clearTimeout(e),i(r.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function Zg(n,r){let o=mn(n);if(!o||!/^[A-Z][A-Z0-9]{4,30}$/i.test(o))throw new TypeError(`Invalid Slack ${r}`);return o}function dQ(n,r){let o=mn(n);if(!o)throw new TypeError(`Slack ${r} is required`);return o}function lC(n,{trim:r=!0}={}){let o=typeof n=="string"?n:"",i=r?o.trim():o;if(!i)throw new TypeError("Slack message text is required");return i.replace(/<@([A-Z0-9]+)>/gi,"@$1").replace(/]*)?>/gi,"@$1")}function mQe(n,r,o){let i=mn(r?.error)??"unknown_error",e=new Error(`Slack ${n} failed: ${i.replaceAll("_"," ")}`);return["invalid_auth","not_authed","token_revoked","account_inactive"].includes(i)?e.code=o==="app"?"slack-invalid-app-token":"slack-invalid-bot-token":i==="missing_scope"?e.code="slack-missing-scope":i==="method_not_supported_for_channel_type"||i==="channel_type_not_supported"||i==="deprecated_endpoint"?e.code="slack-stream-unavailable":e.code=`slack-${i}`,e}function o3(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())}function n3(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())}var EC=class{#e;#A;#t;#r;#g=null;constructor({botToken:r,appToken:o,fetchImpl:i=fetch,baseUrl:e=lQe}){if(r!==void 0&&!o3(r))throw new TypeError("Slack Bot Token is invalid");if(o!==void 0&&!n3(o))throw new TypeError("Slack App Token is invalid");if(!r&&!o)throw new TypeError("SlackApi requires a token");if(typeof i!="function")throw new TypeError("SlackApi requires fetch");this.#e=r?.trim(),this.#A=o?.trim(),this.#t=i,this.#r=new URL(e)}authTest(r={}){return this.#n("auth.test",{...r,tokenKind:"bot"})}openConnection(r={}){return this.#n("apps.connections.open",{...r,tokenKind:"app",body:void 0})}postMessage({channelId:r,text:o,threadTs:i,signal:e}){return this.#n("chat.postMessage",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),text:lC(o),...i?{thread_ts:mn(i)}:{},mrkdwn:!0,link_names:!1,unfurl_links:!1,unfurl_media:!1}})}updateMessage({channelId:r,ts:o,text:i,signal:e}){return this.#n("chat.update",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),ts:dQ(o,"message timestamp"),text:lC(i),parse:"none",link_names:!1}})}startStream({channelId:r,threadTs:o,recipientTeamId:i,recipientUserId:e,markdownText:a,signal:A}){return this.#n("chat.startStream",{tokenKind:"bot",signal:A,body:{channel:Zg(r,"channel id"),thread_ts:dQ(o,"thread timestamp"),...i?{recipient_team_id:Zg(i,"team id")}:{},...e?{recipient_user_id:Zg(e,"user id")}:{},...mn(a)?{markdown_text:lC(a)}:{}}})}appendStream({channelId:r,ts:o,markdownText:i,signal:e}){return this.#n("chat.appendStream",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),ts:dQ(o,"stream timestamp"),markdown_text:lC(i,{trim:!1})}})}stopStream({channelId:r,ts:o,markdownText:i,signal:e}){return this.#n("chat.stopStream",{tokenKind:"bot",signal:e,body:{channel:Zg(r,"channel id"),ts:dQ(o,"stream timestamp"),...mn(i)?{markdown_text:lC(i,{trim:!1})}:{}}})}async downloadFile({url:r,signal:o,maxBytes:i}){if(!this.#e)throw new TypeError("Slack bot token is required for file download");let e=uQe(r);return za(e,{fetchImpl:async(A,t)=>{let s=await this.#t(A,t);if(!hQe(s?.status))return s;let g=BQe(s,A);if(this.#g&&!this.#g.has("files:read")||fQe(g))throw await dQe(s),new XA("slack-file-access-required","Slack redirected a private file request to the workspace because file access was not granted","Slack \u672A\u6388\u6743\u673A\u5668\u4EBA\u8BFB\u53D6\u8BE5\u6587\u4EF6\u3002\u8BF7\u4E3A\u5E94\u7528\u6DFB\u52A0 files:read \u540E\u91CD\u65B0\u5B89\u88C5\uFF0C\u518D\u91CD\u65B0\u53D1\u9001\u56FE\u7247\u3002");return s},headers:{authorization:`Bearer ${this.#e}`},signal:o,maxBytes:i,allowedHosts:pQe})}async#n(r,{tokenKind:o,body:i,signal:e,timeoutMs:a=15e3,retry:A=!0}){let t=o==="app"?this.#A:this.#e;if(!t)throw new TypeError(`Slack ${o} token is required for ${r}`);let s;try{s=await this.#t(new URL(r,this.#r),{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":i===void 0?"application/x-www-form-urlencoded;charset=utf-8":"application/json;charset=utf-8","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.2.2)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:CQe(e,a),redirect:"error"})}catch(c){throw c?.name==="AbortError"||c?.name==="TimeoutError"?c:new Error(`Slack ${r} transport failed`)}if(o==="bot"){let c=QQe(s);c&&(this.#g=c)}let g;try{g=await s.json()}catch{throw new Error(`Slack ${r} returned invalid JSON`)}if(s.status===429&&A){let c=Number(s.headers.get("retry-after"))||1;return await yQe(Math.min(1e4,Math.max(100,c*1e3)),e),this.#n(r,{tokenKind:o,body:i,signal:e,timeoutMs:a,retry:!1})}if(!s.ok||g?.ok!==!0)throw mQe(r,g,o);return g}};async function s3({botToken:n,appToken:r},o={}){if(!o3(n)){let t=new TypeError("Slack Bot Token \u5FC5\u987B\u4EE5 xoxb- \u5F00\u5934\u3002");throw t.code="slack-invalid-bot-token",t}if(!n3(r)){let t=new TypeError("Slack App Token \u5FC5\u987B\u4EE5 xapp- \u5F00\u5934\u3002");throw t.code="slack-invalid-app-token",t}let i=new EC({botToken:n,appToken:r,...o}),[e,a]=await Promise.all([i.authTest(),i.openConnection()]);if(!e?.team_id||!e?.user_id||!e?.bot_id)throw new Error("Slack Bot Token \u6CA1\u6709\u8FD4\u56DE\u5B8C\u6574\u7684\u673A\u5668\u4EBA\u8EAB\u4EFD\u3002");let A;try{A=new URL(a?.url)}catch{A=null}if(!A||A.protocol!=="wss:"){let t=new Error("Slack App Token \u65E0\u6CD5\u521B\u5EFA Socket Mode \u8FDE\u63A5\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u542F\u7528 Socket Mode \u548C connections:write\u3002");throw t.code="slack-socket-mode",t}return{platformId:`${e.team_id}:${e.user_id}`,name:mn(e.user)??"DeepSeek Harness",username:mn(e.user),teamId:String(e.team_id),teamName:mn(e.team)}}var JN=Object.freeze({key:"slack",label:"Slack",connectionLabel:" Socket Mode \u957F\u8FDE\u63A5"}),BQ=class extends lo{constructor(r){super({descriptor:JN,...r})}};function Sn(n){return typeof n=="string"&&n.trim()?n.trim():null}function QQ(n,r){return Object.freeze({code:n,message:r})}var pC=class{#e;#A;#t;#r;#g;#n;#E=new Map;#s=new Map;#I=new Map;#a=0;#i=!1;constructor({credentials:r,configStore:o,inspectCredentials:i=s3,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!r||typeof r.resolve!="function"||typeof r.set!="function"||typeof r.unset!="function")throw new TypeError("Slack requires the DSH credential provider");if(!o||typeof o.list!="function"||typeof o.save!="function"||typeof o.remove!="function")throw new TypeError("Slack requires a config store");if(typeof i!="function"||typeof e!="function")throw new TypeError("Slack controller dependencies are incomplete");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A}async initialize(){if(this.#i)return this.status();for(let r of this.#A.list())await this.#h(r.botId,async()=>{if(this.#i||this.#E.get(r.botId)?.status?.ready)return;let o=await this.#l(r);if(!o){this.#s.set(r.botId,QQ("missing-token","Slack\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002"));return}try{await this.#o(r,o),this.#s.delete(r.botId)}catch(i){this.#s.set(r.botId,QQ("connection-failed","Slack Socket Mode \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#n.warn?.(`[dsh-im:slack] bot ${r.botId} failed to initialize:`,i)}finally{this.#C()}});return this.status()}async bindCredentials({botToken:r,appToken:o}={}){if(this.#i)throw new Error("Slack controller is closed");let i=Sn(r),e=Sn(o);if(!i||!e)throw new TypeError("Slack Bot Token and App Token are required");let a=await this.#t({botToken:i,appToken:e}),A=Sn(a?.platformId),t=Sn(a?.name);if(!A||!t)throw new Error("Slack returned an invalid bot identity");let s=xN(A);return await this.#h(s.botId,async()=>{if(this.#i)throw new Error("Slack controller is closed");let g=this.#A.getByPlatformId(A),c=await this.#e.resolve(s.botTokenRef).catch(()=>{}),l=await this.#e.resolve(s.appTokenRef).catch(()=>{}),p={...s,platformId:A,name:t,username:Sn(a.username),teamId:Sn(a.teamId),teamName:Sn(a.teamName),createdAt:g?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};try{await this.#e.set(s.botTokenRef,i),await this.#e.set(s.appTokenRef,e),await this.#A.save(p)}catch(B){throw await Promise.all([this.#p(s.botTokenRef,c),this.#p(s.appTokenRef,l)]),B}try{await this.#o(p,{botToken:i,appToken:e}),this.#s.delete(s.botId)}catch(B){this.#s.set(s.botId,QQ("connection-failed","Slack\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0CSocket Mode \u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:slack] bot ${s.botId} credential connection failed:`,B)}this.#C()}),this.status()}async reconnectBot(r){let o=this.#A.get(r);if(!o)throw new Error("Unknown Slack bot");return await this.#h(r,async()=>{let i=await this.#l(o);if(!i)throw new Error("Slack bot credentials are missing");try{await this.#o(o,i),this.#s.delete(r)}catch(e){throw this.#s.set(r,QQ("connection-failed","Slack Socket Mode \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u68C0\u67E5\u4E24\u4E2A Token\u3002")),e}finally{this.#C()}}),this.status()}async sendConnectionTest(r){let o=this.#A.get(r);if(!o)throw new Error("Unknown Slack bot");return this.#h(r,async()=>{let i=this.#E.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(Yr(`${o.name}\uFF08${jN(o.platformId)}\uFF09`,"Slack\u673A\u5668\u4EBA")),{sent:!0}})}async deleteBot(r){let o=this.#A.get(r);if(!o)throw new Error("Unknown Slack bot");return await this.#h(r,async()=>{let i=await this.#e.resolve(o.botTokenRef).catch(()=>{}),e=await this.#e.resolve(o.appTokenRef).catch(()=>{});await this.#c(r);try{await this.#e.unset(o.botTokenRef),await this.#e.unset(o.appTokenRef),await this.#A.remove(r)}catch(a){throw await Promise.all([this.#p(o.botTokenRef,i),this.#p(o.appTokenRef,e)]),i?.value&&e?.value&&await this.#o(o,{botToken:i.value,appToken:e.value}).catch(()=>{}),new Error("Unable to remove the Slack bot safely.",{cause:a})}await this.#g({botId:r,config:o}).catch(a=>{this.#n.warn?.(`[dsh-im:slack] bot ${r} state cleanup failed:`,a)}),this.#s.delete(r),this.#C()}),this.status()}status(){let r=this.#A.list().map(i=>{let e=this.#E.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#s.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,teamName:i.teamName,idMasked:jN(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?`Slack${JN.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?"Slack\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"Slack\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},error:structuredClone(this.#s.get(i.botId)??null)}}),o=r.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#a,state:r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o}}}async close(){this.#i||(this.#i=!0,await Promise.allSettled([...this.#I.values()]),await Promise.allSettled([...this.#E.keys()].map(r=>this.#c(r))))}async#o(r,{botToken:o,appToken:i}){if(this.#i)throw new Error("Slack controller is closed");if(await this.#c(r.botId),this.#i)throw new Error("Slack controller is closed");let e=await this.#r({botId:r.botId,config:r,botToken:o,appToken:i});if(!e||typeof e.start!="function"||typeof e.stop!="function")throw new TypeError("createRuntime returned an invalid Slack runtime");this.#E.set(r.botId,e);try{await e.start()}catch(a){throw await e.stop().catch(()=>{}),this.#E.delete(r.botId),a}}async#c(r){let o=this.#E.get(r);this.#E.delete(r),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:slack] bot ${r} failed to stop cleanly:`,i)})}async#l(r){let[o,i]=await Promise.all([this.#e.resolve(r.botTokenRef).catch(()=>{}),this.#e.resolve(r.appTokenRef).catch(()=>{})]),e=Sn(o?.value),a=Sn(i?.value);return e&&a?{botToken:e,appToken:a}:null}async#p(r,o){o?.value?await this.#e.set(r,o.value).catch(()=>{}):await this.#e.unset(r).catch(()=>{})}#h(r,o){let a=(this.#I.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#I.get(r)===a&&this.#I.delete(r)});return this.#I.set(r,a),a}#C(){this.#a+=1}};var fQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"slack",logPrefix:"dsh-slack"})}};var g3=Object.freeze([1e3,3e3,5e3,1e4,3e4]),VN=38e3,c3=11e3,SQe=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function qN(n,r,o){if(typeof n.addEventListener=="function")n.addEventListener(r,o);else if(typeof n.on=="function")n.on(r,o);else throw new TypeError("Slack WebSocket does not support events")}function DQe(n){let r=n?.data??n;return typeof r=="string"?r:Buffer.isBuffer(r)?r.toString("utf8"):r instanceof ArrayBuffer?Buffer.from(r).toString("utf8"):ArrayBuffer.isView(r)?Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):null}function wQe(n){let r=new URL(n);if(r.protocol!=="wss:")throw new Error("Slack returned an insecure Socket Mode URL");return r.href}function OQe(n){return typeof n=="string"?n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"):""}function MQe(n,r){return OQe(n).replace(new RegExp(`<@${r}>`,"gi"),"").trim()}function bQe(n,r){let o=typeof n?.mimetype=="string"?n.mimetype.toLowerCase():"",i=typeof n?.url_private_download=="string"&&n.url_private_download?n.url_private_download:n?.url_private;return!SQe.has(o)||typeof i!="string"||!i?null:{name:typeof n.name=="string"?n.name:void 0,mediaType:o,size:Number.isSafeInteger(n.size)&&n.size>=0?n.size:void 0,load:e=>r(i,e)}}function _Qe(n,r,{loadFile:o=async()=>{throw new Error("Slack file downloader is unavailable")}}={}){let i=n?.event;if(!i||!n?.event_id||!i.channel||!i.user||!i.ts)return null;let e=i.type==="message"&&i.channel_type==="im",a=i.type==="app_mention";if(!e&&!a||i.subtype&&i.subtype!=="file_share"||i.bot_id||i.app_id)return null;let A=String(i.thread_ts??i.ts);return{messageId:String(n.event_id),senderId:String(i.user),senderIsBot:String(i.user)===String(r),kind:e?"direct":"group",conversationId:e?String(i.channel):`${i.channel}:${A}`,content:MQe(i.text??"",r),images:Array.isArray(i.files)?i.files.map(t=>bQe(t,o)).filter(Boolean):[],addressed:e||a,replyTarget:{channelId:String(i.channel),threadTs:A,recipientUserId:String(i.user),recipientTeamId:String(i.user_team??n.team_id??"")},connectionTestTarget:{channelId:String(i.channel)}}}function NQe(n){return typeof n=="string"&&/^正在使用.+…$/.test(n.trim())}async function I3(n,r,o,i,e){if(i)for(let a=0;a{let f=ii(Q,VN)[0]??"";if(!f||!f.startsWith(A))return;let y=f.slice(A.length);y&&(await I3(n,r,a,y,o),A=f)},B=()=>{l||c||s!==null||g||!t||(s=setTimeout(()=>{s=null;let Q=t;t="",g=p(Q).catch(f=>{c=!0,i.warn?.("[dsh-im:slack] streaming append failed:",f)}).finally(()=>{g=null,B()})},350),s?.unref?.())};return{update(Q){l||c||typeof Q!="string"||!Q.trim()||NQe(Q)||(t=Q,B())},async finish(Q){if(l)throw new Error("Slack message stream is already closed");l=!0,s!==null&&clearTimeout(s),s=null,t="",await g?.catch(()=>{});let f=ii(Q,VN),y=f[0]??"\u5904\u7406\u5B8C\u6210\u3002";!c&&y.startsWith(A)?(await I3(n,r,a,y.slice(A.length),o),await n.stopStream({channelId:r.channelId,ts:a,signal:o})):(await n.stopStream({channelId:r.channelId,ts:a,signal:o}).catch(()=>{}),await n.updateMessage({channelId:r.channelId,ts:a,text:y,signal:o}));for(let m of f.slice(1))await n.postMessage({channelId:r.channelId,threadTs:r.threadTs,text:m,signal:o})},cancel(){l=!0,t="",s!==null&&clearTimeout(s),s=null,n.stopStream({channelId:r.channelId,ts:a,signal:o}).catch(()=>{})}}}var zN=class{#e;#A;#t;constructor({api:r,signal:o,logger:i}){this.#e=r,this.#A=o,this.#t=i}async sendText(r,o){let i=ii(o,VN),e=null;for(let a of i)e=await this.#e.postMessage({channelId:r.channelId,threadTs:r.threadTs,text:a,signal:this.#A});return e}openStream(r){return TQe({api:this.#e,target:r,signal:this.#A,logger:this.#t})}};function RQe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var CC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i=RQe();#o=null;#c=null;#l=null;#p=null;#h=null;#C=null;#d=0;#Q=0;#u=!0;#B=null;constructor({config:r,botToken:o,appToken:i,harness:e,state:a,logger:A=console,replyTimeoutMs:t=6e5,connectTimeoutMs:s=2e4,createApi:g=l=>new EC(l),createWebSocket:c=l=>new WebSocket(l)}){if(!r||!o||!i||!e||!a)throw new TypeError("SlackRuntime requires config, both tokens, Harness, and state");if(typeof c!="function")throw new TypeError("SlackRuntime requires WebSocket");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#a=c}get status(){return structuredClone(this.#i)}async sendConnectionTest(r){if(!this.#i.ready||!this.#c){let o=new Error("Slack bot is not connected");throw o.code="test-target-unavailable",o}return this.#c.sendConnectionTest(r)}async start(){return this.#i.ready&&this.#p?this.status:this.#B?this.#B:(this.#B=this.#y().finally(()=>{this.#B=null}),this.#B)}async#y(){await this.stop(),this.#u=!1,this.#d=0,this.#i.startedAt=new Date().toISOString(),this.#i.connectionState="connecting",this.#i.lastError=null,await this.#r.ensureRunning(),this.#i.harnessReachable=!0;let r=new AbortController;this.#l=r;let o=this.#I({botToken:this.#A,appToken:this.#t});this.#o=o;try{let i=await o.authTest({signal:r.signal});if(`${i?.team_id}:${i?.user_id}`!==this.#e.platformId)throw new Error("Slack Bot Token identity does not match the saved bot");let e=new zN({api:o,signal:r.signal,logger:this.#n});this.#c=new BQ({bot:e,harness:this.#r,state:this.#g,status:this.#i,logger:this.#n,replyTimeoutMs:this.#E,signal:r.signal});let a;try{await Promise.race([this.#f(),new Promise((A,t)=>{a=setTimeout(()=>t(new Error("Slack Socket Mode did not become ready in time")),this.#s),a?.unref?.()})])}finally{clearTimeout(a)}return this.status}catch(i){throw this.#i.ready=!1,this.#i.connectionState="failed",this.#i.lastError=i?.message??String(i),await this.stop(),i}}async#f(){if(this.#u)throw new Error("Slack runtime is stopped");let r=await this.#o.openConnection({signal:this.#l?.signal});return this.#D(r?.url)}#D(r){if(this.#u)return Promise.reject(new Error("Slack runtime is stopped"));let o=++this.#Q,i=this.#a(wQe(r));this.#p=i;let e=!1;return new Promise((a,A)=>{let t=s=>{if(e||o!==this.#Q)return;e=!0,this.#h=s?.connection_info?.app_id??null,this.#d=0;let g=Date.now();this.#i.ready=!0,this.#i.connectionState="connected",this.#i.lastCheckedAt=g,this.#i.lastConnectedAt=g,this.#i.lastError=null,a()};qN(i,"message",s=>{if(o!==this.#Q||this.#u)return;let g=DQe(s);if(!g)return;let c;try{c=JSON.parse(g)}catch{this.#n.warn?.("[dsh-im:slack] ignored malformed Socket Mode JSON");return}if(c.type==="hello"){t(c);return}if(c.envelope_id&&i.readyState===1&&(i.send(JSON.stringify({envelope_id:c.envelope_id})),this.#i.lastCheckedAt=Date.now()),c.type==="disconnect"){i.close(4e3,"Slack requested reconnect");return}if(c.type!=="events_api"||c.payload?.type!=="event_callback"||this.#h&&c.payload.api_app_id&&c.payload.api_app_id!==this.#h)return;let l=_Qe(c.payload,this.#e.platformId.split(":")[1],{loadFile:(B,Q)=>this.#o.downloadFile({url:B,...Q})}),p=this.#c;l&&p&&p.accept(l).catch(B=>{o!==this.#Q||this.#u||this.#n.error?.(`[dsh-im:slack] bot ${this.#e.botId} message handling failed:`,B)})}),qN(i,"close",(s={})=>{if(o!==this.#Q)return;if(this.#p===i&&(this.#p=null),this.#u){e||A(new DOMException("Stopped","AbortError"));return}let g=Number(s.code)||0,c=new Error(`Slack Socket Mode closed (${g||"unknown"})`);this.#i.ready=!1,this.#i.connectionState="connecting",this.#i.lastError=c.message,e||(e=!0,A(c)),this.#m()}),qN(i,"error",()=>{o!==this.#Q||this.#u||(this.#i.lastError="Slack Socket Mode WebSocket error")})})}#m(){if(this.#u||this.#C!==null)return;let r=g3[Math.min(this.#d,g3.length-1)];this.#d+=1,this.#C=setTimeout(()=>{this.#C=null,this.#f().catch(o=>{this.#u||(this.#n.warn?.("[dsh-im:slack] Socket Mode reconnect failed:",o),this.#m())})},r),this.#C?.unref?.()}async stop(){this.#u=!0,this.#Q+=1,this.#l?.abort(),this.#l=null,this.#C!==null&&clearTimeout(this.#C),this.#C=null;let r=this.#p,o=this.#c;this.#p=null,this.#c=null,this.#o=null,this.#h=null;try{r&&r.readyState<2&&r.close(1e3,"Plugin stopped")}catch(i){this.#n.warn?.(`[dsh-im:slack] bot ${this.#e.botId} failed to close Socket Mode:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#i.ready=!1,this.#i.connectionState="idle",this.status}};var yQ=class extends Eo{};async function WN(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-im slack requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im slack requires ctx.webServer");let i=o.ConfigStore??hQ,e=o.StateStore??yQ,a=o.HarnessClient??fQ,A=o.Controller??pC,t=o.Runtime??CC,s=o.createConnectionSupervisor??eI,g=typeof n.logger=="function"?n.logger("dsh-im:slack"):n.logger??console,c=yD(r,"slack"),l=await new i(c.config).load(),p=l3(r.workspace??process.cwd()),B=o.WorkspaceStore??Cr,Q=o.workspaces??await new B(c.workspaces,{defaultWorkspace:p}).load(),f=l.list();await Q.reconcile(f.map(j=>j.botId)),await Promise.all(f.map(j=>Q.ensure(j.botId)));let y=typeof l.remove=="function"?Jr(l,{workspaces:Q}):l,m=new Map,R=j=>l3(c.bots,j,"state.json"),k=async j=>{let F=m.get(j);return F||(F=await new e(R(j)).load(),m.set(j,F)),F},G=zr(n,o.commandExecutor),K=new a({baseUrl:fD(n.webServer,r.harnessBaseUrl),workspace:p,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...G?{commandExecutor:G}:{}}),x=new A({credentials:n.credentials,configStore:y,logger:g,...o.inspectCredentials?{inspectCredentials:o.inspectCredentials}:{},createRuntime:async({botId:j,config:F,botToken:T,appToken:V})=>{let U=await k(j);await Q.ensure(j);let b=qr(K,{botId:j,workspaces:Q,state:U});return new t({config:F,botToken:T,appToken:V,harness:b.harness,state:b.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,logger:{error:(...L)=>g.error?.(`[${j}]`,...L),warn:(...L)=>g.warn?.(`[${j}]`,...L),info:(...L)=>g.info?.(`[${j}]`,...L),debug:(...L)=>g.debug?.(`[${j}]`,...L)}})},deleteState:async({botId:j})=>{let F=m.get(j);if(m.delete(j),F&&typeof F.remove=="function")await F.remove();else try{await kQe(R(j))}catch(T){if(T?.code!=="ENOENT")throw T}}}),H=Vr(x,{workspaces:Q,stateFor:k}),q=s({channel:"slack",controller:H,harness:K,logger:g,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:H,ready:q.ready,async close(){await q.close(),await H.close(),K.stopManagedProcess()}}}var p3="/slack",Ji=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),C3=Object.freeze(Object.values(Ji)),vQe=new Set(["token","botToken","appToken","botTokenRef","appTokenRef","tokenRef","platformId","secret","secretRef"]);function XN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function mQ(n,r){return XN(n)&&Object.keys(n).every(o=>r.includes(o))}function E3(n){return typeof n=="string"&&/^slack_[a-f0-9]{24}$/.test(n)}function PQe(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function GQe(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function FQe(n,r){return XN(r)?n===Ji.status?mQ(r,[])?null:"connection.status does not accept fields.":n===Ji.bindCredentials?mQ(r,["botToken","appToken"])&&PQe(r.botToken)&&GQe(r.appToken)?null:"bot.bind-credentials requires xoxb Bot Token and xapp App Token.":n===Ji.reconnectBot?mQ(r,["botId","sendTest"])&&E3(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===Ji.deleteBot?mQ(r,["botId","confirm"])&&E3(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Ji.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Slack endpoint.":"Payload must be an object."}function ZN(n){if(Array.isArray(n))return n.map(ZN);if(!XN(n))return n;let r={};for(let[o,i]of Object.entries(n))vQe.has(o)||(r[o]=ZN(i));return r}function LQe(n){let r=Xr(n);return r||(n?.code==="slack-invalid-bot-token"?{code:"invalid-bot-token",message:"Slack Bot Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xoxb- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-invalid-app-token"?{code:"invalid-app-token",message:"Slack App Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xapp- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-missing-scope"?{code:"missing-scope",message:"Slack \u5E94\u7528\u6743\u9650\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u65B0\u5BFC\u5165 Manifest \u5E76\u5B89\u88C5\u5230\u5DE5\u4F5C\u533A\u3002"}:n?.code==="slack-socket-mode"?{code:"socket-mode-unavailable",message:n.message}:{code:"slack-operation-failed",message:"Slack \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"})}function h3(n){for(let r of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[r]!="function")throw new TypeError(`A complete Slack controller is required (${r})`);return async(r,o,i)=>{if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!C3.includes(r))return{ok:!1,error:{code:"bad-request",message:"Unknown Slack endpoint."}};let e=FQe(r,o);if(e)return{ok:!1,error:{code:"bad-request",message:e}};try{let a;if(r===Ji.status)a=await n.status();else if(r===Ji.bindCredentials)a=await n.bindCredentials(o);else if(r===Ji.reconnectBot){if(a=await n.reconnectBot(o.botId),i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(o.sendTest===!0){let A=null;try{if(a?.bots?.find(t=>t?.botId===o.botId)?.connected!==!0){let t=new Error("Bot is not connected");throw t.code="test-target-unavailable",t}if(typeof n.sendConnectionTest!="function"){let t=new Error("Connection test is unavailable");throw t.code="test-target-unavailable",t}await n.sendConnectionTest(o.botId)}catch(t){A=t}a={...a,testMessage:Ot(A)}}}else if(r===Ji.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");a=await n.updateWorkspace(o.botId,o.workspace)}else a=await n.deleteBot(o.botId);return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:ZN(a)}}catch(a){return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:LQe(a)}}}}function SQ(n,r,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(p3,h3(r),{authority:Wr(o)})}async function d3(n,r={}){if(r?.controller)return SQ(n,r.controller,r.rpcAuthority);let o=await WN(n,r,r.internals??{}),i=SQ(n,o.controller,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Slack bot connections"),i}var u3=Object.freeze({botPrefix:"telegram",tokenRefPrefix:"DSH_TELEGRAM_BOT_TOKEN"});function B3(n){return PE(n,u3)}function Q3(n){return kd(n,"Telegram\u673A\u5668\u4EBA")}var DQ=class extends Zc{constructor(r){super(r,{channel:"Telegram",...u3})}};var wQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"telegram",logPrefix:"dsh-telegram"})}};var UQe="https://api.telegram.org/",HQe=Object.freeze(["api.telegram.org"]);function hC(n){return typeof n=="string"&&n.trim()?n.trim():null}function KQe(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function YQe(n){return typeof n=="string"&&/^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(n.trim())}var dC=class{#e;#A;#t;constructor({token:r,fetchImpl:o=fetch,baseUrl:i=UQe}){if(!YQe(r))throw new TypeError("Telegram Bot Token is invalid");if(typeof o!="function")throw new TypeError("TelegramApi requires fetch");this.#e=r.trim(),this.#A=o,this.#t=new URL(i)}async getMe(r={}){return this.#r("getMe",{},r)}async getWebhookInfo(r={}){return this.#r("getWebhookInfo",{},r)}async getUpdates({offset:r,timeout:o=25,signal:i}={}){let e={timeout:o,limit:100,allowed_updates:["message"],...Number.isSafeInteger(r)?{offset:r}:{}};return this.#r("getUpdates",e,{signal:i,timeoutMs:Math.max(1e4,(o+10)*1e3)})}async getFile({fileId:r,signal:o}={}){let i=hC(r);if(!i||!/^[A-Za-z0-9_-]{1,512}$/.test(i))throw new TypeError("Telegram file id is invalid");return this.#r("getFile",{file_id:i},{signal:o})}async downloadFile({fileId:r,signal:o,maxBytes:i}={}){let e=await this.getFile({fileId:r,signal:o}),a=hC(e?.file_path);if(!a||a.startsWith("/")||a.includes("\\")||a.includes("?")||a.includes("#"))throw new Error("Telegram returned an invalid file path");let A;try{A=a.split("/").map(s=>decodeURIComponent(s))}catch{throw new Error("Telegram returned an invalid file path")}if(A.some(s=>!s||s==="."||s===".."))throw new Error("Telegram returned an invalid file path");let t=new URL(this.#t);return t.pathname=`/file/bot${this.#e}/${a}`,za(t,{fetchImpl:this.#A,signal:o,maxBytes:i,allowedHosts:HQe})}async sendMessage({chatId:r,text:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#r("sendMessage",{chat_id:r,text:o,link_preview_options:{is_disabled:!0},...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async editMessageText({chatId:r,messageId:o,text:i,signal:e}){return this.#r("editMessageText",{chat_id:r,message_id:o,text:i,link_preview_options:{is_disabled:!0}},{signal:e})}async sendChatAction({chatId:r,messageThreadId:o,signal:i}){return this.#r("sendChatAction",{chat_id:r,action:"typing",...o?{message_thread_id:o}:{}},{signal:i})}async#r(r,o,{signal:i,timeoutMs:e=15e3}={}){let a=new URL(this.#t);a.pathname=`${a.pathname.replace(/\/$/,"")}/bot${this.#e}/${r}`;let A;try{A=await this.#A(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),signal:KQe(i,e),redirect:"error"})}catch(s){throw s?.name==="AbortError"||s?.name==="TimeoutError"?s:new Error(`Telegram ${r} transport failed`)}let t;try{t=await A.json()}catch{throw new Error(`Telegram ${r} returned invalid JSON`)}if(!A.ok||t?.ok!==!0){let s=hC(t?.description),g=new Error(s??`Telegram ${r} failed`);throw g.code=Number.isInteger(t?.error_code)?`telegram-${t.error_code}`:"telegram-api-error",g}return t.result}};async function f3(n,r={}){let i=await new dC({token:n,...r}).getMe();if(!i?.id||i?.is_bot!==!0)throw new Error("Telegram token does not belong to a bot");return{platformId:String(i.id),name:hC([i.first_name,i.last_name].filter(Boolean).join(" "))??"Telegram\u673A\u5668\u4EBA",username:hC(i.username)}}var $N=Object.freeze({key:"telegram",label:"Telegram",connectionLabel:" Bot API \u957F\u8F6E\u8BE2"}),OQ=class extends lo{constructor(r){super({descriptor:$N,...r})}};var uC=class extends Xc{constructor(r){super({...r,descriptor:$N,inspectToken:r.inspectToken??f3,deriveIdentity:B3,maskPlatformId:Q3})}};function xQe(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jQe(n,r){return r?[[n?.text,n?.entities],[n?.caption,n?.caption_entities]].some(([o,i])=>typeof o=="string"&&Array.isArray(i)&&i.some(e=>e?.type!=="mention"||!Number.isInteger(e.offset)||!Number.isInteger(e.length)?!1:o.slice(e.offset,e.offset+e.length).toLowerCase()===`@${r.toLowerCase()}`)):!1}function JQe(n,r){return!r||typeof n!="string"?n:n.replace(new RegExp(`@${xQe(r)}\\b`,"ig"),"").trim()}var qQe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),VQe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]);function zQe(n){let r=n?.mime_type??n?.mimetype,o=typeof r=="string"?r.toLowerCase():"";if(qQe.has(o))return o;let i=typeof n?.file_name=="string"?n.file_name.toLowerCase():"";for(let[e,a]of VQe)if(i.endsWith(e))return a;return null}function m3(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function y3(n){return m3(n?.file_size)??(Number(n?.width)||0)*(Number(n?.height)||0)}function WQe(n,r){let o,i,e;if(Array.isArray(n?.photo)&&n.photo.length>0)o=n.photo.reduce((a,A)=>y3(A)>y3(a)?A:a),i="image/jpeg",e=`${o.file_unique_id??o.file_id??"telegram-photo"}.jpg`;else if(n?.document){let a=zQe(n.document);if(!a)return null;o=n.document,i=a,e=typeof o.file_name=="string"?o.file_name:void 0}return!o||typeof o.file_id!="string"?null:{name:e,mediaType:i,size:m3(o.file_size),load:a=>r(o.file_id,a)}}function ZQe(n,{botId:r,username:o,loadFile:i=async()=>{throw new Error("Telegram file downloader is unavailable")}}){let e=n?.message,a=e?.chat?.id,A=e?.from?.id,t=e?.message_id;if(!Number.isSafeInteger(n?.update_id)||a===void 0||A===void 0||!Number.isSafeInteger(t)||!["private","group","supergroup"].includes(e.chat?.type))return null;let s=e.chat.type==="private",g=s||String(e.reply_to_message?.from?.id??"")===String(r)||jQe(e,o),c=Number.isSafeInteger(e.message_thread_id)?e.message_thread_id:void 0,l=WQe(e,i);return{messageId:String(n.update_id),senderId:String(A),senderIsBot:e.from?.is_bot===!0,kind:s?"direct":"group",conversationId:c===void 0?String(a):`${a}:${c}`,content:JQe(e.text??e.caption??"",o),images:l?[l]:[],addressed:g,replyTarget:{chatId:a,replyToMessageId:t,messageThreadId:c},connectionTestTarget:{chatId:a,messageThreadId:c}}}var e0=class{#e;#A;constructor({api:r,signal:o}){this.#e=r,this.#A=o}async sendText(r,o){let i=ii(o,4e3),e=null;for(let[a,A]of i.entries())e=await this.#e.sendMessage({chatId:r.chatId,text:A,replyToMessageId:a===0?r.replyToMessageId:void 0,messageThreadId:r.messageThreadId,signal:this.#A});return e}sendTyping(r){return this.#e.sendChatAction({chatId:r.chatId,messageThreadId:r.messageThreadId,signal:this.#A})}async openStream(r){return Ld({limit:4e3,create:async i=>(await this.#e.sendMessage({chatId:r.chatId,text:i,replyToMessageId:r.replyToMessageId,messageThreadId:r.messageThreadId,signal:this.#A})).message_id,edit:(i,e)=>this.#e.editMessageText({chatId:r.chatId,messageId:i,text:e,signal:this.#A}),sendRemainder:i=>this.#e.sendMessage({chatId:r.chatId,text:i,messageThreadId:r.messageThreadId,signal:this.#A})}).start()}};function XQe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var BC=class{#e;#A;#t;#r;#g;#n;#E;#s=XQe();#I=null;#a=null;#i=null;#o=null;#c=null;constructor({config:r,token:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,createApi:t=s=>new dC(s)}){if(!r||!o||!i||!e)throw new TypeError("TelegramRuntime requires config, token, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t}get status(){return structuredClone(this.#s)}async sendConnectionTest(r){if(!this.#s.ready||!this.#a){let o=new Error("Telegram bot is not connected");throw o.code="test-target-unavailable",o}return this.#a.sendConnectionTest(r)}async start(){return this.#s.ready&&this.#o?this.status:this.#c?this.#c:(this.#c=this.#l().finally(()=>{this.#c=null}),this.#c)}async#l(){await this.stop(),this.#s.startedAt=new Date().toISOString(),this.#s.connectionState="connecting",this.#s.lastError=null,await this.#t.ensureRunning(),this.#s.harnessReachable=!0;let r=new AbortController;this.#i=r;let o=this.#E({token:this.#A});this.#I=o;try{let i=await o.getMe({signal:r.signal});if(String(i?.id??"")!==this.#e.platformId||i?.is_bot!==!0)throw new Error("Telegram token identity does not match the saved bot");let e=await o.getWebhookInfo({signal:r.signal});if(typeof e?.url=="string"&&e.url){let s=new Error("\u8BE5 Telegram \u673A\u5668\u4EBA\u5DF2\u914D\u7F6E Webhook\uFF0C\u8BF7\u5148\u5728\u539F\u670D\u52A1\u4E2D\u79FB\u9664 Webhook \u540E\u91CD\u8BD5\u3002");throw s.code="webhook-configured",s}let a=new e0({api:o,signal:r.signal});this.#a=new OQ({bot:a,harness:this.#t,state:this.#r,status:this.#s,logger:this.#g,replyTimeoutMs:this.#n,signal:r.signal});let A=this.#r.cursor();if(A===null){let s=await o.getUpdates({offset:-1,timeout:0,signal:r.signal});A=s.length>0?s.at(-1).update_id+1:0,await this.#r.setCursor(A)}let t=Date.now();return this.#s.ready=!0,this.#s.connectionState="connected",this.#s.lastCheckedAt=t,this.#s.lastConnectedAt=t,this.#o=this.#p(A,r.signal),this.#o.catch(s=>{r.signal.aborted||(this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=s?.message??String(s),this.#g.error?.(`[dsh-im:telegram] bot ${this.#e.botId} polling stopped:`,s))}),this.status}catch(i){throw this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=i?.message??String(i),await this.stop(),i}}async#p(r,o){let i=r;for(;!o.aborted;){let e=await this.#I.getUpdates({offset:i,timeout:25,signal:o});this.#s.lastCheckedAt=Date.now();for(let a of e){if(o.aborted)return;let A=ZQe(a,{botId:this.#e.platformId,username:this.#e.username,loadFile:(t,s)=>this.#I.downloadFile({fileId:t,...s})});A&&this.#a.accept(A).catch(t=>{o.aborted||this.#g.error?.(`[dsh-im:telegram] bot ${this.#e.botId} message handling failed:`,t)}),i=a.update_id+1,await this.#r.setCursor(i)}}}async stop(){let r=this.#o,o=this.#a;return this.#i?.abort(),this.#i=null,this.#o=null,this.#I=null,this.#a=null,await Promise.race([r?.catch(()=>{})??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#s.ready=!1,this.#s.connectionState="idle",this.status}};var MQ=class extends Eo{};function A0(n,r={},o={}){return Kd(n,r,o,{channel:"telegram",ConfigStore:DQ,StateStore:MQ,HarnessClient:wQ,Controller:uC,Runtime:BC})}var S3="/telegram",D3=ua,$Qe=Object.freeze(Object.values(D3));function bQ(n,r,o){return xd(n,r,{channel:"Telegram",rpcChannel:S3,authority:o})}async function w3(n,r={}){if(r?.controller)return bQ(n,r.controller,r.rpcAuthority);let o=await A0(n,r,r.internals??{}),i=bQ(n,o.controller,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Telegram bot connections"),i}import{unlink as Pfe}from"node:fs/promises";import{homedir as Gfe}from"node:os";import{join as mC,resolve as tc}from"node:path";import{createHash as efe}from"node:crypto";import{mkdir as Afe,readFile as tfe,rename as rfe,unlink as afe,writeFile as ife}from"node:fs/promises";import{dirname as ofe}from"node:path";var t0=Object.freeze({version:1,bots:Object.freeze([])});function Xg(n){return typeof n=="string"&&n.trim()?n.trim():null}function O3(n){let r=Xg(n);return r&&/^wecom_[a-f0-9]{24}$/.test(r)?r:null}function nfe(n){let r=Xg(n);return r&&/^DSH_WECOM_BOT_SECRET_[A-F0-9]{24}$/.test(r)?r:null}function NQ(n){let r=Xg(n);if(!r)throw new TypeError("Enterprise WeChat bot ID is required");let o=efe("sha256").update(r).digest("hex").slice(0,24);return{botId:`wecom_${o}`,secretRef:`DSH_WECOM_BOT_SECRET_${o.toUpperCase()}`}}function r0(n){let r=Xg(n)??"";return r?r.length<=10?`${r.slice(0,3)}\u2022\u2022\u2022`:`${r.slice(0,6)}\u2022\u2022\u2022\u2022${r.slice(-4)}`:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"}function M3(n){if(!n||typeof n!="object")return null;let r=O3(n.botId),o=Xg(n.remoteBotId),i=nfe(n.secretRef);if(!r||!o||!i)return null;let e=NQ(o);return e.botId!==r||e.secretRef!==i?null:Object.freeze({botId:r,remoteBotId:o,secretRef:i,createdAt:Xg(n.createdAt)??new Date().toISOString(),connectedAt:Xg(n.connectedAt)})}function sfe(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let r=n.bots.map(M3);if(r.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of r){if(o.has(a.botId)||i.has(a.remoteBotId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.remoteBotId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(r)})}var _Q=class{#e;#A=t0;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=sfe(JSON.parse(await tfe(this.#e,"utf8")));if(!r)throw new Error("dsh-im Enterprise WeChat config contains invalid bot data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=t0}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByRemoteBotId(r){let o=this.#A.bots.find(i=>i.remoteBotId===r);return o?structuredClone(o):null}async save(r){let o=M3(r);if(!o)throw new Error("Refusing to persist incomplete Enterprise WeChat bot data");return this.#r(i=>{let e=i.find(t=>t.remoteBotId===o.remoteBotId&&t.botId!==o.botId),a=i.find(t=>t.secretRef===o.secretRef&&t.botId!==o.botId);if(e||a)throw new Error("Duplicate Enterprise WeChat bot identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!O3(r))throw new TypeError("Invalid Enterprise WeChat bot ID");return this.#r(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await afe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=t0});this.#t=r.then(()=>{},()=>{}),await r}async#r(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(r){await Afe(ofe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await ife(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await rfe(o,this.#e)}};var TQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"wecom",logPrefix:"dsh-wecom"})}};var gfe="https://work.weixin.qq.com/ai/qc/generate",cfe="https://work.weixin.qq.com/ai/qc/query_result";function b3(){return process.platform==="win32"?2:process.platform==="linux"?3:1}function qI(n){return typeof n=="string"&&n.trim()?n.trim():null}function Ife(n){let r=qI(n);if(!r)return null;try{let o=new URL(r);return o.protocol==="https:"&&o.hostname==="work.weixin.qq.com"&&(!o.port||o.port==="443")?o.href:null}catch{return null}}function lfe(n,r){return n?AbortSignal.any([n,AbortSignal.timeout(r)]):AbortSignal.timeout(r)}async function _3(n,r,o){let i=await n(r,{method:"GET",redirect:"error",signal:lfe(o,1e4),headers:{accept:"application/json"}});if(!i.ok)throw new Error(`Enterprise WeChat QR service returned HTTP ${i.status}`);return i.json()}var RQ=class{#e;#A;#t;#r;constructor({fetch:r=globalThis.fetch,clock:o=()=>Date.now(),source:i="deepseek-harness",platform:e=b3()}={}){if(typeof r!="function")throw new TypeError("A fetch implementation is required");this.#e=r,this.#A=o,this.#t=i,this.#r=[1,2,3].includes(e)?e:b3()}async start({signal:r}={}){let o=new URL(gfe);o.searchParams.set("source",this.#t),o.searchParams.set("plat",String(this.#r));let i=await _3(this.#e,o,r),e=qI(i?.data?.scode),a=Ife(i?.data?.auth_url);if(!e||!a)throw new Error("Enterprise WeChat QR service returned invalid data");return{scode:e,verificationUrl:a,expiresAt:this.#A()+3e5,pollIntervalMs:3e3}}async poll({scode:r,signal:o}={}){let i=qI(r);if(!i)throw new TypeError("Enterprise WeChat QR poll code is required");let e=new URL(cfe);e.searchParams.set("scode",i);let a=await _3(this.#e,e,o),A=qI(a?.data?.status)?.toLowerCase();if(A==="success"){let t=qI(a?.data?.bot_info?.botid),s=qI(a?.data?.bot_info?.secret);if(!t||!s)throw new Error("Enterprise WeChat QR result omitted bot credentials");return{status:"success",remoteBotId:t,secret:s}}return["expired","timeout"].includes(A)?{status:"expired"}:["fail","failed","error"].includes(A)?{status:"failed"}:{status:"waiting"}}};import{mkdir as Efe,readFile as pfe,rename as Cfe,unlink as hfe,writeFile as dfe}from"node:fs/promises";import{dirname as ufe}from"node:path";var kQ=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function Bfe(n){if(!n||typeof n!="object")return structuredClone(kQ);let r={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(r[o]=i);return{version:1,sessions:r,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var vQ=class{#e;#A=structuredClone(kQ);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{this.#A=Bfe(JSON.parse(await pfe(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(kQ),await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}async remove(){try{await hfe(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(kQ)}async#r(){let r=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await Efe(ufe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await dfe(i,r,{encoding:"utf8",mode:384}),await Cfe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as Qfe}from"node:crypto";var N3=new Set(["pending","connecting"]),QC=new Set(["connected","failed","cancelled","expired"]);function $g(n){return typeof n=="string"&&n.trim()?n.trim():null}function Da(n,r){return Object.freeze({code:n,message:r})}function ec(n){return n?{attemptId:n.id,status:n.state,pollIntervalMs:n.pollIntervalMs,qrRevision:n.qrRevision,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var fC=class{#e;#A;#t;#r;#g;#n;#E=new Map;#s=new Map;#I=new Map;#a=null;#i=new Map;#o=0;#c=!1;constructor({qrAuth:r,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!r||typeof r.start!="function"||typeof r.poll!="function")throw new TypeError("Enterprise WeChat QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WecomController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WecomController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A}async initialize(){if(this.#c)return this.status();for(let r of this.#t.list())await this.#B(r.botId,async()=>{let o=this.#E.get(r.botId)?.status;if(this.#c||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#Q(r.secretRef);if(!i){this.#s.set(r.botId,Da("missing-secret","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002"));return}try{await this.#C(r,i),this.#s.delete(r.botId)}catch{this.#s.set(r.botId,Da("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#n.warn?.(`[dsh-im:wecom] bot ${r.botId} failed to initialize`)}finally{this.#f()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("Enterprise WeChat controller is closed");this.#a&&await this.cancelProvisioning(this.#a);let r={id:Qfe(),state:"pending",createdAt:Date.now(),expiresAt:null,pollIntervalMs:3e3,qrRevision:1,verificationUrl:null,scode:null,botId:null,error:null,controller:new AbortController,polling:null,transition:null};this.#I.set(r.id,r),this.#a=r.id,this.#f();try{let o=await this.#e.start({signal:r.controller.signal});if(r.scode=$g(o.scode),r.verificationUrl=$g(o.verificationUrl),r.expiresAt=Number(o.expiresAt),r.pollIntervalMs=Math.min(1e4,Math.max(500,Number(o.pollIntervalMs)||3e3)),!r.scode||!r.verificationUrl||!Number.isFinite(r.expiresAt))throw new Error("Enterprise WeChat QR auth returned incomplete data");return this.#f(),ec(r)}catch(o){throw r.state=r.controller.signal.aborted?"cancelled":"failed",r.error=r.controller.signal.aborted?Da("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"):Da("qr-start-failed","\u65E0\u6CD5\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),this.#y(r),o}}async registrationStatus(r){let o=this.#I.get(r);if(!o||QC.has(o.state))return ec(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),ec(o);if(Date.now()>=o.expiresAt)return o.state="expired",o.error=Da("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),o.controller.abort(),this.#y(o),ec(o);if(!o.polling){let i=this.#l(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),ec(o)}async bindCredentials({botId:r,secret:o}={}){if(this.#c)throw new Error("Enterprise WeChat controller is closed");let i=$g(r),e=$g(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#a&&await this.cancelProvisioning(this.#a),this.#c)throw new Error("Enterprise WeChat controller is closed");let a=NQ(i);return await this.#B(a.botId,async()=>{if(this.#c)throw new Error("Enterprise WeChat controller is closed");let A=this.#t.getByRemoteBotId(i),t=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#c)throw new Error("Enterprise WeChat controller is closed");let s={botId:a.botId,remoteBotId:i,secretRef:a.secretRef,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#u(a.secretRef,t),g}try{await this.#C(s,e),this.#s.delete(a.botId)}catch{this.#s.set(a.botId,Da("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:wecom] bot ${a.botId} credential connection failed`)}this.#f()}),this.status()}async cancelProvisioning(r){let o=this.#I.get(r);return o?(QC.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),QC.has(o.state)||(o.state="cancelled"),o.error??=Da("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"),this.#y(o)),ec(o)):null}async reconnectBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#B(r,async()=>{let i=await this.#Q(o.secretRef);if(!i)throw new Error("Enterprise WeChat bot secret is missing");try{await this.#C(o,i),this.#s.delete(r)}catch(e){throw this.#s.set(r,Da("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Enterprise WeChat bot");return this.#B(r,async()=>{let i=this.#E.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw kt("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA");return i.sendConnectionTest(Yr(`\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08${r0(o.remoteBotId)}\uFF09`))})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#B(r,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#d(r);try{await this.#A.unset(o.secretRef),await this.#t.remove(r)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#C(o,i.value).catch(()=>{})),new Error("Unable to remove the Enterprise WeChat bot safely.",{cause:e})}await this.#g({botId:r,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:wecom] bot ${r} state cleanup failed:`,e)}),this.#s.delete(r),this.#f()}),this.status()}status(){let r=this.#t.list().map(e=>{let a=this.#E.get(e.botId)?.status??null,A=a?.ready===!0&&a.wecomConnectionState==="connected"&&a.harnessReachable===!0,t=A?"connected":a?.wecomConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||a?.wecomConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",appIdMasked:r0(e.remoteBotId)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":t==="error"?"\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},error:structuredClone(this.#s.get(e.botId)??null)}}),o=r.filter(e=>e.connected).length,i=this.#a?this.#I.get(this.#a):null;return{schemaVersion:1,revision:this.#o,state:i&&N3.has(i.state)?"provisioning":r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o},...i&&N3.has(i.state)?{provisioning:ec(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#a&&await this.cancelProvisioning(this.#a),await Promise.allSettled([...this.#i.values()]),await Promise.allSettled([...this.#E.keys()].map(r=>this.#d(r))))}async#l(r){try{let o=await this.#e.poll({scode:r.scode,signal:r.controller.signal});if(r.controller.signal.aborted||QC.has(r.state)||o.status==="waiting")return;if(o.status==="expired"){r.state="expired",r.error=Da("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),this.#y(r);return}if(o.status!=="success"){r.state="failed",r.error=Da("qr-connect-failed","\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u6CA1\u6709\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"),this.#y(r);return}r.state="connecting",r.verificationUrl=null,r.expiresAt=null,r.scode=null,this.#f();let i=this.#p(r,o);r.transition=i,await i}catch{if(r.controller.signal.aborted)return;r.state="failed",r.error=Da("qr-connect-failed","\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"),this.#n.warn?.("[dsh-im:wecom] QR polling failed"),this.#y(r)}}async#p(r,o){try{let i=$g(o.remoteBotId),e=$g(o.secret);if(!i||!e)throw new Error("Enterprise WeChat authorization returned incomplete credentials");r.botId=await this.#h(r,{remoteBotId:i,secret:e}),r.state="connected",r.error=null}catch{r.controller.signal.aborted?(r.state="cancelled",r.error=Da("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=Da("activation-failed","\u4F01\u4E1A\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u63A5\u5165\u914D\u7F6E\u3002"),this.#n.error?.("[dsh-im:wecom] provisioning failed"))}finally{this.#y(r)}}async#h(r,{remoteBotId:o,secret:i}){let e=NQ(o),a=this.#t.getByRemoteBotId(o),A=await this.#A.resolve(e.secretRef).catch(()=>{}),t={botId:e.botId,remoteBotId:o,secretRef:e.secretRef,createdAt:a?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#B(e.botId,async()=>{await this.#A.set(e.secretRef,i);try{if(r.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(t)}catch(s){throw await this.#u(e.secretRef,A),s}try{if(r.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#C(t,i),this.#s.delete(e.botId)}catch(s){if(r.controller.signal.aborted)throw await this.#d(e.botId),a?await this.#t.save(a).catch(()=>{}):await this.#t.remove(e.botId).catch(()=>null)&&await this.#g({botId:e.botId,config:t}).catch(c=>{this.#n.warn?.("[dsh-im:wecom] cancelled bot state cleanup failed:",c)}),await this.#u(e.secretRef,A),s;this.#s.set(e.botId,Da("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:wecom] bot ${e.botId} activation connection failed`)}return this.#f(),e.botId})}async#C(r,o){if(this.#c)throw new Error("Enterprise WeChat controller is closed");if(await this.#d(r.botId),this.#c)throw new Error("Enterprise WeChat controller is closed");let i=await this.#r({botId:r.botId,config:r,secret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Enterprise WeChat runtime");this.#E.set(r.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#E.delete(r.botId),e}}async#d(r){let o=this.#E.get(r);this.#E.delete(r),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:wecom] bot ${r} failed to stop cleanly:`,i)})}async#Q(r){let o=await this.#A.resolve(r).catch(()=>{});return $g(o?.value)}async#u(r,o){o?.value?await this.#A.set(r,o.value).catch(()=>{}):await this.#A.unset(r).catch(()=>{})}#B(r,o){let a=(this.#i.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(r)===a&&this.#i.delete(r)});return this.#i.set(r,a),a}#y(r){r.scode=null,r.verificationUrl=null,r.expiresAt=null,this.#a===r.id&&(this.#a=null),this.#f();let o=[...this.#I.values()].filter(i=>QC.has(i.state));for(;o.length>16;)this.#I.delete(o.shift().id)}#f(){this.#o+=1}};import{WSAuthFailureError as _fe,WSClient as Nfe,WSReconnectExhaustedError as Tfe}from"@wecom/aibot-node-sdk";import{generateReqId as ffe}from"@wecom/aibot-node-sdk";var yfe=["\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` `),mfe=18e3,T3=5*1024*1024,v3=4,PQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function ys(n){return typeof n=="string"&&n.trim()?n.trim():null}function Ac(n){return n?.body&&typeof n.body=="object"?n.body:{}}function R3(n){let r=Ac(n);return r.chattype==="group"?`group:${r.chatid}`:`direct:${r.from?.userid}`}function P3(n){let r=Ac(n),o="";return r.msgtype==="text"?o=typeof r.text?.content=="string"?r.text.content.trim():"":r.msgtype==="voice"?o=typeof r.voice?.content=="string"?r.voice.content.trim():"":r.msgtype==="mixed"&&Array.isArray(r.mixed?.msg_item)&&(o=r.mixed.msg_item.filter(i=>i?.msgtype==="text"&&typeof i.text?.content=="string").map(i=>i.text.content).join(` -`).trim()),r.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function Sfe(n){let r=Ac(n);return r.msgtype==="image"?[r.image]:r.msgtype!=="mixed"||!Array.isArray(r.mixed?.msg_item)?[]:r.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function Dfe(n,r){let o=ys(r?.url);if(!o)return null;let i=ys(r?.aeskey)??void 0;return{async load({signal:e,maxBytes:a}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat image download is unavailable");let A=await n.downloadFile(o,i);e?.throwIfAborted();let t=A?.buffer;if(!Buffer.isBuffer(t)&&!(t instanceof Uint8Array))throw new Error("Enterprise WeChat image download returned no data");let s=Buffer.from(t);if(Number.isFinite(a)&&s.length>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return{data:s,name:A?.filename}}}}function k3(n,r){return{content:P3(n),images:Sfe(n).map(o=>Dfe(r,o)).filter(Boolean)}}function wfe(n,r){return Mr(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:r,maxBytes:T3});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:a=T3}={}){e?.throwIfAborted();let A=await i;e?.throwIfAborted();let t=A?.data??A?.buffer??A;if((Buffer.isBuffer(t)||t instanceof Uint8Array?t.length:0)>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return A}}})}:n}function Ofe(n){return{...n,images:n.images.map(r=>({...r,async load(){throw new XA("image-queue-full",`Enterprise WeChat already has ${v3} prefetched images`,"\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002")}}))}}function a0(n){return Ac(n).msgtype==="text"?P3(n):""}function GQ(n,r=mfe){let o=String(n??"").trim();if(!o)return[];let i=[],e="",a=0;for(let A of o){let t=Buffer.byteLength(A);e&&a+t>r?(i.push(e),e=A,a=t):(e+=A,a+=t)}return e&&i.push(e),i}function Mfe(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function bfe(n,r){return r.questions[r.index]&&ys(Ac(n).from?.userid)===r.actor&&ys(a0(n))}function i0(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var FQ=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Set;#c=new Set;#l;#p=0;constructor({client:r,harness:o,state:i,status:e=i0(),logger:a=console,replyTimeoutMs:A=6e5,generateStreamId:t=ffe,signal:s}){if(!r||typeof r.replyStream!="function"||typeof r.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#l=new Ca({label:"wecom",logger:a})}get status(){return structuredClone(this.#r)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Ac(r),i=ys(o.msgid),e=ys(o.from?.userid),a=o.chattype==="group"?ys(o.chatid):e;if(!i||!e||!a||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#o.has(i))return Promise.resolve();let A=R3(r);this.#o.add(i),o.chattype==="single"&&Va(this.#t,{chatId:a});let t=this.#a.get(A),s=this.#l.claimReply({key:A,actor:e,messageId:i,text:a0(r),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#a.has(A),send:g=>this.#d(r,a,g)});if(s){let g;return g=s.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(i),this.#c.delete(g)}),this.#c.add(g),g}if(t&&t.actor!==e)return this.#h(r,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#h(r,i,A);if(t){bfe(r,t)&&(t.claimedReplyMessageId=i);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(r,i,e,a,A,t)).finally(()=>{this.#o.delete(i),t.claimedReplyMessageId===i&&(t.claimedReplyMessageId=null),t.queue===c&&(t.queue=null)});return t.queue=c,c}return this.#h(r,i,A)}#h(r,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1}={}){let A=k3(r,this.#e),t=A.images.length,s=0,g=A;t>0&&(this.#p+t<=v3?(s=t,this.#p+=s,g=wfe(A,this.#s)):g=Ofe(A));let l=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,{alreadyRecorded:a,preparedMessage:g})).finally(()=>{this.#p-=s,e&&this.#o.delete(o),this.#I.get(i)===l&&this.#I.delete(i)});return this.#I.set(i,l),l}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c])}async#C(r,o){for(let i of GQ(o))this.#s?.throwIfAborted(),await this.#e.sendMessage(r,{msgtype:"markdown",markdown:{content:i}})}async#d(r,o,i){this.#s?.throwIfAborted();let e=GQ(i);if(e.length!==0)try{await this.#e.replyStream(r,this.#E("stream"),e[0],!0);for(let a of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:a}})}catch{await this.#C(o,i)}}async#Q(r,{alreadyRecorded:o=!1,preparedMessage:i}={}){if(this.#s?.aborted)return;let e=Ac(r),a=typeof e.msgid=="string"?e.msgid:"",A=typeof e.from?.userid=="string"?e.from.userid:"",t=e.chattype==="group"?e.chatid:A;if(!a||!A||!t||!["single","group"].includes(e.chattype))return;if(!o){if(this.#t.hasSeen(a))return;this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString()}let s=i??k3(r,this.#e),g=s.content,c=Mr(s),l=R3(r),p=null,B=!1;try{if(!g&&!c){await this.#d(r,t,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002"),await this.#t.markSeen(a);return}let Q=g.toLowerCase();if(!c&&Q==="/help"){await this.#d(r,t,yfe),await this.#t.markSeen(a);return}if(!c&&Q==="/status"){await this.#A.ensureRunning({signal:this.#s}),await this.#d(r,t,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(a);return}if(!c&&Q==="/new"){await this.#t.clearSession(l),await this.#d(r,t,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(a);return}let f=c?null:await ti(g,this.#A,l);if(f){for(let K of f.messages??[f.message])await this.#d(r,t,K);await this.#t.markSeen(a);return}let y=c?null:await Ai(g,this.#A,this.#t,l,{signal:this.#s});if(y){await this.#d(r,t,y.message),await this.#t.markSeen(a);return}p=this.#E("stream");try{await this.#e.replyStream(r,p,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),B=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",K)}let m=c?await Wa(s,{signal:this.#s}):void 0,{answer:R}=await ha({harness:this.#A,state:this.#t,key:l,text:g,content:m,createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#n,signal:this.#s,onUpdate:B&&typeof this.#e.replyStreamNonBlocking=="function"?async K=>{let x=GQ(Mfe(K))[0];x&&await this.#e.replyStreamNonBlocking(r,p,x,!1)}:void 0,onInteraction:K=>this.#B(K,{key:l,actor:A,chatId:t,requiresMention:e.chattype==="group"}),onInteractionResolved:K=>this.#y(K)}}),k=GQ(R||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),G=!1;if(B&&k.length>0)try{await this.#e.replyStream(r,p,k[0],!0);for(let K of k.slice(1))await this.#e.sendMessage(t,{msgtype:"markdown",markdown:{content:K}});G=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",K)}G||await this.#C(t,R),await this.#t.markSeen(a),this.#r.messagesReplied+=1,this.#r.lastReplyAt=new Date().toISOString(),this.#r.lastError=null}catch(Q){if(this.#s?.aborted)return;this.#r.lastError=Q?.message??String(Q),this.#g.error?.("[dsh-im:wecom] failed to process an inbound message");let f=Za(Q)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{B&&p?await this.#e.replyStream(r,p,f,!0):await this.#d(r,t,f),await this.#t.markSeen(a)}catch{this.#g.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await Promise.allSettled([this.#N(l),this.#l.closeRoute(l)])}}async#u(r,o,i,e,a,A){if(this.#s?.aborted)return;let t=this.#a.get(a),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#D(r,o,e):this.#h(r,o,a,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString();let g=ys(a0(r));if(!g){await this.#d(r,e,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#a.get(a);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#f(c)}catch{this.#r.lastError="\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let p=this.#a.get(a);if(!p||p!==A||p.submitting){if(s&&(!p||p!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,g)),c.index+=1,c.index{});return}if(this.#a.get(a)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#r.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#d(r,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#B(r,{key:o,actor:i,chatId:e,requiresMention:a}){if(r?.kind==="approval")return this.#l.handleRequested(r,{key:o,actor:i,requiresMention:a,send:c=>this.#C(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r?.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#g.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#C(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002").catch(()=>{});return}let s=this.#a.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#f(s);return}if(this.#i.has(t))return;if(s){this.#g.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await r.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#a.set(o,g),this.#i.set(g.interactionId,o),await this.#f(g)}async#y(r){if(r?.kind==="approval"){await this.#l.handleResolved(r);return}let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#i.get(o);i&&this.#w(i,o)}#f(r){if(!r.needsPresentation)return Promise.resolve();if(r.presentationPromise)return r.presentationPromise;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=this.#C(r.chatId,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})).then(()=>{r.needsPresentation=!1}).finally(()=>{r.presentationPromise===i&&(r.presentationPromise=null)});return r.presentationPromise=i,i}async#D(r,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),await this.#d(r,i,PQ).catch(()=>{}))}#m(r,o){let i=this.#a.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#a.delete(r),this.#i.delete(i.interactionId),i)}#w(r,o){return this.#m(r,o)!==null}async#N(r){let o=this.#m(r);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#g.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function Rfe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function kfe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...i0()}}var yC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=kfe();#i=null;#o=null;#c=null;#l=null;#p=null;constructor({config:r,secret:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new Nfe(c)}){if(!r||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}get status(){return structuredClone(this.#a)}async start(){if(this.#a.ready&&this.#i)return this.status;if(this.#c)return this.#c;this.#p?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let r=new AbortController;return this.#l=r,this.#p=r,this.#c=this.#h(r.signal).finally(()=>{this.#l===r&&(this.#l=null),this.#c=null}),this.#c}async#h(r){await this.#C(),r.throwIfAborted(),this.#a.startedAt=new Date().toISOString(),this.#a.wecomConnectionState="connecting",this.#a.lastError=null,await this.#t.ensureRunning(),this.#a.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#I({botId:this.#e.remoteBotId,secret:this.#A,logger:o,maxReconnectAttempts:this.#s});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#i=i,this.#o=new FQ({client:i,harness:this.#t,state:this.#r,status:this.#a,logger:this.#g,replyTimeoutMs:this.#n,signal:r});let e,a,A=!1,t=new Promise((Q,f)=>{e=Q,a=f}),s=()=>{if(this.#i!==i||r.aborted)return;A=!0;let Q=Date.now();this.#a.ready=!0,this.#a.wecomConnectionState="connected",this.#a.lastCheckedAt=Q,this.#a.lastConnectedAt=Q,this.#a.lastError=null,e()},g=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},c=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},l=Q=>{if(this.#i!==i)return;let f=Q instanceof _fe||Q instanceof Tfe;!A&&f&&a(Q),f&&(this.#a.ready=!1,this.#a.wecomConnectionState="failed"),this.#a.lastError=f?Q.name:"connection-error",this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} connection error`)},p=Q=>this.#o?.accept(Q);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",l),i.on("message",p);let B;try{return i.connect(),await Promise.race([t,new Promise((Q,f)=>{r.addEventListener("abort",()=>f(r.reason),{once:!0})}),new Promise((Q,f)=>{B=setTimeout(()=>f(Rfe()),this.#E)})]),this.status}catch(Q){throw r.aborted?(await this.#C(),Q):(this.#a.ready=!1,this.#a.wecomConnectionState="failed",this.#a.lastError=Q?.message??String(Q),await this.#C(),Q)}finally{clearTimeout(B)}}async stop(){let r=this.#c;return this.#l?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p=null,await this.#C(),await r?.catch(()=>{}),this.status}async sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",send:async({chatId:o},i)=>{if(!this.#a.ready||!this.#i)throw new Error("Enterprise WeChat runtime is not connected");await this.#i.sendMessage(o,{msgtype:"markdown",markdown:{content:i}})}})}async#C(){let r=this.#i,o=this.#o;this.#i=null,this.#o=null;try{r?.disconnect(),r?.removeAllListeners?.()}catch{this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#a.ready=!1,this.#a.wecomConnectionState="idle"}};var G3=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function vfe(n){if(!Array.isArray(n)||n.length===0)return[...G3];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...G3]}var LQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=vfe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-im Enterprise WeChat requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function Lfe(n){let r=tc(n.dshHome??process.env.DSH_HOME??mC(Gfe(),".dsh")),o=tc(n.dataDir??mC(r,"integrations","dsh-wecom"));return{config:tc(n.configPath??mC(o,"config.json")),bots:tc(n.botsDir??mC(o,"bots")),workspaces:tc(n.workspacesPath??mC(o,"workspaces.json"))}}async function n0(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-im Enterprise WeChat requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im Enterprise WeChat requires ctx.webServer");let i=o.ConfigStore??_Q,e=o.StateStore??vQ,a=o.HarnessClient??TQ,A=o.Controller??fC,t=o.Runtime??yC,s=o.QrAuth??RQ,g=o.createConnectionSupervisor??o0,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Lfe(r),p=await new i(l.config).load(),B=tc(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(T=>T.botId)),await Promise.all(y.map(T=>f.ensure(T.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=o.qrAuth??new s({source:r.qrSource??"deepseek-harness",platform:r.qrPlatform}),k=new Map,G=T=>tc(l.bots,T,"state.json"),K=async T=>{let V=k.get(T);return V||(V=await new e(G(T)).load(),k.set(T,V)),V},x=zr(n,o.commandExecutor),H=new a({baseUrl:Ffe(n.webServer,r.harnessBaseUrl),workspace:B,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...x?{commandExecutor:x}:{}}),q=new A({qrAuth:R,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:T,config:V,secret:U})=>{let b=await K(T);await f.ensure(T);let L=qr(H,{botId:T,workspaces:f,state:b});return new t({config:V,secret:U,harness:L.harness,state:L.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,maxReconnectAttempts:r.maxReconnectAttempts??10,logger:{error:(...X)=>c.error?.(`[${T}]`,...X),warn:(...X)=>c.warn?.(`[${T}]`,...X),info:(...X)=>c.info?.(`[${T}]`,...X),debug:(...X)=>c.debug?.(`[${T}]`,...X)}})},deleteState:async({botId:T})=>{let V=k.get(T);if(k.delete(T),V&&typeof V.remove=="function")await V.remove();else try{await Pfe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=Vr(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import Ufe from"qrcode";var L3="/wecom",Nr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),U3=Object.freeze(Object.values(Nr)),Hfe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function c0(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function VI(n,r){return c0(n)&&Object.keys(n).every(o=>r.includes(o))}function s0(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function F3(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function Kfe(n,r){return c0(r)?n===Nr.status?VI(r,[])?null:"connection.status does not accept fields.":n===Nr.beginProvisioning?VI(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Nr.pollProvisioning,Nr.cancelProvisioning].includes(n)?VI(r,["attemptId"])&&s0(r.attemptId)?null:`${n} requires an attemptId.`:n===Nr.bindCredentials?VI(r,["botId","secret"])&&F3(r.botId,512)&&F3(r.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===Nr.reconnectBot?VI(r,["botId","sendTest"])&&s0(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Nr.deleteBot?VI(r,["botId","confirm"])&&s0(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Nr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function zI(n){if(Array.isArray(n))return n.map(zI);if(!c0(n))return n;let r={};for(let[o,i]of Object.entries(n))Hfe.has(o)||(r[o]=zI(i));return r}async function Yfe(n){return Ufe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function g0(n,r){return!n||typeof n.verificationUrl!="string"?zI(n):zI({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function SC(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await g0(o.provisioning,r)),zI(o)}function H3(n,{encodeQr:r=Yfe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat 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(()=>r(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(!U3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Kfe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===Nr.status)s=await SC(await n.status(),i);else if(e===Nr.beginProvisioning)s=await g0(await n.startProvisioning(),i);else if(e===Nr.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 g0(g,i)}else if(e===Nr.cancelProvisioning)s=zI(await n.cancelProvisioning(a.attemptId));else if(e===Nr.bindCredentials)s=await SC(await n.bindCredentials(a),i);else if(e===Nr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await SC({...g,...c?{testMessage:c}:{}},i)}else if(e===Nr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await SC(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await SC(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=Xr(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"wecom-operation-failed",message:"\u4F01\u4E1A\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function UQ(n,r,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(L3,H3(r,o),{authority:Wr(i)})}async function K3(n,r={}){if(r?.controller)return UQ(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await n0(n,r,r.internals),i=UQ(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as Rye}from"node:fs/promises";import{homedir as kye}from"node:os";import{join as bC,resolve as rc}from"node:path";import{createHash as nye}from"node:crypto";import{mkdir as sye,readFile as gye,rename as cye,unlink as Iye,writeFile as lye}from"node:fs/promises";import{dirname as Eye}from"node:path";import{createDecipheriv as xfe,randomBytes as jfe,randomUUID as Jfe}from"node:crypto";var KQ="https://ilinkai.weixin.qq.com/",qfe="2.4.6",Vfe="3",zfe="https://novac2c.cdn.weixin.qq.com/c2c",j3="novac2c.cdn.weixin.qq.com",Wfe="bot",Zfe=2<<16|1024|6,Xfe=15e3,Y3=35e3,$fe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),qA=class extends Error{constructor(r,o,i={}){super(o,i),this.name="WeixinApiError",this.code=r,this.status=i.status}};function aa(n){return typeof n=="string"&&n.trim()?n.trim():null}function eye(n){let r=aa(n);return!r||r.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(r)?null:Buffer.from(r,"base64")}function Aye(n){let r=aa(n?.aeskey);if(r){if(!/^[0-9a-fA-F]{32}$/.test(r))throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(r,"hex")}let o=eye(n?.media?.aes_key);if(o?.length===16)return o;if(o?.length===32&&/^[0-9a-fA-F]{32}$/.test(o.toString("ascii")))return Buffer.from(o.toString("ascii"),"hex");throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002")}function tye(n,r){let o=Buffer.from(n),i=Buffer.from(r);if(i.length!==16||o.length===0||o.length%16!==0)throw new qA("invalid-image-ciphertext","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u6570\u636E\u65E0\u6548\u3002");try{let e=xfe("aes-128-ecb",i,null);return Buffer.concat([e.update(o),e.final()])}catch(e){throw new qA("image-decryption-failed","\u5FAE\u4FE1\u56FE\u7247\u89E3\u5BC6\u5931\u8D25\u3002",{cause:e})}}function rye(n){let r=aa(n?.encrypt_query_param);if(r)return`${zfe}/download?encrypted_query_param=${encodeURIComponent(r)}`;let o=aa(n?.full_url);if(!o)throw new qA("missing-image-url","\u5FAE\u4FE1\u56FE\u7247\u6CA1\u6709\u53EF\u7528\u7684\u4E0B\u8F7D\u5730\u5740\u3002");let i;try{i=new URL(o)}catch{throw new qA("invalid-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u65E0\u6548\u3002")}if(i.protocol!=="https:"||i.hostname!==j3||i.port&&i.port!=="443"||!i.pathname.startsWith("/c2c/"))throw new qA("untrusted-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u4E0D\u53D7\u4FE1\u4EFB\u3002");return i.username="",i.password="",i.hash="",i.toString()}function I0(n,{fetchImpl:r=fetch}={}){if(typeof r!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.image_item;!e||typeof e!="object"||o.push({name:o.length===0?"image":`image-${o.length+1}`,load:async({signal:a,maxBytes:A})=>{let t=Aye(e),s=rye(e.media),g=await za(s,{fetchImpl:r,signal:a,maxBytes:A+16,allowedHosts:[j3]});return tye(g,t)}})}return o}function l0(n){let r=n.toLowerCase().replace(/\.$/,"");return r==="weixin.qq.com"||r.endsWith(".weixin.qq.com")}function ZI(n){let r;try{r=new URL(n)}catch{throw new qA("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(r.protocol!=="https:"||!l0(r.hostname)||r.port!==""&&r.port!=="443")throw new qA("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return r.username="",r.password="",r.search="",r.hash="",r.pathname.endsWith("/")||(r.pathname+="/"),r.toString()}function aye(n){let r=aa(n);if(!r)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(r)}catch{throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!l0(o.hostname))throw new qA("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function J3(){return{"iLink-App-Id":Wfe,"iLink-App-ClientVersion":String(Zfe)}}function iye(n){let r={...J3(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(jfe(4).readUInt32BE(0)),"utf8").toString("base64")};return aa(n)&&(r.Authorization=`Bearer ${n.trim()}`),r}function HQ(){return{channel_version:qfe,bot_agent:"DeepSeekHarness/0.10.0"}}function x3(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function WI(n,{method:r,baseUrl:o,endpoint:i,body:e,token:a,timeoutMs:A=Xfe,signal:t,authenticated:s=!0}){let g=ZI(o),c=new URL(i,g);if(!l0(c.hostname))throw new qA("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let l=new AbortController,p=!1,B=()=>l.abort(t?.reason);if(t?.aborted)throw x3(t);t?.addEventListener("abort",B,{once:!0});let Q=A>0?setTimeout(()=>{p=!0,l.abort()},A):null;try{let f=await n(c,{method:r,headers:s?iye(a):J3(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new qA("http-error",`\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${f.status}\uFF09\u3002`,{status:f.status});try{return await f.json()}catch(y){throw new qA("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?x3(t):p?new qA("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof qA?f:new qA("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",B)}}function oye(n){if(!n||typeof n!="object"||!$fe.has(n.status))throw new qA("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function q3({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({inboundImages(r){return I0(r,{fetchImpl:n})},async beginLogin({localTokens:r=[],botType:o=Vfe,signal:i}={}){let e=[...new Set(r.map(aa).filter(Boolean))].slice(-10),a=await WI(n,{method:"POST",baseUrl:KQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=aa(a?.qrcode);if(!A)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:aye(a.qrcode_img_content)}},async pollLogin({qrcode:r,baseUrl:o=KQ,verifyCode:i,signal:e}){let a=aa(r);if(!a)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(a)}`;aa(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await WI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:Y3,signal:e,authenticated:!1});return oye(t)},async getUpdates({baseUrl:r,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:a}){try{return await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:HQ()},token:o,timeoutMs:e??Y3,signal:a})}catch(A){if(A instanceof qA&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:r,token:o,toUserId:i,text:e,contextToken:a,runId:A,signal:t}){let s=aa(i),g=aa(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Jfe()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...aa(a)?{context_token:a.trim()}:{},...aa(A)?{run_id:A.trim()}:{}},base_info:HQ()}});if(c?.ret!==void 0&&c.ret!==0)throw new qA("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async notifyStart({baseUrl:r,token:o,signal:i}){let e=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}});if(e?.ret!==void 0&&e.ret!==0)throw new qA("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:r,token:o,signal:i}){return WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}})}})}function DC(n){for(let r of n?.item_list??[]){if(r?.type===1&&typeof r.text_item?.text=="string"){let o=r.text_item.text.trim();if(o)return o}if(r?.type===3&&typeof r.voice_item?.text=="string"){let o=r.voice_item.text.trim();if(o)return o}}return null}function E0(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):aa(n?.client_id)}function V3(n,r=4e3){if(n.length<=r)return[n];let o=[],i=n;for(;i.length>r;){let e=i.lastIndexOf(` +`).trim()),r.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function Sfe(n){let r=Ac(n);return r.msgtype==="image"?[r.image]:r.msgtype!=="mixed"||!Array.isArray(r.mixed?.msg_item)?[]:r.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function Dfe(n,r){let o=ys(r?.url);if(!o)return null;let i=ys(r?.aeskey)??void 0;return{async load({signal:e,maxBytes:a}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat image download is unavailable");let A=await n.downloadFile(o,i);e?.throwIfAborted();let t=A?.buffer;if(!Buffer.isBuffer(t)&&!(t instanceof Uint8Array))throw new Error("Enterprise WeChat image download returned no data");let s=Buffer.from(t);if(Number.isFinite(a)&&s.length>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return{data:s,name:A?.filename}}}}function k3(n,r){return{content:P3(n),images:Sfe(n).map(o=>Dfe(r,o)).filter(Boolean)}}function wfe(n,r){return Mr(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:r,maxBytes:T3});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:a=T3}={}){e?.throwIfAborted();let A=await i;e?.throwIfAborted();let t=A?.data??A?.buffer??A;if((Buffer.isBuffer(t)||t instanceof Uint8Array?t.length:0)>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return A}}})}:n}function Ofe(n){return{...n,images:n.images.map(r=>({...r,async load(){throw new XA("image-queue-full",`Enterprise WeChat already has ${v3} prefetched images`,"\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002")}}))}}function a0(n){return Ac(n).msgtype==="text"?P3(n):""}function GQ(n,r=mfe){let o=String(n??"").trim();if(!o)return[];let i=[],e="",a=0;for(let A of o){let t=Buffer.byteLength(A);e&&a+t>r?(i.push(e),e=A,a=t):(e+=A,a+=t)}return e&&i.push(e),i}function Mfe(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function bfe(n,r){return r.questions[r.index]&&ys(Ac(n).from?.userid)===r.actor&&ys(a0(n))}function i0(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var FQ=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Set;#c=new Set;#l;#p=0;constructor({client:r,harness:o,state:i,status:e=i0(),logger:a=console,replyTimeoutMs:A=6e5,generateStreamId:t=ffe,signal:s}){if(!r||typeof r.replyStream!="function"||typeof r.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#l=new Ca({label:"wecom",logger:a})}get status(){return structuredClone(this.#r)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Ac(r),i=ys(o.msgid),e=ys(o.from?.userid),a=o.chattype==="group"?ys(o.chatid):e;if(!i||!e||!a||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#o.has(i))return Promise.resolve();let A=R3(r);this.#o.add(i),o.chattype==="single"&&Va(this.#t,{chatId:a});let t=this.#a.get(A),s=this.#l.claimReply({key:A,actor:e,messageId:i,text:a0(r),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#a.has(A),send:g=>this.#d(r,a,g)});if(s){let g;return g=s.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(i),this.#c.delete(g)}),this.#c.add(g),g}if(t&&t.actor!==e)return this.#h(r,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#h(r,i,A);if(t){bfe(r,t)&&(t.claimedReplyMessageId=i);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(r,i,e,a,A,t)).finally(()=>{this.#o.delete(i),t.claimedReplyMessageId===i&&(t.claimedReplyMessageId=null),t.queue===c&&(t.queue=null)});return t.queue=c,c}return this.#h(r,i,A)}#h(r,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1}={}){let A=k3(r,this.#e),t=A.images.length,s=0,g=A;t>0&&(this.#p+t<=v3?(s=t,this.#p+=s,g=wfe(A,this.#s)):g=Ofe(A));let l=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,{alreadyRecorded:a,preparedMessage:g})).finally(()=>{this.#p-=s,e&&this.#o.delete(o),this.#I.get(i)===l&&this.#I.delete(i)});return this.#I.set(i,l),l}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c])}async#C(r,o){for(let i of GQ(o))this.#s?.throwIfAborted(),await this.#e.sendMessage(r,{msgtype:"markdown",markdown:{content:i}})}async#d(r,o,i){this.#s?.throwIfAborted();let e=GQ(i);if(e.length!==0)try{await this.#e.replyStream(r,this.#E("stream"),e[0],!0);for(let a of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:a}})}catch{await this.#C(o,i)}}async#Q(r,{alreadyRecorded:o=!1,preparedMessage:i}={}){if(this.#s?.aborted)return;let e=Ac(r),a=typeof e.msgid=="string"?e.msgid:"",A=typeof e.from?.userid=="string"?e.from.userid:"",t=e.chattype==="group"?e.chatid:A;if(!a||!A||!t||!["single","group"].includes(e.chattype))return;if(!o){if(this.#t.hasSeen(a))return;this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString()}let s=i??k3(r,this.#e),g=s.content,c=Mr(s),l=R3(r),p=null,B=!1;try{if(!g&&!c){await this.#d(r,t,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002"),await this.#t.markSeen(a);return}let Q=g.toLowerCase();if(!c&&Q==="/help"){await this.#d(r,t,yfe),await this.#t.markSeen(a);return}if(!c&&Q==="/status"){await this.#A.ensureRunning({signal:this.#s}),await this.#d(r,t,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(a);return}if(!c&&Q==="/new"){await this.#t.clearSession(l),await this.#d(r,t,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(a);return}let f=c?null:await ti(g,this.#A,l);if(f){for(let K of f.messages??[f.message])await this.#d(r,t,K);await this.#t.markSeen(a);return}let y=c?null:await Ai(g,this.#A,this.#t,l,{signal:this.#s});if(y){await this.#d(r,t,y.message),await this.#t.markSeen(a);return}p=this.#E("stream");try{await this.#e.replyStream(r,p,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),B=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",K)}let m=c?await Wa(s,{signal:this.#s}):void 0,{answer:R}=await ha({harness:this.#A,state:this.#t,key:l,text:g,content:m,createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#n,signal:this.#s,onUpdate:B&&typeof this.#e.replyStreamNonBlocking=="function"?async K=>{let x=GQ(Mfe(K))[0];x&&await this.#e.replyStreamNonBlocking(r,p,x,!1)}:void 0,onInteraction:K=>this.#B(K,{key:l,actor:A,chatId:t,requiresMention:e.chattype==="group"}),onInteractionResolved:K=>this.#y(K)}}),k=GQ(R||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),G=!1;if(B&&k.length>0)try{await this.#e.replyStream(r,p,k[0],!0);for(let K of k.slice(1))await this.#e.sendMessage(t,{msgtype:"markdown",markdown:{content:K}});G=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",K)}G||await this.#C(t,R),await this.#t.markSeen(a),this.#r.messagesReplied+=1,this.#r.lastReplyAt=new Date().toISOString(),this.#r.lastError=null}catch(Q){if(this.#s?.aborted)return;this.#r.lastError=Q?.message??String(Q),this.#g.error?.("[dsh-im:wecom] failed to process an inbound message");let f=Za(Q)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{B&&p?await this.#e.replyStream(r,p,f,!0):await this.#d(r,t,f),await this.#t.markSeen(a)}catch{this.#g.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await Promise.allSettled([this.#N(l),this.#l.closeRoute(l)])}}async#u(r,o,i,e,a,A){if(this.#s?.aborted)return;let t=this.#a.get(a),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#D(r,o,e):this.#h(r,o,a,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString();let g=ys(a0(r));if(!g){await this.#d(r,e,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#a.get(a);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#f(c)}catch{this.#r.lastError="\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let p=this.#a.get(a);if(!p||p!==A||p.submitting){if(s&&(!p||p!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,g)),c.index+=1,c.index{});return}if(this.#a.get(a)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#r.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#d(r,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#B(r,{key:o,actor:i,chatId:e,requiresMention:a}){if(r?.kind==="approval")return this.#l.handleRequested(r,{key:o,actor:i,requiresMention:a,send:c=>this.#C(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r?.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#g.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#C(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002").catch(()=>{});return}let s=this.#a.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#f(s);return}if(this.#i.has(t))return;if(s){this.#g.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await r.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#a.set(o,g),this.#i.set(g.interactionId,o),await this.#f(g)}async#y(r){if(r?.kind==="approval"){await this.#l.handleResolved(r);return}let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#i.get(o);i&&this.#w(i,o)}#f(r){if(!r.needsPresentation)return Promise.resolve();if(r.presentationPromise)return r.presentationPromise;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=this.#C(r.chatId,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})).then(()=>{r.needsPresentation=!1}).finally(()=>{r.presentationPromise===i&&(r.presentationPromise=null)});return r.presentationPromise=i,i}async#D(r,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),await this.#d(r,i,PQ).catch(()=>{}))}#m(r,o){let i=this.#a.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#a.delete(r),this.#i.delete(i.interactionId),i)}#w(r,o){return this.#m(r,o)!==null}async#N(r){let o=this.#m(r);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#g.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function Rfe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function kfe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...i0()}}var yC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=kfe();#i=null;#o=null;#c=null;#l=null;#p=null;constructor({config:r,secret:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new Nfe(c)}){if(!r||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}get status(){return structuredClone(this.#a)}async start(){if(this.#a.ready&&this.#i)return this.status;if(this.#c)return this.#c;this.#p?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let r=new AbortController;return this.#l=r,this.#p=r,this.#c=this.#h(r.signal).finally(()=>{this.#l===r&&(this.#l=null),this.#c=null}),this.#c}async#h(r){await this.#C(),r.throwIfAborted(),this.#a.startedAt=new Date().toISOString(),this.#a.wecomConnectionState="connecting",this.#a.lastError=null,await this.#t.ensureRunning(),this.#a.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#I({botId:this.#e.remoteBotId,secret:this.#A,logger:o,maxReconnectAttempts:this.#s});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#i=i,this.#o=new FQ({client:i,harness:this.#t,state:this.#r,status:this.#a,logger:this.#g,replyTimeoutMs:this.#n,signal:r});let e,a,A=!1,t=new Promise((Q,f)=>{e=Q,a=f}),s=()=>{if(this.#i!==i||r.aborted)return;A=!0;let Q=Date.now();this.#a.ready=!0,this.#a.wecomConnectionState="connected",this.#a.lastCheckedAt=Q,this.#a.lastConnectedAt=Q,this.#a.lastError=null,e()},g=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},c=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},l=Q=>{if(this.#i!==i)return;let f=Q instanceof _fe||Q instanceof Tfe;!A&&f&&a(Q),f&&(this.#a.ready=!1,this.#a.wecomConnectionState="failed"),this.#a.lastError=f?Q.name:"connection-error",this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} connection error`)},p=Q=>this.#o?.accept(Q);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",l),i.on("message",p);let B;try{return i.connect(),await Promise.race([t,new Promise((Q,f)=>{r.addEventListener("abort",()=>f(r.reason),{once:!0})}),new Promise((Q,f)=>{B=setTimeout(()=>f(Rfe()),this.#E)})]),this.status}catch(Q){throw r.aborted?(await this.#C(),Q):(this.#a.ready=!1,this.#a.wecomConnectionState="failed",this.#a.lastError=Q?.message??String(Q),await this.#C(),Q)}finally{clearTimeout(B)}}async stop(){let r=this.#c;return this.#l?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p=null,await this.#C(),await r?.catch(()=>{}),this.status}async sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",send:async({chatId:o},i)=>{if(!this.#a.ready||!this.#i)throw new Error("Enterprise WeChat runtime is not connected");await this.#i.sendMessage(o,{msgtype:"markdown",markdown:{content:i}})}})}async#C(){let r=this.#i,o=this.#o;this.#i=null,this.#o=null;try{r?.disconnect(),r?.removeAllListeners?.()}catch{this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#a.ready=!1,this.#a.wecomConnectionState="idle"}};var G3=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function vfe(n){if(!Array.isArray(n)||n.length===0)return[...G3];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...G3]}var LQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=vfe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-im Enterprise WeChat requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function Lfe(n){let r=tc(n.dshHome??process.env.DSH_HOME??mC(Gfe(),".dsh")),o=tc(n.dataDir??mC(r,"integrations","dsh-wecom"));return{config:tc(n.configPath??mC(o,"config.json")),bots:tc(n.botsDir??mC(o,"bots")),workspaces:tc(n.workspacesPath??mC(o,"workspaces.json"))}}async function n0(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-im Enterprise WeChat requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im Enterprise WeChat requires ctx.webServer");let i=o.ConfigStore??_Q,e=o.StateStore??vQ,a=o.HarnessClient??TQ,A=o.Controller??fC,t=o.Runtime??yC,s=o.QrAuth??RQ,g=o.createConnectionSupervisor??o0,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Lfe(r),p=await new i(l.config).load(),B=tc(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(T=>T.botId)),await Promise.all(y.map(T=>f.ensure(T.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=o.qrAuth??new s({source:r.qrSource??"deepseek-harness",platform:r.qrPlatform}),k=new Map,G=T=>tc(l.bots,T,"state.json"),K=async T=>{let V=k.get(T);return V||(V=await new e(G(T)).load(),k.set(T,V)),V},x=zr(n,o.commandExecutor),H=new a({baseUrl:Ffe(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...x?{commandExecutor:x}:{}}),q=new A({qrAuth:R,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:T,config:V,secret:U})=>{let b=await K(T);await f.ensure(T);let L=qr(H,{botId:T,workspaces:f,state:b});return new t({config:V,secret:U,harness:L.harness,state:L.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,maxReconnectAttempts:r.maxReconnectAttempts??10,logger:{error:(...X)=>c.error?.(`[${T}]`,...X),warn:(...X)=>c.warn?.(`[${T}]`,...X),info:(...X)=>c.info?.(`[${T}]`,...X),debug:(...X)=>c.debug?.(`[${T}]`,...X)}})},deleteState:async({botId:T})=>{let V=k.get(T);if(k.delete(T),V&&typeof V.remove=="function")await V.remove();else try{await Pfe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=Vr(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import Ufe from"qrcode";var L3="/wecom",Nr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),U3=Object.freeze(Object.values(Nr)),Hfe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function c0(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function VI(n,r){return c0(n)&&Object.keys(n).every(o=>r.includes(o))}function s0(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function F3(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function Kfe(n,r){return c0(r)?n===Nr.status?VI(r,[])?null:"connection.status does not accept fields.":n===Nr.beginProvisioning?VI(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Nr.pollProvisioning,Nr.cancelProvisioning].includes(n)?VI(r,["attemptId"])&&s0(r.attemptId)?null:`${n} requires an attemptId.`:n===Nr.bindCredentials?VI(r,["botId","secret"])&&F3(r.botId,512)&&F3(r.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===Nr.reconnectBot?VI(r,["botId","sendTest"])&&s0(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Nr.deleteBot?VI(r,["botId","confirm"])&&s0(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Nr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function zI(n){if(Array.isArray(n))return n.map(zI);if(!c0(n))return n;let r={};for(let[o,i]of Object.entries(n))Hfe.has(o)||(r[o]=zI(i));return r}async function Yfe(n){return Ufe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function g0(n,r){return!n||typeof n.verificationUrl!="string"?zI(n):zI({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function SC(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await g0(o.provisioning,r)),zI(o)}function H3(n,{encodeQr:r=Yfe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat 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(()=>r(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(!U3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Kfe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===Nr.status)s=await SC(await n.status(),i);else if(e===Nr.beginProvisioning)s=await g0(await n.startProvisioning(),i);else if(e===Nr.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 g0(g,i)}else if(e===Nr.cancelProvisioning)s=zI(await n.cancelProvisioning(a.attemptId));else if(e===Nr.bindCredentials)s=await SC(await n.bindCredentials(a),i);else if(e===Nr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await SC({...g,...c?{testMessage:c}:{}},i)}else if(e===Nr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await SC(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await SC(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=Xr(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"wecom-operation-failed",message:"\u4F01\u4E1A\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function UQ(n,r,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(L3,H3(r,o),{authority:Wr(i)})}async function K3(n,r={}){if(r?.controller)return UQ(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await n0(n,r,r.internals),i=UQ(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as Rye}from"node:fs/promises";import{homedir as kye}from"node:os";import{join as bC,resolve as rc}from"node:path";import{createHash as nye}from"node:crypto";import{mkdir as sye,readFile as gye,rename as cye,unlink as Iye,writeFile as lye}from"node:fs/promises";import{dirname as Eye}from"node:path";import{createDecipheriv as xfe,randomBytes as jfe,randomUUID as Jfe}from"node:crypto";var KQ="https://ilinkai.weixin.qq.com/",qfe="2.4.6",Vfe="3",zfe="https://novac2c.cdn.weixin.qq.com/c2c",j3="novac2c.cdn.weixin.qq.com",Wfe="bot",Zfe=2<<16|1024|6,Xfe=15e3,Y3=35e3,$fe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),qA=class extends Error{constructor(r,o,i={}){super(o,i),this.name="WeixinApiError",this.code=r,this.status=i.status}};function aa(n){return typeof n=="string"&&n.trim()?n.trim():null}function eye(n){let r=aa(n);return!r||r.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(r)?null:Buffer.from(r,"base64")}function Aye(n){let r=aa(n?.aeskey);if(r){if(!/^[0-9a-fA-F]{32}$/.test(r))throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(r,"hex")}let o=eye(n?.media?.aes_key);if(o?.length===16)return o;if(o?.length===32&&/^[0-9a-fA-F]{32}$/.test(o.toString("ascii")))return Buffer.from(o.toString("ascii"),"hex");throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002")}function tye(n,r){let o=Buffer.from(n),i=Buffer.from(r);if(i.length!==16||o.length===0||o.length%16!==0)throw new qA("invalid-image-ciphertext","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u6570\u636E\u65E0\u6548\u3002");try{let e=xfe("aes-128-ecb",i,null);return Buffer.concat([e.update(o),e.final()])}catch(e){throw new qA("image-decryption-failed","\u5FAE\u4FE1\u56FE\u7247\u89E3\u5BC6\u5931\u8D25\u3002",{cause:e})}}function rye(n){let r=aa(n?.encrypt_query_param);if(r)return`${zfe}/download?encrypted_query_param=${encodeURIComponent(r)}`;let o=aa(n?.full_url);if(!o)throw new qA("missing-image-url","\u5FAE\u4FE1\u56FE\u7247\u6CA1\u6709\u53EF\u7528\u7684\u4E0B\u8F7D\u5730\u5740\u3002");let i;try{i=new URL(o)}catch{throw new qA("invalid-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u65E0\u6548\u3002")}if(i.protocol!=="https:"||i.hostname!==j3||i.port&&i.port!=="443"||!i.pathname.startsWith("/c2c/"))throw new qA("untrusted-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u4E0D\u53D7\u4FE1\u4EFB\u3002");return i.username="",i.password="",i.hash="",i.toString()}function I0(n,{fetchImpl:r=fetch}={}){if(typeof r!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.image_item;!e||typeof e!="object"||o.push({name:o.length===0?"image":`image-${o.length+1}`,load:async({signal:a,maxBytes:A})=>{let t=Aye(e),s=rye(e.media),g=await za(s,{fetchImpl:r,signal:a,maxBytes:A+16,allowedHosts:[j3]});return tye(g,t)}})}return o}function l0(n){let r=n.toLowerCase().replace(/\.$/,"");return r==="weixin.qq.com"||r.endsWith(".weixin.qq.com")}function ZI(n){let r;try{r=new URL(n)}catch{throw new qA("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(r.protocol!=="https:"||!l0(r.hostname)||r.port!==""&&r.port!=="443")throw new qA("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return r.username="",r.password="",r.search="",r.hash="",r.pathname.endsWith("/")||(r.pathname+="/"),r.toString()}function aye(n){let r=aa(n);if(!r)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(r)}catch{throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!l0(o.hostname))throw new qA("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function J3(){return{"iLink-App-Id":Wfe,"iLink-App-ClientVersion":String(Zfe)}}function iye(n){let r={...J3(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(jfe(4).readUInt32BE(0)),"utf8").toString("base64")};return aa(n)&&(r.Authorization=`Bearer ${n.trim()}`),r}function HQ(){return{channel_version:qfe,bot_agent:"DeepSeekHarness/0.10.0"}}function x3(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function WI(n,{method:r,baseUrl:o,endpoint:i,body:e,token:a,timeoutMs:A=Xfe,signal:t,authenticated:s=!0}){let g=ZI(o),c=new URL(i,g);if(!l0(c.hostname))throw new qA("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let l=new AbortController,p=!1,B=()=>l.abort(t?.reason);if(t?.aborted)throw x3(t);t?.addEventListener("abort",B,{once:!0});let Q=A>0?setTimeout(()=>{p=!0,l.abort()},A):null;try{let f=await n(c,{method:r,headers:s?iye(a):J3(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new qA("http-error",`\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${f.status}\uFF09\u3002`,{status:f.status});try{return await f.json()}catch(y){throw new qA("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?x3(t):p?new qA("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof qA?f:new qA("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",B)}}function oye(n){if(!n||typeof n!="object"||!$fe.has(n.status))throw new qA("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function q3({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({inboundImages(r){return I0(r,{fetchImpl:n})},async beginLogin({localTokens:r=[],botType:o=Vfe,signal:i}={}){let e=[...new Set(r.map(aa).filter(Boolean))].slice(-10),a=await WI(n,{method:"POST",baseUrl:KQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=aa(a?.qrcode);if(!A)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:aye(a.qrcode_img_content)}},async pollLogin({qrcode:r,baseUrl:o=KQ,verifyCode:i,signal:e}){let a=aa(r);if(!a)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(a)}`;aa(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await WI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:Y3,signal:e,authenticated:!1});return oye(t)},async getUpdates({baseUrl:r,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:a}){try{return await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:HQ()},token:o,timeoutMs:e??Y3,signal:a})}catch(A){if(A instanceof qA&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:r,token:o,toUserId:i,text:e,contextToken:a,runId:A,signal:t}){let s=aa(i),g=aa(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Jfe()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...aa(a)?{context_token:a.trim()}:{},...aa(A)?{run_id:A.trim()}:{}},base_info:HQ()}});if(c?.ret!==void 0&&c.ret!==0)throw new qA("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async notifyStart({baseUrl:r,token:o,signal:i}){let e=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}});if(e?.ret!==void 0&&e.ret!==0)throw new qA("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:r,token:o,signal:i}){return WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}})}})}function DC(n){for(let r of n?.item_list??[]){if(r?.type===1&&typeof r.text_item?.text=="string"){let o=r.text_item.text.trim();if(o)return o}if(r?.type===3&&typeof r.voice_item?.text=="string"){let o=r.voice_item.text.trim();if(o)return o}}return null}function E0(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):aa(n?.client_id)}function V3(n,r=4e3){if(n.length<=r)return[n];let o=[],i=n;for(;i.length>r;){let e=i.lastIndexOf(` `,r);ea===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of r){if(o.has(a.botId)||i.has(a.accountId)||e.has(a.tokenRef))return null;o.add(a.botId),i.add(a.accountId),e.add(a.tokenRef)}return Object.freeze({version:1,accounts:Object.freeze(r)})}var YQ=class{#e;#A=p0;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=Cye(JSON.parse(await gye(this.#e,"utf8")));if(!r)throw new Error("dsh-weixin config contains invalid account data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=p0}return this}list(){return structuredClone(this.#A.accounts)}get(r){let o=this.#A.accounts.find(i=>i.botId===r);return o?structuredClone(o):null}getByAccountId(r){let o=this.#A.accounts.find(i=>i.accountId===r);return o?structuredClone(o):null}async save(r){let o=W3(r);if(!o)throw new Error("Refusing to persist incomplete dsh-weixin account data");return this.#r(i=>{let e=i.find(t=>t.accountId===o.accountId&&t.botId!==o.botId),a=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||a)throw new Error("Duplicate Weixin account identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!z3(r))throw new TypeError("Invalid Weixin bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await Iye(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=p0});this.#t=r.then(()=>{},()=>{}),await r}async#r(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.accounts];o=r(e);let a=Object.freeze({version:1,accounts:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(r){await sye(Eye(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await lye(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await cye(o,this.#e)}};var xQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"weixin",logPrefix:"dsh-weixin"})}};import{mkdir as hye,readFile as dye,rename as uye,unlink as Bye,writeFile as Qye}from"node:fs/promises";import{dirname as fye}from"node:path";var jQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],getUpdatesBuf:""});function yye(n){if(!n||typeof n!="object")return structuredClone(jQ);let r={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(r[o]=i);return{version:1,sessions:r,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[],getUpdatesBuf:typeof n.getUpdatesBuf=="string"?n.getUpdatesBuf:""}}var JQ=class{#e;#A=structuredClone(jQ);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{this.#A=yye(JSON.parse(await dye(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(jQ),await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}getUpdatesBuf(){return this.#A.getUpdatesBuf}async setGetUpdatesBuf(r){typeof r!="string"||r===this.#A.getUpdatesBuf||(this.#A.getUpdatesBuf=r,await this.#r())}snapshot(){return structuredClone(this.#A)}async remove(){try{await Bye(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(jQ)}async#r(){let r=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await hye(fye(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await Qye(i,r,{encoding:"utf8",mode:384}),await uye(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as mye}from"node:crypto";var Z3=new Set(["starting","pending","scanned","needs_verification","connecting"]),qQ=new Set(["connected","expired","failed","cancelled"]),X3=5*6e4;function XI(n){return typeof n=="string"&&n.trim()?n.trim():null}function Sye(){return new DOMException("Provisioning was cancelled","AbortError")}function $3(n,r){let o=XI(n);return o?ZI(o.includes("://")?o:`https://${o}`):ZI(r)}function wC(n){return n?{attemptId:n.id,status:n.state,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},pollIntervalMs:1e3,...n.state==="needs_verification"?{verificationRequired:!0}:{},...n.botId?{botId:n.botId}:{},...n.alreadyConnected?{alreadyConnected:!0}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}function Ua(n,r){return Object.freeze({code:n,message:r})}var OC=class{#e;#A;#t;#r;#g;#n;#E=new Map;#s=new Map;#I=new Map;#a=null;#i=new Map;#o=0;#c=!1;constructor({api:r,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!r||typeof r.beginLogin!="function"||typeof r.pollLogin!="function")throw new TypeError("WeixinController requires a Weixin API client");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WeixinController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WeixinController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A}async initialize(){if(this.#c)return this.status();for(let r of this.#t.list())this.#E.get(r.botId)?.status?.ready!==!0&&await this.#B(r.botId,async()=>{let i=this.#t.get(r.botId);if(!(!i||this.#c))try{let e=await this.#d(i.tokenRef);if(!e){this.#s.set(i.botId,Ua("missing-token","\u767B\u5F55\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u8D26\u53F7\u540E\u91CD\u65B0\u626B\u7801\u3002"));return}await this.#h(i,e),this.#s.delete(i.botId)}catch(e){this.#s.set(i.botId,Ua("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#n.warn?.(`[dsh-weixin] account ${i.botId} failed to initialize:`,e)}finally{this.#f()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("dsh-weixin controller is closed");this.#a&&await this.cancelProvisioning(this.#a);let r={id:mye(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+X3,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:KQ,error:null,botId:null,task:null};this.#I.set(r.id,r),this.#a=r.id,this.#f();try{let o=(await Promise.all(this.#t.list().slice(-10).map(async e=>this.#d(e.tokenRef)))).filter(Boolean),i=await this.#e.beginLogin({localTokens:o,signal:r.controller.signal});return this.#u(r),r.qrcode=i.qrcode,r.verificationUrl=i.qrcodeUrl,r.state="pending",r.expiresAt=Date.now()+X3,this.#f(),r.task=this.#l(r),wC(r)}catch(o){throw r.controller.signal.aborted?(r.state="cancelled",r.error=Ua("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=Ua(o instanceof qA?o.code:"qr-start-failed",o instanceof qA?o.message:"\u65E0\u6CD5\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),this.#a===r.id&&(this.#a=null),this.#f(),o}}registrationStatus(r){return wC(this.#I.get(r))}async submitVerification(r,o){let i=this.#I.get(r);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=XI(o);if(!e||!/^\d{4,8}$/.test(e))throw new TypeError("Verification code must contain 4 to 8 digits");return i.pendingVerifyCode=e,i.state="scanned",i.verifyResolve?.(),i.verifyResolve=null,this.#f(),wC(i)}async cancelProvisioning(r){let o=this.#I.get(r);return o?(qQ.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),qQ.has(o.state)||(o.state="cancelled"),o.error??=Ua("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#a===o.id&&(this.#a=null),this.#f(),wC(o)):null}async reconnectBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Weixin account");return await this.#B(r,async()=>{let i=await this.#d(o.tokenRef);if(!i)throw new Error("The Weixin token is missing");try{await this.#h(o,i),this.#s.delete(r)}catch(e){throw this.#s.set(r,Ua("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Weixin account");return this.#B(r,async()=>{let i=this.#E.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw kt("\u5FAE\u4FE1\u673A\u5668\u4EBA");return i.sendConnectionTest(Yr(`\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08${h0(o.accountId)}\uFF09`))})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Weixin account");return await this.#B(r,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#C(r);try{await this.#A.unset(o.tokenRef),await this.#t.remove(r)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the Weixin account safely.",{cause:e})}try{await this.#g({botId:r,config:o})}catch(e){this.#n.warn?.(`[dsh-weixin] account ${r} state cleanup failed:`,e)}this.#s.delete(r),this.#f()}),this.status()}status(){let r=this.#t.list().map(e=>{let a=this.#E.get(e.botId)?.status??null,A=a?.ready===!0&&a.weixinConnectionState==="connected"&&a.harnessReachable===!0,t=A?"connected":a?.weixinConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||a?.weixinConnectionState==="failed"?"error":"offline",s=this.#s.get(e.botId)??(t==="error"?Ua("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"):null);return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:"\u5FAE\u4FE1\u673A\u5668\u4EBA",accountIdMasked:h0(e.accountId)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"\u5FAE\u4FE1\u6D88\u606F\u957F\u8F6E\u8BE2\u8FD0\u884C\u6B63\u5E38":t==="error"?"\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:a?.lastCheckedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},error:s?structuredClone(s):null}}),o=r.filter(e=>e.connected).length,i=this.#a?this.#I.get(this.#a):null;return{schemaVersion:1,revision:this.#o,state:i&&Z3.has(i.state)?"provisioning":r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o},...i&&Z3.has(i.state)?{provisioning:wC(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#a&&await this.cancelProvisioning(this.#a),await Promise.allSettled([...this.#E.keys()].map(r=>this.#C(r))))}async#l(r){try{for(;!r.controller.signal.aborted&&Date.now(){r.verifyResolve=i,r.controller.signal.aborted&&i()}),r.verifyResolve=null,this.#u(r));let o=await this.#e.pollLogin({qrcode:r.qrcode,baseUrl:r.currentBaseUrl,verifyCode:r.pendingVerifyCode,signal:r.controller.signal});if(this.#u(r),o.status==="wait")r.state="pending";else if(o.status==="scaned")r.pendingVerifyCode=null,r.state="scanned";else if(o.status==="need_verifycode")r.pendingVerifyCode=null,r.state="needs_verification";else if(o.status==="verify_code_blocked"){r.state="failed",r.error=Ua("verification-blocked","\u914D\u5BF9\u7801\u591A\u6B21\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002");break}else if(o.status==="expired"){r.state="expired",r.error=Ua("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002");break}else if(o.status==="scaned_but_redirect")r.currentBaseUrl=$3(o.redirect_host,r.currentBaseUrl),r.state="scanned";else if(o.status==="binded_redirect"){let i=this.#t.list().find(e=>this.#E.get(e.botId)?.status?.ready===!0)??this.#t.list()[0];i?(r.state="connected",r.botId=i.botId,r.alreadyConnected=!0):(r.state="failed",r.error=Ua("already-bound","\u8BE5\u5FAE\u4FE1\u8D26\u53F7\u5DF2\u7ED1\u5B9A\uFF0C\u4F46\u672C\u673A\u6CA1\u6709\u53EF\u6062\u590D\u7684\u51ED\u636E\u3002"));break}else if(o.status==="confirmed"){let i=XI(o.bot_token),e=XI(o.ilink_bot_id),a=XI(o.ilink_user_id);if(!i||!e||!a)throw new qA("incomplete-login","\u5FAE\u4FE1\u6388\u6743\u6210\u529F\uFF0C\u4F46\u8FD4\u56DE\u7684\u8D26\u53F7\u51ED\u636E\u4E0D\u5B8C\u6574\u3002");r.state="connecting",this.#f();let A=$3(o.baseurl,r.currentBaseUrl);r.botId=await this.#p(r,{token:i,accountId:e,ownerUserId:a,baseUrl:A}),r.state="connected",r.error=null;break}this.#f()}!r.controller.signal.aborted&&Date.now()>=r.expiresAt&&!qQ.has(r.state)&&(r.state="expired",r.error=Ua("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"))}catch(o){r.controller.signal.aborted||o?.name==="AbortError"?(r.state="cancelled",r.error=Ua("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=Ua(o instanceof qA?o.code:"activation-failed",o instanceof qA?o.message:"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u4FDD\u5B58\u51ED\u636E\u6216\u542F\u52A8\u6D88\u606F\u8FDE\u63A5\u3002"),this.#n.error?.("[dsh-weixin] provisioning failed:",o))}finally{r.pendingVerifyCode=null,r.verifyResolve?.(),r.verifyResolve=null,this.#a===r.id&&(this.#a=null),this.#f(),this.#y()}}async#p(r,{token:o,accountId:i,ownerUserId:e,baseUrl:a}){let A=C0(i),t=this.#t.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:a,createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()},g=await this.#A.resolve(A.tokenRef).catch(()=>{});return this.#B(A.botId,async()=>{await this.#A.set(A.tokenRef,o);try{return this.#u(r),await this.#t.save(s),this.#u(r),await this.#h(s,o),this.#u(r),this.#s.delete(A.botId),this.#f(),A.botId}catch(c){throw await this.#C(A.botId),t?await this.#t.save(t).catch(()=>{}):this.#t.get(A.botId)&&await this.#t.remove(A.botId).catch(()=>null)&&await this.#g({botId:A.botId,config:s}).catch(p=>{this.#n.warn?.("[dsh-weixin] failed to clean up cancelled bot state:",p)}),await this.#Q(A.tokenRef,g),t&&g?.value&&await this.#h(t,g.value).catch(()=>{}),c}})}async#h(r,o){await this.#C(r.botId);let i=await this.#r({botId:r.botId,config:r,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Weixin runtime");try{await i.start(),this.#E.set(r.botId,i)}catch(e){throw await i.stop().catch(()=>{}),e}}async#C(r){let o=this.#E.get(r);this.#E.delete(r),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-weixin] account ${r} failed to stop cleanly:`,i)})}async#d(r){let o=await this.#A.resolve(r).catch(()=>{});return XI(o?.value)}async#Q(r,o){try{o?.value?await this.#A.set(r,o.value):await this.#A.unset(r)}catch(i){this.#n.error?.(`[dsh-weixin] failed to restore credential ${r}:`,i)}}#u(r){if(r.controller.signal.aborted||this.#a!==r.id)throw Sye()}#B(r,o){let a=(this.#i.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(r)===a&&this.#i.delete(r)});return this.#i.set(r,a),a}#y(){for(let[r,o]of this.#I)r!==this.#a&&qQ.has(o.state)&&this.#I.size>16&&this.#I.delete(r)}#f(){this.#o+=1}};var VQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",Dye=["\u5FAE\u4FE1\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` -`);function wye(n){return`p2p:${n}`}function ia(n){return typeof n=="string"&&n.trim()?n.trim():null}function d0(n){return Array.isArray(n?.item_list)&&n.item_list.some(r=>r?.image_item&&typeof r.image_item=="object")}function Oye(n,r){return r.questions[r.index]&&ia(n?.from_user_id)===r.actor&&!d0(n)&&ia(DC(n))}function u0(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var zQ=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i;#o=new Map;#c=new Map;#l=new Map;#p=new Set;#h=new Set;#C;constructor({api:r,baseUrl:o,token:i,ownerUserId:e,harness:a,state:A,status:t=u0(),logger:s=console,replyTimeoutMs:g=6e5,maxMessageChars:c=4e3,signal:l}){if(!r||typeof r.sendText!="function")throw new TypeError("Weixin API is required");if(!o||!i||!e)throw new TypeError("Weixin account credentials are required");if(!a||!A)throw new TypeError("Harness client and state store are required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#a=c,this.#i=l,this.#C=new Ca({label:"weixin",logger:s})}get status(){return structuredClone(this.#E)}accept(r){if(this.#i?.aborted||r?.message_type===2)return Promise.resolve();let o=E0(r),i=ia(r?.from_user_id);if(!o||!i||this.#n.hasSeen(o)||this.#p.has(o))return Promise.resolve();this.#p.add(o),i===this.#r&&Va(this.#n,{toUserId:i});let e=wye(i),a=ia(r?.context_token)??void 0,A=ia(r?.run_id)??void 0,t=this.#c.get(e),s=this.#C.claimReply({key:e,actor:i,messageId:o,text:d0(r)?"":DC(r),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#c.has(e),send:g=>this.#O(i,g,a,A)});if(s){let g;return g=s.process(async()=>this.#n.hasSeen(o)?!1:(await this.#n.markSeen(o),this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#p.delete(o),this.#h.delete(g)}),this.#h.add(g),g}if(t?.submitting||t?.claimedReplyMessageId)return this.#d(r,o,e);if(t){Oye(r,t)&&(t.claimedReplyMessageId=o);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(r,o,e,t)).catch(l=>this.#S(r,o,l)).finally(()=>{this.#p.delete(o),t.claimedReplyMessageId===o&&(t.claimedReplyMessageId=null),t.queue===c&&(t.queue=null)});return t.queue=c,c}return this.#d(r,o,e)}#d(r,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1}={}){let t=(this.#o.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,i,{alreadyRecorded:a})).finally(()=>{e&&this.#p.delete(o),this.#o.get(i)===t&&this.#o.delete(i)});return this.#o.set(i,t),t}async waitForIdle(){await Promise.allSettled([...this.#o.values(),...[...this.#c.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#h])}async#Q(r,o,{alreadyRecorded:i=!1}={}){this.#i?.throwIfAborted();let e=E0(r),a=ia(r?.from_user_id);if(!e||!a)return;if(!i){if(this.#n.hasSeen(e))return;this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString()}if(a!==this.#r){this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString();return}let A=typeof r.context_token=="string"?r.context_token:void 0,t=typeof r.run_id=="string"?r.run_id:void 0,s=DC(r)??"";try{let g=typeof this.#e.inboundImages=="function"?this.#e.inboundImages(r):I0(r),c={content:s,images:g},l=Mr(c);if(!s&&!l){await this.#O(a,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002",A,t),await this.#n.markSeen(e);return}let p=s.trim().toLowerCase();if(!l&&p==="/help"){await this.#O(a,Dye,A,t),await this.#n.markSeen(e);return}if(!l&&p==="/status"){await this.#g.ensureRunning({signal:this.#i}),await this.#O(a,"\u5FAE\u4FE1\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002",A,t),await this.#n.markSeen(e);return}if(!l&&p==="/new"){await this.#n.clearSession(o),await this.#O(a,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002",A,t),await this.#n.markSeen(e);return}let B=l?null:await ti(s,this.#g,o);if(B){for(let m of B.messages??[B.message])await this.#O(a,m,A,t);await this.#n.markSeen(e);return}let Q=l?null:await Ai(s,this.#g,this.#n,o,{signal:this.#i});if(Q){await this.#O(a,Q.message,A,t),await this.#n.markSeen(e);return}let f=l?await Wa(c,{signal:this.#i}):void 0,y;try{({answer:y}=await ha({harness:this.#g,state:this.#n,key:o,...l?{content:f}:{text:s},createOptions:{signal:this.#i},existsOptions:{signal:this.#i},askOptions:{timeoutMs:this.#I,signal:this.#i,onInteraction:m=>this.#B(m,{key:o,actor:a,contextToken:A,runId:t}),onInteractionResolved:m=>this.#y(m)}}))}finally{await Promise.allSettled([this.#N(o),this.#C.closeRoute(o)])}await this.#O(a,y,A,t),await this.#n.markSeen(e),this.#E.messagesReplied+=1,this.#E.lastReplyAt=new Date().toISOString(),this.#E.lastError=null}catch(g){if(this.#i?.aborted)return;this.#E.lastError=g?.message??String(g),this.#s.error?.("[dsh-weixin] failed to process an inbound message:",g);try{await this.#O(a,Za(g)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",A,t),await this.#n.markSeen(e)}catch(c){this.#s.error?.("[dsh-weixin] failed to send the safe error reply:",c)}}}async#u(r,o,i,e){this.#i?.throwIfAborted();let a=this.#c.get(i),A=e.claimedReplyMessageId===o;if(!a||a!==e||a.submitting)return A&&(!a||a!==e)?this.#D(r,o):this.#d(r,o,i,{releaseMessageId:!1});if(this.#n.hasSeen(o))return;await this.#n.markSeen(o),this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString();let t=ia(DC(r)),s=ia(r?.context_token)??void 0,g=ia(r?.run_id)??void 0;if(!t||d0(r)){await this.#O(e.actor,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002",s,g);return}let c=this.#c.get(i);if(!c||c!==e||c.submitting){if(A&&(!c||c!==e)){await this.#O(e.actor,VQ,s,g);return}return this.#d(r,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.contextToken=s,c.runId=g,c.needsPresentation){try{await this.#f(c)}catch{this.#E.lastError="\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#s.error?.("[dsh-weixin] failed to retry an interaction question"),c.interaction.reconnect?.();return}let p=this.#c.get(i);if(!p||p!==e||p.submitting){if(A&&(!p||p!==e)){await this.#O(e.actor,VQ,s,g).catch(()=>{});return}return this.#d(r,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,t)),c.index+=1,c.index{});return}if(this.#c.get(i)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#E.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#s.error?.("[dsh-weixin] failed to answer a Harness interaction"),await this.#O(c.actor,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002",c.contextToken,c.runId).catch(()=>{})}}}async#B(r,{key:o,actor:i,contextToken:e,runId:a}){if(r?.kind==="approval")return this.#C.handleRequested(r,{key:o,actor:i,send:c=>this.#O(i,c,e,a)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r?.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#s.warn?.("[dsh-weixin] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.respond({ok:!1,error:{code:"cancelled",message:"Weixin safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#O(i,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002",e,a).catch(()=>{});return}let s=this.#c.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#f(s);return}if(this.#l.has(t))return;if(s){await r.respond({ok:!1,error:{code:"cancelled",message:"Weixin is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,questions:A,answers:[],index:0,contextToken:e,runId:a,queue:null,claimedReplyMessageId:null,presentationPromise:null,submitting:!1,needsPresentation:!0};this.#c.set(o,g),this.#l.set(t,o),await this.#f(g)}async#y(r){if(r?.kind==="approval"){await this.#C.handleResolved(r);return}let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#l.get(o);i&&this.#w(i,o)}#f(r){if(!r.needsPresentation)return Promise.resolve();if(r.presentationPromise)return r.presentationPromise;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=this.#O(r.actor,$a(o,r.index,r.questions.length),r.contextToken,r.runId).then(()=>{r.needsPresentation=!1}).finally(()=>{r.presentationPromise===i&&(r.presentationPromise=null)});return r.presentationPromise=i,i}async#D(r,o){this.#n.hasSeen(o)||(await this.#n.markSeen(o),this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString(),await this.#O(ia(r?.from_user_id),VQ,ia(r?.context_token)??void 0,ia(r?.run_id)??void 0).catch(()=>{}))}#m(r,o){let i=this.#c.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#c.delete(r),this.#l.delete(i.interactionId),i)}#w(r,o){return this.#m(r,o)!==null}async#N(r){let o=this.#m(r);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Weixin interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#s.warn?.("[dsh-weixin] failed to cancel a pending Harness interaction")}}async#S(r,o,i){this.#i?.aborted||(this.#E.lastError=i?.message??String(i),this.#s.error?.("[dsh-weixin] failed to process an interaction reply:",i),this.#n.hasSeen(o)||await this.#n.markSeen(o).catch(()=>{}),await this.#O(ia(r?.from_user_id),"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",ia(r?.context_token)??void 0,ia(r?.run_id)??void 0).catch(()=>{}))}async#O(r,o,i,e){for(let a of V3(o,this.#a))await this.#e.sendText({baseUrl:this.#A,token:this.#t,toUserId:r,text:a,contextToken:i,runId:e})}};var Mye=Object.freeze([250,1e3,3e3]);function bye(n){if(n===void 0)return[...Mye];if(!Array.isArray(n))throw new TypeError("startRetryDelaysMs must be an array");return n.map(r=>{if(!Number.isFinite(r)||r<0)throw new TypeError("startRetryDelaysMs must contain non-negative delays");return r})}function _ye(n){return n instanceof qA?n.code==="network-error"||n.code==="timeout"?!0:n.code==="http-error"&&(n.status===408||n.status===425||n.status===429||n.status>=500):!1}function ej(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let a=setTimeout(()=>{r?.removeEventListener("abort",A),o()},n),A=()=>{clearTimeout(a),r?.removeEventListener("abort",A),i(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",A,{once:!0})})}function Nye(){return{startedAt:null,ready:!1,weixinConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastError:null,...u0()}}var MC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=Nye();#i=null;#o=null;#c=null;#l=null;constructor({api:r,config:o,token:i,harness:e,state:a,logger:A=console,replyTimeoutMs:t=6e5,maxMessageChars:s=4e3,startRetryDelaysMs:g}){if(!r||!o||!i||!e||!a)throw new TypeError("WeixinRuntime requires API, account, token, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=bye(g)}get status(){return structuredClone(this.#a)}async start(){return this.#a.ready&&this.#c?this.status:this.#l?this.#l:(this.#l=this.#p().finally(()=>{this.#l=null}),this.#l)}async#p(){await this.stop(),this.#a.startedAt=new Date().toISOString(),this.#a.weixinConnectionState="connecting",this.#a.lastError=null;try{await this.#r.ensureRunning(),this.#a.harnessReachable=!0,await this.#h(),this.#o=new AbortController;let r=this.#o.signal;return this.#i=new zQ({api:this.#e,baseUrl:this.#A.baseUrl,token:this.#t,ownerUserId:this.#A.ownerUserId,harness:this.#r,state:this.#g,status:this.#a,logger:this.#n,replyTimeoutMs:this.#E,maxMessageChars:this.#s,signal:r}),this.#a.ready=!0,this.#a.weixinConnectionState="connected",this.#a.lastCheckedAt=Date.now(),this.#c=this.#C(r).catch(o=>{r.aborted||(this.#a.ready=!1,this.#a.weixinConnectionState="failed",this.#a.lastError=o?.message??String(o),this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} monitor stopped:`,o))}),this.status}catch(r){throw this.#o?.abort(),this.#o=null,this.#i=null,this.#a.ready=!1,this.#a.weixinConnectionState="failed",this.#a.lastError=r?.message??String(r),r}}async#h(){for(let r=0;;r+=1)try{return await this.#e.notifyStart({baseUrl:this.#A.baseUrl,token:this.#t})}catch(o){let i=this.#I[r];if(i===void 0||!_ye(o))throw o;this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} start request failed; retrying in ${i}ms:`,o),await ej(i)}}async#C(r){let o=0;for(;!r.aborted;)try{let i=await this.#e.getUpdates({baseUrl:this.#A.baseUrl,token:this.#t,getUpdatesBuf:this.#g.getUpdatesBuf(),signal:r});if(r.aborted)return;if(i?.ret!==void 0&&i.ret!==0||i?.errcode!==void 0&&i.errcode!==0){let a=i.errcode??i.ret;throw new qA(a===-14?"stale-token":"updates-rejected",a===-14?"\u5FAE\u4FE1\u767B\u5F55\u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u8D26\u53F7\u540E\u91CD\u65B0\u626B\u7801\u3002":"\u5FAE\u4FE1\u6D88\u606F\u540C\u6B65\u8BF7\u6C42\u88AB\u62D2\u7EDD\u3002")}o=0,this.#a.ready=!0,this.#a.weixinConnectionState="connected",this.#a.lastCheckedAt=Date.now(),this.#a.lastError=null;for(let a of i?.msgs??[])this.#i.accept(a).catch(A=>{r.aborted||this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} message handling failed:`,A)});typeof i?.get_updates_buf=="string"&&i.get_updates_buf&&await this.#g.setGetUpdatesBuf(i.get_updates_buf)}catch(i){if(r.aborted)return;if(o+=1,this.#a.lastError=i?.message??String(i),this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} poll failed (${o}/3):`,i),i instanceof qA&&i.code==="stale-token"||o>=3)throw i;await ej(Math.min(2e3*2**(o-1),1e4),r)}}async stop(){let r=this.#c,o=this.#i,i=!!(this.#o||r||this.#a.ready);if(this.#o?.abort(),this.#o=null,this.#c=null,await r?.catch(()=>{}),await o?.waitForIdle(),this.#i=null,i)try{await this.#e.notifyStop({baseUrl:this.#A.baseUrl,token:this.#t,signal:AbortSignal.timeout(1e4)})}catch(e){this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} stop notification failed:`,e)}return this.#a.ready=!1,this.#a.weixinConnectionState="idle",this.status}async sendConnectionTest(r){let o=OE(this.#g),i=typeof o?.toUserId=="string"&&o.toUserId.trim()?o.toUserId.trim():typeof this.#A.ownerUserId=="string"&&this.#A.ownerUserId.trim()?this.#A.ownerUserId.trim():null;if(!i)throw kt("\u5FAE\u4FE1\u673A\u5668\u4EBA");if(!this.#a.ready||!this.#o)throw new Error("Weixin runtime is not connected");return await this.#e.sendText({baseUrl:this.#A.baseUrl,token:this.#t,toUserId:i,text:r,signal:this.#o.signal}),{sent:!0}}};var Aj=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function Tye(n){if(!Array.isArray(n)||n.length===0)return[...Aj];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...Aj]}var WQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=Tye(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-weixin requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function Pye(n){let r=rc(n.dshHome??process.env.DSH_HOME??bC(kye(),".dsh")),o=rc(n.dataDir??bC(r,"integrations","dsh-weixin"));return{root:o,config:rc(n.configPath??bC(o,"config.json")),accounts:rc(n.accountsDir??bC(o,"accounts")),workspaces:rc(n.workspacesPath??bC(o,"workspaces.json"))}}async function Q0(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-weixin requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-weixin requires ctx.webServer");let i=o.ConfigStore??YQ,e=o.StateStore??JQ,a=o.HarnessClient??xQ,A=o.Controller??OC,t=o.Runtime??MC,s=o.api??q3(),g=o.createConnectionSupervisor??B0,c=typeof n.logger=="function"?n.logger("dsh-weixin"):n.logger??console,l=Pye(r),p=await new i(l.config).load(),B=rc(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(F=>F.botId)),await Promise.all(y.map(F=>f.ensure(F.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=new Map,k=F=>rc(l.accounts,F,"state.json"),G=async F=>{let T=R.get(F);return T||(T=await new e(k(F)).load(),R.set(F,T)),T},K=zr(n,o.commandExecutor),x=new a({baseUrl:vye(n.webServer,r.harnessBaseUrl),workspace:B,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...K?{commandExecutor:K}:{}}),H=new A({api:s,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:F,config:T,token:V})=>{let U=await G(F);await f.ensure(F);let b=qr(x,{botId:F,workspaces:f,state:U});return new t({api:s,config:T,token:V,harness:b.harness,state:b.state,replyTimeoutMs:r.replyTimeoutMs??6e5,maxMessageChars:r.maxMessageChars??4e3,logger:{error:(...L)=>c.error?.(`[${F}]`,...L),warn:(...L)=>c.warn?.(`[${F}]`,...L),info:(...L)=>c.info?.(`[${F}]`,...L),debug:(...L)=>c.debug?.(`[${F}]`,...L)}})},deleteState:async({botId:F})=>{let T=R.get(F);if(R.delete(F),T&&typeof T.remove=="function")await T.remove();else try{await Rye(k(F))}catch(V){if(V?.code!=="ENOENT")throw V}}}),q=Vr(H,{workspaces:f,stateFor:G}),j=g({controller:q,harness:x,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:q,ready:j.ready,async close(){await j.close(),await q.close(),x.stopManagedProcess()}}}import Gye from"qrcode";var tj="/weixin",Tr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",submitVerification:"provision.verify",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),rj=Object.freeze(Object.values(Tr));function aj(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function $I(n,r){return aj(n)&&Object.keys(n).every(o=>r.includes(o))}function ZQ(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function Fye(n,r){return aj(r)?n===Tr.status?$I(r,[])?null:"connection.status does not accept fields.":n===Tr.beginProvisioning?$I(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Tr.pollProvisioning,Tr.cancelProvisioning].includes(n)?$I(r,["attemptId"])&&ZQ(r.attemptId)?null:`${n} requires an attemptId.`:n===Tr.submitVerification?$I(r,["attemptId","verifyCode"])&&ZQ(r.attemptId)&&typeof r.verifyCode=="string"&&/^\d{4,8}$/.test(r.verifyCode)?null:"provision.verify requires an attemptId and a 4-to-8-digit code.":n===Tr.reconnectBot?$I(r,["botId","sendTest"])&&ZQ(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Tr.deleteBot?$I(r,["botId","confirm"])&&ZQ(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Tr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Weixin endpoint.":"Payload must be an object."}function XQ(n){return{ok:!1,error:{code:"bad-request",message:n}}}function _C(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function Lye(){return{ok:!1,error:{code:"weixin-operation-failed",message:"\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}async function Uye(n){return Gye.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function ef(n,r){return!n||!n.verificationUrl?n:{...n,qrCodeDataUrl:await r(n.verificationUrl)}}async function $Q(n,r){let o=structuredClone(n);return o.provisioning&&(o.provisioning=await ef(o.provisioning,r)),o}function Hye(n){if(!n||typeof n.status!="function"||typeof n.startProvisioning!="function"||typeof n.registrationStatus!="function"||typeof n.submitVerification!="function"||typeof n.cancelProvisioning!="function"||typeof n.reconnectBot!="function"||typeof n.deleteBot!="function")throw new TypeError("A complete Weixin controller is required")}function ij(n,{encodeQr:r=Uye}={}){Hye(n);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(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return _C();if(!rj.includes(e))return XQ("Unknown Weixin endpoint.");let t=Fye(e,a);if(t)return XQ(t);try{let s;if(e===Tr.status)s=await $Q(await n.status(),i);else if(e===Tr.beginProvisioning){let g=await n.startProvisioning();if(A?.aborted)return await n.cancelProvisioning(g.attemptId),_C();s=await ef(g,i)}else if(e===Tr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return XQ("The provisioning attempt no longer exists.");s=await ef(g,i)}else if(e===Tr.submitVerification)s=await ef(await n.submitVerification(a.attemptId,a.verifyCode),i);else if(e===Tr.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return XQ("The provisioning attempt no longer exists.")}else if(e===Tr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return _C();let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await $Q({...g,...c?{testMessage:c}:{}},i)}else if(e===Tr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await $Q(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await $Q(await n.deleteBot(a.botId),i);return A?.aborted?_C():{ok:!0,value:s}}catch(s){let g=Xr(s);return A?.aborted?_C():g?{ok:!1,error:g}:Lye()}}}function Af(n,r,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(tj,ij(r,o),{authority:Wr(i)})}async function oj(n,r={}){if(r?.controller)return Af(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await Q0(n,r,r.internals),i=Af(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-weixin: close account connections"),i}import{rm as FLe,unlink as LLe}from"node:fs/promises";import{homedir as ULe}from"node:os";import{join as DE,resolve as Wn}from"node:path";import{createHash as Kye}from"node:crypto";import{mkdir as Yye,readFile as xye,rename as jye,unlink as Jye,writeFile as qye}from"node:fs/promises";import{dirname as Vye}from"node:path";var f0=Object.freeze({version:2,bots:Object.freeze([])}),nj=/^whatsapp_[a-f0-9]{24}$/,zye=/^[a-f0-9-]{36}$/;function el(n){return typeof n=="string"&&n.trim()?n.trim():null}function tf(n){let r=el(n)?.toLowerCase();return/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(r??"")?r:null}function y0(n){let r=tf(n);if(!r)throw new TypeError("A valid WhatsApp account JID is required");return`whatsapp_${Kye("sha256").update(r).digest("hex").slice(0,24)}`}function m0(n){let r=tf(n)?.split("@")[0]??"";return r?r.length<=7?`${r.slice(0,2)}\u2022\u2022\u2022${r.slice(-2)}`:`${r.slice(0,4)}\u2022\u2022\u2022\u2022${r.slice(-4)}`:"WhatsApp\u8D26\u53F7"}var rf=class{#e;#A=f0;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=this.#g(JSON.parse(await xye(this.#e,"utf8")));if(!r)throw new Error("dsh-im WhatsApp config contains invalid account data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=f0}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByAccountJid(r){let o=tf(r),i=this.#A.bots.find(e=>e.accountJid===o);return i?structuredClone(i):null}async save(r){let o=this.#r(r);if(!o)throw new Error("Refusing to persist incomplete WhatsApp account data");return this.#n(i=>{let e=i.find(t=>t.accountJid===o.accountJid&&t.botId!==o.botId),a=i.find(t=>t.authDirectory===o.authDirectory&&t.botId!==o.botId);if(e||a)throw new Error("Duplicate WhatsApp account identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!nj.test(r))throw new TypeError("Invalid WhatsApp bot id");return this.#n(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await Jye(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=f0});this.#t=r.then(()=>{},()=>{}),await r}#r(r){if(!r||typeof r!="object")return null;let o=tf(r.accountJid),i=el(r.botId),e=el(r.authDirectory),a=el(r.name);return!o||!i||!e||!a||!nj.test(i)||!zye.test(e)||y0(o)!==i?null:Object.freeze({botId:i,accountJid:o,authDirectory:e,name:a,createdAt:el(r.createdAt)??new Date().toISOString(),connectedAt:el(r.connectedAt)})}#g(r){if(!r||r.version!==2||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.accountJid)||a.has(A.authDirectory))return null;i.add(A.botId),e.add(A.accountJid),a.add(A.authDirectory)}return Object.freeze({version:2,bots:Object.freeze(o)})}async#n(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#E(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#E(r){await Yye(Vye(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await qye(o,`${JSON.stringify(r,null,2)} +`);function wye(n){return`p2p:${n}`}function ia(n){return typeof n=="string"&&n.trim()?n.trim():null}function d0(n){return Array.isArray(n?.item_list)&&n.item_list.some(r=>r?.image_item&&typeof r.image_item=="object")}function Oye(n,r){return r.questions[r.index]&&ia(n?.from_user_id)===r.actor&&!d0(n)&&ia(DC(n))}function u0(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var zQ=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i;#o=new Map;#c=new Map;#l=new Map;#p=new Set;#h=new Set;#C;constructor({api:r,baseUrl:o,token:i,ownerUserId:e,harness:a,state:A,status:t=u0(),logger:s=console,replyTimeoutMs:g=6e5,maxMessageChars:c=4e3,signal:l}){if(!r||typeof r.sendText!="function")throw new TypeError("Weixin API is required");if(!o||!i||!e)throw new TypeError("Weixin account credentials are required");if(!a||!A)throw new TypeError("Harness client and state store are required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#a=c,this.#i=l,this.#C=new Ca({label:"weixin",logger:s})}get status(){return structuredClone(this.#E)}accept(r){if(this.#i?.aborted||r?.message_type===2)return Promise.resolve();let o=E0(r),i=ia(r?.from_user_id);if(!o||!i||this.#n.hasSeen(o)||this.#p.has(o))return Promise.resolve();this.#p.add(o),i===this.#r&&Va(this.#n,{toUserId:i});let e=wye(i),a=ia(r?.context_token)??void 0,A=ia(r?.run_id)??void 0,t=this.#c.get(e),s=this.#C.claimReply({key:e,actor:i,messageId:o,text:d0(r)?"":DC(r),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#c.has(e),send:g=>this.#O(i,g,a,A)});if(s){let g;return g=s.process(async()=>this.#n.hasSeen(o)?!1:(await this.#n.markSeen(o),this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#p.delete(o),this.#h.delete(g)}),this.#h.add(g),g}if(t?.submitting||t?.claimedReplyMessageId)return this.#d(r,o,e);if(t){Oye(r,t)&&(t.claimedReplyMessageId=o);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(r,o,e,t)).catch(l=>this.#S(r,o,l)).finally(()=>{this.#p.delete(o),t.claimedReplyMessageId===o&&(t.claimedReplyMessageId=null),t.queue===c&&(t.queue=null)});return t.queue=c,c}return this.#d(r,o,e)}#d(r,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1}={}){let t=(this.#o.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,i,{alreadyRecorded:a})).finally(()=>{e&&this.#p.delete(o),this.#o.get(i)===t&&this.#o.delete(i)});return this.#o.set(i,t),t}async waitForIdle(){await Promise.allSettled([...this.#o.values(),...[...this.#c.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#h])}async#Q(r,o,{alreadyRecorded:i=!1}={}){this.#i?.throwIfAborted();let e=E0(r),a=ia(r?.from_user_id);if(!e||!a)return;if(!i){if(this.#n.hasSeen(e))return;this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString()}if(a!==this.#r){this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString();return}let A=typeof r.context_token=="string"?r.context_token:void 0,t=typeof r.run_id=="string"?r.run_id:void 0,s=DC(r)??"";try{let g=typeof this.#e.inboundImages=="function"?this.#e.inboundImages(r):I0(r),c={content:s,images:g},l=Mr(c);if(!s&&!l){await this.#O(a,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002",A,t),await this.#n.markSeen(e);return}let p=s.trim().toLowerCase();if(!l&&p==="/help"){await this.#O(a,Dye,A,t),await this.#n.markSeen(e);return}if(!l&&p==="/status"){await this.#g.ensureRunning({signal:this.#i}),await this.#O(a,"\u5FAE\u4FE1\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002",A,t),await this.#n.markSeen(e);return}if(!l&&p==="/new"){await this.#n.clearSession(o),await this.#O(a,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002",A,t),await this.#n.markSeen(e);return}let B=l?null:await ti(s,this.#g,o);if(B){for(let m of B.messages??[B.message])await this.#O(a,m,A,t);await this.#n.markSeen(e);return}let Q=l?null:await Ai(s,this.#g,this.#n,o,{signal:this.#i});if(Q){await this.#O(a,Q.message,A,t),await this.#n.markSeen(e);return}let f=l?await Wa(c,{signal:this.#i}):void 0,y;try{({answer:y}=await ha({harness:this.#g,state:this.#n,key:o,...l?{content:f}:{text:s},createOptions:{signal:this.#i},existsOptions:{signal:this.#i},askOptions:{timeoutMs:this.#I,signal:this.#i,onInteraction:m=>this.#B(m,{key:o,actor:a,contextToken:A,runId:t}),onInteractionResolved:m=>this.#y(m)}}))}finally{await Promise.allSettled([this.#N(o),this.#C.closeRoute(o)])}await this.#O(a,y,A,t),await this.#n.markSeen(e),this.#E.messagesReplied+=1,this.#E.lastReplyAt=new Date().toISOString(),this.#E.lastError=null}catch(g){if(this.#i?.aborted)return;this.#E.lastError=g?.message??String(g),this.#s.error?.("[dsh-weixin] failed to process an inbound message:",g);try{await this.#O(a,Za(g)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",A,t),await this.#n.markSeen(e)}catch(c){this.#s.error?.("[dsh-weixin] failed to send the safe error reply:",c)}}}async#u(r,o,i,e){this.#i?.throwIfAborted();let a=this.#c.get(i),A=e.claimedReplyMessageId===o;if(!a||a!==e||a.submitting)return A&&(!a||a!==e)?this.#D(r,o):this.#d(r,o,i,{releaseMessageId:!1});if(this.#n.hasSeen(o))return;await this.#n.markSeen(o),this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString();let t=ia(DC(r)),s=ia(r?.context_token)??void 0,g=ia(r?.run_id)??void 0;if(!t||d0(r)){await this.#O(e.actor,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002",s,g);return}let c=this.#c.get(i);if(!c||c!==e||c.submitting){if(A&&(!c||c!==e)){await this.#O(e.actor,VQ,s,g);return}return this.#d(r,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.contextToken=s,c.runId=g,c.needsPresentation){try{await this.#f(c)}catch{this.#E.lastError="\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#s.error?.("[dsh-weixin] failed to retry an interaction question"),c.interaction.reconnect?.();return}let p=this.#c.get(i);if(!p||p!==e||p.submitting){if(A&&(!p||p!==e)){await this.#O(e.actor,VQ,s,g).catch(()=>{});return}return this.#d(r,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,t)),c.index+=1,c.index{});return}if(this.#c.get(i)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#E.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#s.error?.("[dsh-weixin] failed to answer a Harness interaction"),await this.#O(c.actor,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002",c.contextToken,c.runId).catch(()=>{})}}}async#B(r,{key:o,actor:i,contextToken:e,runId:a}){if(r?.kind==="approval")return this.#C.handleRequested(r,{key:o,actor:i,send:c=>this.#O(i,c,e,a)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r?.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#s.warn?.("[dsh-weixin] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.respond({ok:!1,error:{code:"cancelled",message:"Weixin safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#O(i,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002",e,a).catch(()=>{});return}let s=this.#c.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#f(s);return}if(this.#l.has(t))return;if(s){await r.respond({ok:!1,error:{code:"cancelled",message:"Weixin is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,questions:A,answers:[],index:0,contextToken:e,runId:a,queue:null,claimedReplyMessageId:null,presentationPromise:null,submitting:!1,needsPresentation:!0};this.#c.set(o,g),this.#l.set(t,o),await this.#f(g)}async#y(r){if(r?.kind==="approval"){await this.#C.handleResolved(r);return}let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#l.get(o);i&&this.#w(i,o)}#f(r){if(!r.needsPresentation)return Promise.resolve();if(r.presentationPromise)return r.presentationPromise;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=this.#O(r.actor,$a(o,r.index,r.questions.length),r.contextToken,r.runId).then(()=>{r.needsPresentation=!1}).finally(()=>{r.presentationPromise===i&&(r.presentationPromise=null)});return r.presentationPromise=i,i}async#D(r,o){this.#n.hasSeen(o)||(await this.#n.markSeen(o),this.#E.messagesReceived+=1,this.#E.lastMessageAt=new Date().toISOString(),await this.#O(ia(r?.from_user_id),VQ,ia(r?.context_token)??void 0,ia(r?.run_id)??void 0).catch(()=>{}))}#m(r,o){let i=this.#c.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#c.delete(r),this.#l.delete(i.interactionId),i)}#w(r,o){return this.#m(r,o)!==null}async#N(r){let o=this.#m(r);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Weixin interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#s.warn?.("[dsh-weixin] failed to cancel a pending Harness interaction")}}async#S(r,o,i){this.#i?.aborted||(this.#E.lastError=i?.message??String(i),this.#s.error?.("[dsh-weixin] failed to process an interaction reply:",i),this.#n.hasSeen(o)||await this.#n.markSeen(o).catch(()=>{}),await this.#O(ia(r?.from_user_id),"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",ia(r?.context_token)??void 0,ia(r?.run_id)??void 0).catch(()=>{}))}async#O(r,o,i,e){for(let a of V3(o,this.#a))await this.#e.sendText({baseUrl:this.#A,token:this.#t,toUserId:r,text:a,contextToken:i,runId:e})}};var Mye=Object.freeze([250,1e3,3e3]);function bye(n){if(n===void 0)return[...Mye];if(!Array.isArray(n))throw new TypeError("startRetryDelaysMs must be an array");return n.map(r=>{if(!Number.isFinite(r)||r<0)throw new TypeError("startRetryDelaysMs must contain non-negative delays");return r})}function _ye(n){return n instanceof qA?n.code==="network-error"||n.code==="timeout"?!0:n.code==="http-error"&&(n.status===408||n.status===425||n.status===429||n.status>=500):!1}function ej(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let a=setTimeout(()=>{r?.removeEventListener("abort",A),o()},n),A=()=>{clearTimeout(a),r?.removeEventListener("abort",A),i(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",A,{once:!0})})}function Nye(){return{startedAt:null,ready:!1,weixinConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastError:null,...u0()}}var MC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=Nye();#i=null;#o=null;#c=null;#l=null;constructor({api:r,config:o,token:i,harness:e,state:a,logger:A=console,replyTimeoutMs:t=6e5,maxMessageChars:s=4e3,startRetryDelaysMs:g}){if(!r||!o||!i||!e||!a)throw new TypeError("WeixinRuntime requires API, account, token, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=bye(g)}get status(){return structuredClone(this.#a)}async start(){return this.#a.ready&&this.#c?this.status:this.#l?this.#l:(this.#l=this.#p().finally(()=>{this.#l=null}),this.#l)}async#p(){await this.stop(),this.#a.startedAt=new Date().toISOString(),this.#a.weixinConnectionState="connecting",this.#a.lastError=null;try{await this.#r.ensureRunning(),this.#a.harnessReachable=!0,await this.#h(),this.#o=new AbortController;let r=this.#o.signal;return this.#i=new zQ({api:this.#e,baseUrl:this.#A.baseUrl,token:this.#t,ownerUserId:this.#A.ownerUserId,harness:this.#r,state:this.#g,status:this.#a,logger:this.#n,replyTimeoutMs:this.#E,maxMessageChars:this.#s,signal:r}),this.#a.ready=!0,this.#a.weixinConnectionState="connected",this.#a.lastCheckedAt=Date.now(),this.#c=this.#C(r).catch(o=>{r.aborted||(this.#a.ready=!1,this.#a.weixinConnectionState="failed",this.#a.lastError=o?.message??String(o),this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} monitor stopped:`,o))}),this.status}catch(r){throw this.#o?.abort(),this.#o=null,this.#i=null,this.#a.ready=!1,this.#a.weixinConnectionState="failed",this.#a.lastError=r?.message??String(r),r}}async#h(){for(let r=0;;r+=1)try{return await this.#e.notifyStart({baseUrl:this.#A.baseUrl,token:this.#t})}catch(o){let i=this.#I[r];if(i===void 0||!_ye(o))throw o;this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} start request failed; retrying in ${i}ms:`,o),await ej(i)}}async#C(r){let o=0;for(;!r.aborted;)try{let i=await this.#e.getUpdates({baseUrl:this.#A.baseUrl,token:this.#t,getUpdatesBuf:this.#g.getUpdatesBuf(),signal:r});if(r.aborted)return;if(i?.ret!==void 0&&i.ret!==0||i?.errcode!==void 0&&i.errcode!==0){let a=i.errcode??i.ret;throw new qA(a===-14?"stale-token":"updates-rejected",a===-14?"\u5FAE\u4FE1\u767B\u5F55\u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u8D26\u53F7\u540E\u91CD\u65B0\u626B\u7801\u3002":"\u5FAE\u4FE1\u6D88\u606F\u540C\u6B65\u8BF7\u6C42\u88AB\u62D2\u7EDD\u3002")}o=0,this.#a.ready=!0,this.#a.weixinConnectionState="connected",this.#a.lastCheckedAt=Date.now(),this.#a.lastError=null;for(let a of i?.msgs??[])this.#i.accept(a).catch(A=>{r.aborted||this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} message handling failed:`,A)});typeof i?.get_updates_buf=="string"&&i.get_updates_buf&&await this.#g.setGetUpdatesBuf(i.get_updates_buf)}catch(i){if(r.aborted)return;if(o+=1,this.#a.lastError=i?.message??String(i),this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} poll failed (${o}/3):`,i),i instanceof qA&&i.code==="stale-token"||o>=3)throw i;await ej(Math.min(2e3*2**(o-1),1e4),r)}}async stop(){let r=this.#c,o=this.#i,i=!!(this.#o||r||this.#a.ready);if(this.#o?.abort(),this.#o=null,this.#c=null,await r?.catch(()=>{}),await o?.waitForIdle(),this.#i=null,i)try{await this.#e.notifyStop({baseUrl:this.#A.baseUrl,token:this.#t,signal:AbortSignal.timeout(1e4)})}catch(e){this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} stop notification failed:`,e)}return this.#a.ready=!1,this.#a.weixinConnectionState="idle",this.status}async sendConnectionTest(r){let o=OE(this.#g),i=typeof o?.toUserId=="string"&&o.toUserId.trim()?o.toUserId.trim():typeof this.#A.ownerUserId=="string"&&this.#A.ownerUserId.trim()?this.#A.ownerUserId.trim():null;if(!i)throw kt("\u5FAE\u4FE1\u673A\u5668\u4EBA");if(!this.#a.ready||!this.#o)throw new Error("Weixin runtime is not connected");return await this.#e.sendText({baseUrl:this.#A.baseUrl,token:this.#t,toUserId:i,text:r,signal:this.#o.signal}),{sent:!0}}};var Aj=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function Tye(n){if(!Array.isArray(n)||n.length===0)return[...Aj];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...Aj]}var WQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=Tye(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(i65535)throw new Error("dsh-weixin requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function Pye(n){let r=rc(n.dshHome??process.env.DSH_HOME??bC(kye(),".dsh")),o=rc(n.dataDir??bC(r,"integrations","dsh-weixin"));return{root:o,config:rc(n.configPath??bC(o,"config.json")),accounts:rc(n.accountsDir??bC(o,"accounts")),workspaces:rc(n.workspacesPath??bC(o,"workspaces.json"))}}async function Q0(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-weixin requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-weixin requires ctx.webServer");let i=o.ConfigStore??YQ,e=o.StateStore??JQ,a=o.HarnessClient??xQ,A=o.Controller??OC,t=o.Runtime??MC,s=o.api??q3(),g=o.createConnectionSupervisor??B0,c=typeof n.logger=="function"?n.logger("dsh-weixin"):n.logger??console,l=Pye(r),p=await new i(l.config).load(),B=rc(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(F=>F.botId)),await Promise.all(y.map(F=>f.ensure(F.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=new Map,k=F=>rc(l.accounts,F,"state.json"),G=async F=>{let T=R.get(F);return T||(T=await new e(k(F)).load(),R.set(F,T)),T},K=zr(n,o.commandExecutor),x=new a({baseUrl:vye(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...K?{commandExecutor:K}:{}}),H=new A({api:s,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:F,config:T,token:V})=>{let U=await G(F);await f.ensure(F);let b=qr(x,{botId:F,workspaces:f,state:U});return new t({api:s,config:T,token:V,harness:b.harness,state:b.state,replyTimeoutMs:r.replyTimeoutMs??6e5,maxMessageChars:r.maxMessageChars??4e3,logger:{error:(...L)=>c.error?.(`[${F}]`,...L),warn:(...L)=>c.warn?.(`[${F}]`,...L),info:(...L)=>c.info?.(`[${F}]`,...L),debug:(...L)=>c.debug?.(`[${F}]`,...L)}})},deleteState:async({botId:F})=>{let T=R.get(F);if(R.delete(F),T&&typeof T.remove=="function")await T.remove();else try{await Rye(k(F))}catch(V){if(V?.code!=="ENOENT")throw V}}}),q=Vr(H,{workspaces:f,stateFor:G}),j=g({controller:q,harness:x,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:q,ready:j.ready,async close(){await j.close(),await q.close(),x.stopManagedProcess()}}}import Gye from"qrcode";var tj="/weixin",Tr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",submitVerification:"provision.verify",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),rj=Object.freeze(Object.values(Tr));function aj(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function $I(n,r){return aj(n)&&Object.keys(n).every(o=>r.includes(o))}function ZQ(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function Fye(n,r){return aj(r)?n===Tr.status?$I(r,[])?null:"connection.status does not accept fields.":n===Tr.beginProvisioning?$I(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Tr.pollProvisioning,Tr.cancelProvisioning].includes(n)?$I(r,["attemptId"])&&ZQ(r.attemptId)?null:`${n} requires an attemptId.`:n===Tr.submitVerification?$I(r,["attemptId","verifyCode"])&&ZQ(r.attemptId)&&typeof r.verifyCode=="string"&&/^\d{4,8}$/.test(r.verifyCode)?null:"provision.verify requires an attemptId and a 4-to-8-digit code.":n===Tr.reconnectBot?$I(r,["botId","sendTest"])&&ZQ(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Tr.deleteBot?$I(r,["botId","confirm"])&&ZQ(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Tr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Weixin endpoint.":"Payload must be an object."}function XQ(n){return{ok:!1,error:{code:"bad-request",message:n}}}function _C(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function Lye(){return{ok:!1,error:{code:"weixin-operation-failed",message:"\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}async function Uye(n){return Gye.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function ef(n,r){return!n||!n.verificationUrl?n:{...n,qrCodeDataUrl:await r(n.verificationUrl)}}async function $Q(n,r){let o=structuredClone(n);return o.provisioning&&(o.provisioning=await ef(o.provisioning,r)),o}function Hye(n){if(!n||typeof n.status!="function"||typeof n.startProvisioning!="function"||typeof n.registrationStatus!="function"||typeof n.submitVerification!="function"||typeof n.cancelProvisioning!="function"||typeof n.reconnectBot!="function"||typeof n.deleteBot!="function")throw new TypeError("A complete Weixin controller is required")}function ij(n,{encodeQr:r=Uye}={}){Hye(n);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(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return _C();if(!rj.includes(e))return XQ("Unknown Weixin endpoint.");let t=Fye(e,a);if(t)return XQ(t);try{let s;if(e===Tr.status)s=await $Q(await n.status(),i);else if(e===Tr.beginProvisioning){let g=await n.startProvisioning();if(A?.aborted)return await n.cancelProvisioning(g.attemptId),_C();s=await ef(g,i)}else if(e===Tr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return XQ("The provisioning attempt no longer exists.");s=await ef(g,i)}else if(e===Tr.submitVerification)s=await ef(await n.submitVerification(a.attemptId,a.verifyCode),i);else if(e===Tr.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return XQ("The provisioning attempt no longer exists.")}else if(e===Tr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return _C();let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await $Q({...g,...c?{testMessage:c}:{}},i)}else if(e===Tr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await $Q(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await $Q(await n.deleteBot(a.botId),i);return A?.aborted?_C():{ok:!0,value:s}}catch(s){let g=Xr(s);return A?.aborted?_C():g?{ok:!1,error:g}:Lye()}}}function Af(n,r,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(tj,ij(r,o),{authority:Wr(i)})}async function oj(n,r={}){if(r?.controller)return Af(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await Q0(n,r,r.internals),i=Af(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-weixin: close account connections"),i}import{rm as FLe,unlink as LLe}from"node:fs/promises";import{homedir as ULe}from"node:os";import{join as DE,resolve as Wn}from"node:path";import{createHash as Kye}from"node:crypto";import{mkdir as Yye,readFile as xye,rename as jye,unlink as Jye,writeFile as qye}from"node:fs/promises";import{dirname as Vye}from"node:path";var f0=Object.freeze({version:2,bots:Object.freeze([])}),nj=/^whatsapp_[a-f0-9]{24}$/,zye=/^[a-f0-9-]{36}$/;function el(n){return typeof n=="string"&&n.trim()?n.trim():null}function tf(n){let r=el(n)?.toLowerCase();return/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(r??"")?r:null}function y0(n){let r=tf(n);if(!r)throw new TypeError("A valid WhatsApp account JID is required");return`whatsapp_${Kye("sha256").update(r).digest("hex").slice(0,24)}`}function m0(n){let r=tf(n)?.split("@")[0]??"";return r?r.length<=7?`${r.slice(0,2)}\u2022\u2022\u2022${r.slice(-2)}`:`${r.slice(0,4)}\u2022\u2022\u2022\u2022${r.slice(-4)}`:"WhatsApp\u8D26\u53F7"}var rf=class{#e;#A=f0;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=this.#g(JSON.parse(await xye(this.#e,"utf8")));if(!r)throw new Error("dsh-im WhatsApp config contains invalid account data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=f0}return this}list(){return structuredClone(this.#A.bots)}get(r){let o=this.#A.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByAccountJid(r){let o=tf(r),i=this.#A.bots.find(e=>e.accountJid===o);return i?structuredClone(i):null}async save(r){let o=this.#r(r);if(!o)throw new Error("Refusing to persist incomplete WhatsApp account data");return this.#n(i=>{let e=i.find(t=>t.accountJid===o.accountJid&&t.botId!==o.botId),a=i.find(t=>t.authDirectory===o.authDirectory&&t.botId!==o.botId);if(e||a)throw new Error("Duplicate WhatsApp account identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!nj.test(r))throw new TypeError("Invalid WhatsApp bot id");return this.#n(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await Jye(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=f0});this.#t=r.then(()=>{},()=>{}),await r}#r(r){if(!r||typeof r!="object")return null;let o=tf(r.accountJid),i=el(r.botId),e=el(r.authDirectory),a=el(r.name);return!o||!i||!e||!a||!nj.test(i)||!zye.test(e)||y0(o)!==i?null:Object.freeze({botId:i,accountJid:o,authDirectory:e,name:a,createdAt:el(r.createdAt)??new Date().toISOString(),connectedAt:el(r.connectedAt)})}#g(r){if(!r||r.version!==2||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.accountJid)||a.has(A.authDirectory))return null;i.add(A.botId),e.add(A.accountJid),a.add(A.authDirectory)}return Object.freeze({version:2,bots:Object.freeze(o)})}async#n(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=r(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#E(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#E(r){await Yye(Vye(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await qye(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await jye(o,this.#e)}};var af=class extends qt{constructor(r){super({...r,rpcIdPrefix:"whatsapp",logPrefix:"dsh-whatsapp"})}};var of=class extends Eo{};import{randomUUID as Wye}from"node:crypto";var sj=new Set(["starting","pending","connecting"]),nf=new Set(["connected","failed","cancelled"]),Zye=6e4;function Ss(n,r){return Object.freeze({code:n,message:r})}function sf(n){return n?{attemptId:n.id,status:n.state,qrRevision:n.qrRevision,pollIntervalMs:1e3,...n.qrValue?{qrValue:n.qrValue}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var NC=class{#e;#A;#t;#r;#g;#n;#E;#s=new Map;#I=new Map;#a=new Map;#i=new Map;#o=null;#c=0;#l=!1;constructor({configStore:r,authPath:o,createSession:i,createRuntime:e,deleteAuth:a=async()=>{},deleteState:A=async()=>{},logger:t=console}){if(!r||typeof r.list!="function"||typeof r.save!="function"||typeof r.remove!="function")throw new TypeError("WhatsappController requires a config store");if(typeof o!="function"||typeof i!="function"||typeof e!="function")throw new TypeError("WhatsappController dependencies are incomplete");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t}async initialize(){if(this.#l)return this.status();for(let r of this.#e.list())await this.#Q(r.botId,async()=>{if(!(this.#l||this.#s.get(r.botId)?.status?.ready))try{await this.#C(r),this.#I.delete(r.botId)}catch(o){this.#I.set(r.botId,Ss(o?.code==="relink-required"?"relink-required":"connection-failed",o?.code==="relink-required"?"WhatsApp \u5173\u8054\u8BBE\u5907\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002":"WhatsApp \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#E.warn?.(`[dsh-im:whatsapp] bot ${r.botId} failed to initialize`)}finally{this.#u()}});return this.status()}async startProvisioning(){if(this.#l)throw new Error("WhatsApp controller is closed");this.#o&&await this.cancelProvisioning(this.#o);let r,o,i=!1,e=new Promise((t,s)=>{r=()=>{i||(i=!0,t())},o=g=>{i||(i=!0,s(g))}}),a=Wye(),A={id:a,state:"starting",authDirectory:a,createdAt:Date.now(),expiresAt:null,qrRevision:0,qrValue:null,controller:new AbortController,session:null,task:null,error:null,botId:null};this.#a.set(a,A),this.#o=a,this.#u();try{let t=await this.#t({authDir:this.#A(A.authDirectory),signal:A.controller.signal,logger:this.#E,onQr:s=>{A.controller.signal.aborted||nf.has(A.state)||typeof s!="string"||!s||(A.qrValue=s,A.qrRevision+=1,A.expiresAt=Date.now()+Zye,A.state="pending",this.#u(),r())}});return A.session=t,A.task=t.ready.then(s=>this.#p(A,s)).catch(s=>this.#h(A,s,o)),await e,sf(A)}catch(t){throw await this.#h(A,t,o),t}}registrationStatus(r){return sf(this.#a.get(r))}async cancelProvisioning(r){let o=this.#a.get(r);return o?(nf.has(o.state)||(o.controller.abort(),await o.session?.close().catch(()=>{}),await o.task?.catch(()=>{}),nf.has(o.state)||(o.state="cancelled",o.error=Ss("cancelled","\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002")),await this.#g(o.authDirectory).catch(()=>{})),this.#o===o.id&&(this.#o=null),this.#u(),sf(o)):null}async reconnectBot(r){let o=this.#e.get(r);if(!o)throw new Error("Unknown WhatsApp bot");return await this.#Q(r,async()=>{try{await this.#C(o),this.#I.delete(r)}catch(i){throw this.#I.set(r,Ss(i?.code==="relink-required"?"relink-required":"connection-failed",i?.code==="relink-required"?"WhatsApp \u5173\u8054\u8BBE\u5907\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002":"WhatsApp \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),i}finally{this.#u()}}),this.status()}async sendConnectionTest(r){let o=this.#e.get(r);if(!o)throw new Error("Unknown WhatsApp bot");return this.#Q(r,async()=>{let i=this.#s.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return i.sendConnectionTest(Yr(`${o.name}\uFF08${m0(o.accountJid)}\uFF09`,"WhatsApp\u673A\u5668\u4EBA"))})}async deleteBot(r){let o=this.#e.get(r);if(!o)throw new Error("Unknown WhatsApp bot");return await this.#Q(r,async()=>{await this.#d(r);try{await this.#e.remove(r)}catch(i){throw await this.#C(o).catch(()=>{}),i}await Promise.allSettled([this.#g(o.authDirectory),this.#n({botId:r,config:o})]),this.#I.delete(r),this.#u()}),this.status()}status(){let r=this.#e.list().map(e=>{let a=this.#s.get(e.botId)?.status??null,A=a?.ready===!0&&a.connectionState==="connected"&&a.harnessReachable===!0,t=A?"connected":a?.connectionState==="connecting"?"connecting":this.#I.has(e.botId)||a?.connectionState==="failed"?"error":"offline";return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:e.name,idMasked:m0(e.accountJid)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"WhatsApp Web \u5173\u8054\u8BBE\u5907\u8FD0\u884C\u6B63\u5E38":t==="error"?"WhatsApp \u8FDE\u63A5\u672A\u5C31\u7EEA":"WhatsApp \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},error:structuredClone(this.#I.get(e.botId)??null)}}),o=r.filter(e=>e.connected).length,i=this.#o?this.#a.get(this.#o):null;return{schemaVersion:1,revision:this.#c,state:i&&sj.has(i.state)?"provisioning":r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o},...i&&sj.has(i.state)?{provisioning:sf(i)}:{}}}async close(){this.#l||(this.#l=!0,this.#o&&await this.cancelProvisioning(this.#o),await Promise.allSettled([...this.#i.values()]),await Promise.allSettled([...this.#s.keys()].map(r=>this.#d(r))))}async#p(r,o){if(r.controller.signal.aborted||this.#l)return;r.state="connecting",r.qrValue=null,r.expiresAt=null,this.#u();let i=y0(o.accountJid);r.botId=i,await r.session?.close();let e=this.#e.get(i),a={botId:i,accountJid:o.accountJid,authDirectory:r.authDirectory,name:o.name,createdAt:e?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};try{if(r.controller.signal.aborted||this.#l)throw Object.assign(new Error,{name:"AbortError"});if(await this.#e.save(a),r.controller.signal.aborted||this.#l)throw Object.assign(new Error,{name:"AbortError"});try{await this.#C(a),this.#I.delete(i)}catch{this.#I.set(i,Ss("connection-failed","WhatsApp \u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#E.warn?.(`[dsh-im:whatsapp] bot ${i} did not reconnect after QR binding`)}e?.authDirectory&&e.authDirectory!==a.authDirectory&&await this.#g(e.authDirectory).catch(()=>{}),r.state="connected",r.error=null}catch(A){r.controller.signal.aborted||this.#l||A?.name==="AbortError"?(await this.#d(i),e?await this.#e.save(e).catch(()=>{}):await this.#e.remove(i).catch(()=>null)&&await this.#n({botId:i,config:a}).catch(s=>{this.#E.warn?.("[dsh-im:whatsapp] cancelled bot state cleanup failed:",s)}),await this.#g(r.authDirectory).catch(()=>{}),e&&await this.#C(e).catch(()=>{}),r.state="cancelled",r.error=Ss("cancelled","\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002")):(await this.#g(r.authDirectory).catch(()=>{}),r.state="failed",r.error=Ss("activation-failed","WhatsApp \u5DF2\u626B\u7801\uFF0C\u4F46\u65E0\u6CD5\u4FDD\u5B58\u5173\u8054\u8BBE\u5907\u3002"),this.#E.error?.("[dsh-im:whatsapp] unable to persist linked-device session"))}finally{this.#o===r.id&&(this.#o=null),this.#u()}}async#h(r,o,i=()=>{}){nf.has(r.state)||(r.controller.signal.aborted||o?.name==="AbortError"?(r.state="cancelled",r.error=Ss("cancelled","\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=Ss("qr-connect-failed","\u65E0\u6CD5\u8FDE\u63A5 WhatsApp\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002")),this.#o===r.id&&(this.#o=null),await r.session?.close().catch(()=>{}),await this.#g(r.authDirectory).catch(()=>{}),this.#u(),i(o))}async#C(r){if(this.#l)throw new Error("WhatsApp controller is closed");if(await this.#d(r.botId),this.#l)throw new Error("WhatsApp controller is closed");let o=await this.#r({botId:r.botId,config:r,authDir:this.#A(r.authDirectory)});if(!o||typeof o.start!="function"||typeof o.stop!="function")throw new TypeError("createRuntime returned an invalid WhatsApp runtime");this.#s.set(r.botId,o);try{await o.start()}catch(i){throw await o.stop().catch(()=>{}),this.#s.delete(r.botId),i}}async#d(r){let o=this.#s.get(r);this.#s.delete(r),await o?.stop().catch(()=>{})}#Q(r,o){let a=(this.#i.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(r)===a&&this.#i.delete(r)});return this.#i.set(r,a),a}#u(){this.#c+=1}};var _=Le(dB(),1),D=_.default.Reader,N=_.default.Writer,I=_.default.util,E=_.default.roots.default||(_.default.roots.default={});function re(n,r){if(typeof n=="string")return n;if(typeof n=="number")return String(n);if(n&&typeof n.low=="number"&&typeof n.high=="number"){let o=BigInt(n.low>>>0),e=BigInt(n.high>>>0)<<32n|o;return!r&&n.high<0?(e-(1n<<64n)).toString():e.toString()}return String(n)}function ae(n,r){if(typeof n=="number")return n;if(typeof n=="string")return Number(n);if(n&&typeof n.low=="number"&&typeof n.high=="number"){let o=BigInt(n.low>>>0),e=BigInt(n.high>>>0)<<32n|o;return!r&&n.high<0?Number(e-(1n<<64n)):Number(e)}return Number(n)}var Ae=E.proto=(()=>{let n={};return n.ADVDeviceIdentity=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rawId=e.uint32();break}case 2:{s.timestamp=e.uint64();break}case 3:{s.keyIndex=e.uint32();break}case 4:{s.accountType=e.int32();break}case 5:{s.deviceType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ADVDeviceIdentity)return e;var a=new E.proto.ADVDeviceIdentity;switch(e.rawId!=null&&(a.rawId=e.rawId>>>0),e.timestamp!=null&&(I.Long?(a.timestamp=I.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new I.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.keyIndex!=null&&(a.keyIndex=e.keyIndex>>>0),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}switch(e.deviceType){default:if(typeof e.deviceType=="number"){a.deviceType=e.deviceType;break}break;case"E2EE":case 0:a.deviceType=0;break;case"HOSTED":case 1:a.deviceType=1;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.rawId!=null&&e.hasOwnProperty("rawId")&&(A.rawId=e.rawId,a.oneofs&&(A._rawId="rawId")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?re(e.timestamp,!0):a.longs===Number?ae(e.timestamp,!0):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.keyIndex!=null&&e.hasOwnProperty("keyIndex")&&(A.keyIndex=e.keyIndex,a.oneofs&&(A._keyIndex="keyIndex")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?E.proto.ADVEncryptionType[e.accountType]===void 0?e.accountType:E.proto.ADVEncryptionType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),e.deviceType!=null&&e.hasOwnProperty("deviceType")&&(A.deviceType=a.enums===String?E.proto.ADVEncryptionType[e.deviceType]===void 0?e.deviceType:E.proto.ADVEncryptionType[e.deviceType]:e.deviceType,a.oneofs&&(A._deviceType="deviceType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVDeviceIdentity"},r})(),n.ADVEncryptionType=(function(){let r={},o=Object.create(r);return o[r[0]="E2EE"]=0,o[r[1]="HOSTED"]=1,o})(),n.ADVKeyIndexList=(function(){function r(i){if(this.validIndexes=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rawId=e.uint32();break}case 2:{s.timestamp=e.uint64();break}case 3:{s.currentIndex=e.uint32();break}case 4:{if(s.validIndexes&&s.validIndexes.length||(s.validIndexes=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos>>0),e.timestamp!=null&&(I.Long?(a.timestamp=I.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new I.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.currentIndex!=null&&(a.currentIndex=e.currentIndex>>>0),e.validIndexes){if(!Array.isArray(e.validIndexes))throw TypeError(".proto.ADVKeyIndexList.validIndexes: array expected");a.validIndexes=[];for(var A=0;A>>0}switch(e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}return a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.validIndexes=[]),e.rawId!=null&&e.hasOwnProperty("rawId")&&(A.rawId=e.rawId,a.oneofs&&(A._rawId="rawId")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?re(e.timestamp,!0):a.longs===Number?ae(e.timestamp,!0):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.currentIndex!=null&&e.hasOwnProperty("currentIndex")&&(A.currentIndex=e.currentIndex,a.oneofs&&(A._currentIndex="currentIndex")),e.validIndexes&&e.validIndexes.length){A.validIndexes=[];for(var t=0;t>>3){case 1:{s.details=e.bytes();break}case 2:{s.accountSignatureKey=e.bytes();break}case 3:{s.accountSignature=e.bytes();break}case 4:{s.deviceSignature=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ADVSignedDeviceIdentity)return e;var a=new E.proto.ADVSignedDeviceIdentity;return e.details!=null&&(typeof e.details=="string"?I.base64.decode(e.details,a.details=I.newBuffer(I.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.accountSignatureKey!=null&&(typeof e.accountSignatureKey=="string"?I.base64.decode(e.accountSignatureKey,a.accountSignatureKey=I.newBuffer(I.base64.length(e.accountSignatureKey)),0):e.accountSignatureKey.length>=0&&(a.accountSignatureKey=e.accountSignatureKey)),e.accountSignature!=null&&(typeof e.accountSignature=="string"?I.base64.decode(e.accountSignature,a.accountSignature=I.newBuffer(I.base64.length(e.accountSignature)),0):e.accountSignature.length>=0&&(a.accountSignature=e.accountSignature)),e.deviceSignature!=null&&(typeof e.deviceSignature=="string"?I.base64.decode(e.deviceSignature,a.deviceSignature=I.newBuffer(I.base64.length(e.deviceSignature)),0):e.deviceSignature.length>=0&&(a.deviceSignature=e.deviceSignature)),a},r.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?I.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.accountSignatureKey!=null&&e.hasOwnProperty("accountSignatureKey")&&(A.accountSignatureKey=a.bytes===String?I.base64.encode(e.accountSignatureKey,0,e.accountSignatureKey.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignatureKey):e.accountSignatureKey,a.oneofs&&(A._accountSignatureKey="accountSignatureKey")),e.accountSignature!=null&&e.hasOwnProperty("accountSignature")&&(A.accountSignature=a.bytes===String?I.base64.encode(e.accountSignature,0,e.accountSignature.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignature):e.accountSignature,a.oneofs&&(A._accountSignature="accountSignature")),e.deviceSignature!=null&&e.hasOwnProperty("deviceSignature")&&(A.deviceSignature=a.bytes===String?I.base64.encode(e.deviceSignature,0,e.deviceSignature.length):a.bytes===Array?Array.prototype.slice.call(e.deviceSignature):e.deviceSignature,a.oneofs&&(A._deviceSignature="deviceSignature")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedDeviceIdentity"},r})(),n.ADVSignedDeviceIdentityHMAC=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.hmac=e.bytes();break}case 3:{s.accountType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ADVSignedDeviceIdentityHMAC)return e;var a=new E.proto.ADVSignedDeviceIdentityHMAC;switch(e.details!=null&&(typeof e.details=="string"?I.base64.decode(e.details,a.details=I.newBuffer(I.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.hmac!=null&&(typeof e.hmac=="string"?I.base64.decode(e.hmac,a.hmac=I.newBuffer(I.base64.length(e.hmac)),0):e.hmac.length>=0&&(a.hmac=e.hmac)),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?I.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.hmac!=null&&e.hasOwnProperty("hmac")&&(A.hmac=a.bytes===String?I.base64.encode(e.hmac,0,e.hmac.length):a.bytes===Array?Array.prototype.slice.call(e.hmac):e.hmac,a.oneofs&&(A._hmac="hmac")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?E.proto.ADVEncryptionType[e.accountType]===void 0?e.accountType:E.proto.ADVEncryptionType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedDeviceIdentityHMAC"},r})(),n.ADVSignedKeyIndexList=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.accountSignature=e.bytes();break}case 3:{s.accountSignatureKey=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ADVSignedKeyIndexList)return e;var a=new E.proto.ADVSignedKeyIndexList;return e.details!=null&&(typeof e.details=="string"?I.base64.decode(e.details,a.details=I.newBuffer(I.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.accountSignature!=null&&(typeof e.accountSignature=="string"?I.base64.decode(e.accountSignature,a.accountSignature=I.newBuffer(I.base64.length(e.accountSignature)),0):e.accountSignature.length>=0&&(a.accountSignature=e.accountSignature)),e.accountSignatureKey!=null&&(typeof e.accountSignatureKey=="string"?I.base64.decode(e.accountSignatureKey,a.accountSignatureKey=I.newBuffer(I.base64.length(e.accountSignatureKey)),0):e.accountSignatureKey.length>=0&&(a.accountSignatureKey=e.accountSignatureKey)),a},r.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?I.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.accountSignature!=null&&e.hasOwnProperty("accountSignature")&&(A.accountSignature=a.bytes===String?I.base64.encode(e.accountSignature,0,e.accountSignature.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignature):e.accountSignature,a.oneofs&&(A._accountSignature="accountSignature")),e.accountSignatureKey!=null&&e.hasOwnProperty("accountSignatureKey")&&(A.accountSignatureKey=a.bytes===String?I.base64.encode(e.accountSignatureKey,0,e.accountSignatureKey.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignatureKey):e.accountSignatureKey,a.oneofs&&(A._accountSignatureKey="accountSignatureKey")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedKeyIndexList"},r})(),n.AIHomeState=(function(){function r(i){if(this.capabilityOptions=[],this.conversationOptions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lastFetchTime=e.int64();break}case 2:{s.capabilityOptions&&s.capabilityOptions.length||(s.capabilityOptions=[]),s.capabilityOptions.push(E.proto.AIHomeState.AIHomeOption.decode(e,e.uint32()));break}case 3:{s.conversationOptions&&s.conversationOptions.length||(s.conversationOptions=[]),s.conversationOptions.push(E.proto.AIHomeState.AIHomeOption.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIHomeState)return e;var a=new E.proto.AIHomeState;if(e.lastFetchTime!=null&&(I.Long?(a.lastFetchTime=I.Long.fromValue(e.lastFetchTime)).unsigned=!1:typeof e.lastFetchTime=="string"?a.lastFetchTime=parseInt(e.lastFetchTime,10):typeof e.lastFetchTime=="number"?a.lastFetchTime=e.lastFetchTime:typeof e.lastFetchTime=="object"&&(a.lastFetchTime=new I.LongBits(e.lastFetchTime.low>>>0,e.lastFetchTime.high>>>0).toNumber())),e.capabilityOptions){if(!Array.isArray(e.capabilityOptions))throw TypeError(".proto.AIHomeState.capabilityOptions: array expected");a.capabilityOptions=[];for(var A=0;A>>3){case 1:{c.type=A.int32();break}case 2:{c.title=A.string();break}case 3:{c.promptText=A.string();break}case 4:{c.sessionId=A.string();break}case 5:{c.imageWdsIdentifier=A.string();break}case 6:{c.imageTintColor=A.string();break}case 7:{c.imageBackgroundColor=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIHomeState.AIHomeOption)return A;var t=new E.proto.AIHomeState.AIHomeOption;switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"PROMPT":case 0:t.type=0;break;case"CREATE_IMAGE":case 1:t.type=1;break;case"ANIMATE_PHOTO":case 2:t.type=2;break;case"ANALYZE_FILE":case 3:t.type=3;break}return A.title!=null&&(t.title=String(A.title)),A.promptText!=null&&(t.promptText=String(A.promptText)),A.sessionId!=null&&(t.sessionId=String(A.sessionId)),A.imageWdsIdentifier!=null&&(t.imageWdsIdentifier=String(A.imageWdsIdentifier)),A.imageTintColor!=null&&(t.imageTintColor=String(A.imageTintColor)),A.imageBackgroundColor!=null&&(t.imageBackgroundColor=String(A.imageBackgroundColor)),t},i.toObject=function(A,t){t||(t={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.AIHomeState.AIHomeOption.AIHomeActionType[A.type]===void 0?A.type:E.proto.AIHomeState.AIHomeOption.AIHomeActionType[A.type]:A.type,t.oneofs&&(s._type="type")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),A.promptText!=null&&A.hasOwnProperty("promptText")&&(s.promptText=A.promptText,t.oneofs&&(s._promptText="promptText")),A.sessionId!=null&&A.hasOwnProperty("sessionId")&&(s.sessionId=A.sessionId,t.oneofs&&(s._sessionId="sessionId")),A.imageWdsIdentifier!=null&&A.hasOwnProperty("imageWdsIdentifier")&&(s.imageWdsIdentifier=A.imageWdsIdentifier,t.oneofs&&(s._imageWdsIdentifier="imageWdsIdentifier")),A.imageTintColor!=null&&A.hasOwnProperty("imageTintColor")&&(s.imageTintColor=A.imageTintColor,t.oneofs&&(s._imageTintColor="imageTintColor")),A.imageBackgroundColor!=null&&A.hasOwnProperty("imageBackgroundColor")&&(s.imageBackgroundColor=A.imageBackgroundColor,t.oneofs&&(s._imageBackgroundColor="imageBackgroundColor")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIHomeState.AIHomeOption"},i.AIHomeActionType=(function(){let a={},A=Object.create(a);return A[a[0]="PROMPT"]=0,A[a[1]="CREATE_IMAGE"]=1,A[a[2]="ANIMATE_PHOTO"]=2,A[a[3]="ANALYZE_FILE"]=3,A})(),i})(),r})(),n.AIQueryFanout=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=E.proto.Message.decode(e,e.uint32());break}case 3:{s.timestamp=e.int64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIQueryFanout)return e;var a=new E.proto.AIQueryFanout;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.AIQueryFanout.messageKey: object expected");a.messageKey=E.proto.MessageKey.fromObject(e.messageKey)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.AIQueryFanout.message: object expected");a.message=E.proto.Message.fromObject(e.message)}return e.timestamp!=null&&(I.Long?(a.timestamp=I.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new I.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=E.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=E.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?re(e.timestamp):a.longs===Number?ae(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIQueryFanout"},r})(),n.AIRegenerateMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.responseTimestampMs=e.int64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRegenerateMetadata)return e;var a=new E.proto.AIRegenerateMetadata;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.AIRegenerateMetadata.messageKey: object expected");a.messageKey=E.proto.MessageKey.fromObject(e.messageKey)}return e.responseTimestampMs!=null&&(I.Long?(a.responseTimestampMs=I.Long.fromValue(e.responseTimestampMs)).unsigned=!1:typeof e.responseTimestampMs=="string"?a.responseTimestampMs=parseInt(e.responseTimestampMs,10):typeof e.responseTimestampMs=="number"?a.responseTimestampMs=e.responseTimestampMs:typeof e.responseTimestampMs=="object"&&(a.responseTimestampMs=new I.LongBits(e.responseTimestampMs.low>>>0,e.responseTimestampMs.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=E.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.responseTimestampMs!=null&&e.hasOwnProperty("responseTimestampMs")&&(typeof e.responseTimestampMs=="number"?A.responseTimestampMs=a.longs===String?String(e.responseTimestampMs):e.responseTimestampMs:A.responseTimestampMs=a.longs===String?re(e.responseTimestampMs):a.longs===Number?ae(e.responseTimestampMs):e.responseTimestampMs,a.oneofs&&(A._responseTimestampMs="responseTimestampMs")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRegenerateMetadata"},r})(),n.AIRichResponseCodeMetadata=(function(){function r(i){if(this.codeBlocks=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.codeLanguage=e.string();break}case 2:{s.codeBlocks&&s.codeBlocks.length||(s.codeBlocks=[]),s.codeBlocks.push(E.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseCodeMetadata)return e;var a=new E.proto.AIRichResponseCodeMetadata;if(e.codeLanguage!=null&&(a.codeLanguage=String(e.codeLanguage)),e.codeBlocks){if(!Array.isArray(e.codeBlocks))throw TypeError(".proto.AIRichResponseCodeMetadata.codeBlocks: array expected");a.codeBlocks=[];for(var A=0;A>>3){case 1:{c.highlightType=A.int32();break}case 2:{c.codeContent=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock)return A;var t=new E.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock;switch(A.highlightType){default:if(typeof A.highlightType=="number"){t.highlightType=A.highlightType;break}break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_DEFAULT":case 0:t.highlightType=0;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_KEYWORD":case 1:t.highlightType=1;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_METHOD":case 2:t.highlightType=2;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_STRING":case 3:t.highlightType=3;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_NUMBER":case 4:t.highlightType=4;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_COMMENT":case 5:t.highlightType=5;break}return A.codeContent!=null&&(t.codeContent=String(A.codeContent)),t},i.toObject=function(A,t){t||(t={});var s={};return A.highlightType!=null&&A.hasOwnProperty("highlightType")&&(s.highlightType=t.enums===String?E.proto.AIRichResponseCodeMetadata.AIRichResponseCodeHighlightType[A.highlightType]===void 0?A.highlightType:E.proto.AIRichResponseCodeMetadata.AIRichResponseCodeHighlightType[A.highlightType]:A.highlightType,t.oneofs&&(s._highlightType="highlightType")),A.codeContent!=null&&A.hasOwnProperty("codeContent")&&(s.codeContent=A.codeContent,t.oneofs&&(s._codeContent="codeContent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock"},i})(),r.AIRichResponseCodeHighlightType=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_DEFAULT"]=0,e[i[1]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_KEYWORD"]=1,e[i[2]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_METHOD"]=2,e[i[3]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_STRING"]=3,e[i[4]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_NUMBER"]=4,e[i[5]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_COMMENT"]=5,e})(),r})(),n.AIRichResponseContentItemsMetadata=(function(){function r(i){if(this.itemsMetadata=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.itemsMetadata&&s.itemsMetadata.length||(s.itemsMetadata=[]),s.itemsMetadata.push(E.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata.decode(e,e.uint32()));break}case 2:{s.contentType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseContentItemsMetadata)return e;var a=new E.proto.AIRichResponseContentItemsMetadata;if(e.itemsMetadata){if(!Array.isArray(e.itemsMetadata))throw TypeError(".proto.AIRichResponseContentItemsMetadata.itemsMetadata: array expected");a.itemsMetadata=[];for(var A=0;A>>3){case 1:{c.reelItem=E.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata)return A;var t=new E.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata;if(A.reelItem!=null){if(typeof A.reelItem!="object")throw TypeError(".proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata.reelItem: object expected");t.reelItem=E.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.fromObject(A.reelItem)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.reelItem!=null&&A.hasOwnProperty("reelItem")&&(s.reelItem=E.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.toObject(A.reelItem,t),t.oneofs&&(s.aIRichResponseContentItem="reelItem")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata"},i})(),r.AIRichResponseReelItem=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.title=A.string();break}case 2:{c.profileIconUrl=A.string();break}case 3:{c.thumbnailUrl=A.string();break}case 4:{c.videoUrl=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem)return A;var t=new E.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem;return A.title!=null&&(t.title=String(A.title)),A.profileIconUrl!=null&&(t.profileIconUrl=String(A.profileIconUrl)),A.thumbnailUrl!=null&&(t.thumbnailUrl=String(A.thumbnailUrl)),A.videoUrl!=null&&(t.videoUrl=String(A.videoUrl)),t},i.toObject=function(A,t){t||(t={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),A.profileIconUrl!=null&&A.hasOwnProperty("profileIconUrl")&&(s.profileIconUrl=A.profileIconUrl,t.oneofs&&(s._profileIconUrl="profileIconUrl")),A.thumbnailUrl!=null&&A.hasOwnProperty("thumbnailUrl")&&(s.thumbnailUrl=A.thumbnailUrl,t.oneofs&&(s._thumbnailUrl="thumbnailUrl")),A.videoUrl!=null&&A.hasOwnProperty("videoUrl")&&(s.videoUrl=A.videoUrl,t.oneofs&&(s._videoUrl="videoUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem"},i})(),r.ContentType=(function(){let i={},e=Object.create(i);return e[i[0]="DEFAULT"]=0,e[i[1]="CAROUSEL"]=1,e})(),r})(),n.AIRichResponseDynamicMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.version=e.uint64();break}case 3:{s.url=e.string();break}case 4:{s.loopCount=e.uint32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseDynamicMetadata)return e;var a=new E.proto.AIRichResponseDynamicMetadata;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_UNKNOWN":case 0:a.type=0;break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE":case 1:a.type=1;break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF":case 2:a.type=2;break}return e.version!=null&&(I.Long?(a.version=I.Long.fromValue(e.version)).unsigned=!0:typeof e.version=="string"?a.version=parseInt(e.version,10):typeof e.version=="number"?a.version=e.version:typeof e.version=="object"&&(a.version=new I.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber(!0))),e.url!=null&&(a.url=String(e.url)),e.loopCount!=null&&(a.loopCount=e.loopCount>>>0),a},r.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?E.proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType[e.type]===void 0?e.type:E.proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType[e.type]:e.type,a.oneofs&&(A._type="type")),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?A.version=a.longs===String?String(e.version):e.version:A.version=a.longs===String?re(e.version,!0):a.longs===Number?ae(e.version,!0):e.version,a.oneofs&&(A._version="version")),e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.loopCount!=null&&e.hasOwnProperty("loopCount")&&(A.loopCount=e.loopCount,a.oneofs&&(A._loopCount="loopCount")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseDynamicMetadata"},r.AIRichResponseDynamicMetadataType=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_UNKNOWN"]=0,e[i[1]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE"]=1,e[i[2]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF"]=2,e})(),r})(),n.AIRichResponseGridImageMetadata=(function(){function r(i){if(this.imageUrls=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.gridImageUrl=E.proto.AIRichResponseImageURL.decode(e,e.uint32());break}case 2:{s.imageUrls&&s.imageUrls.length||(s.imageUrls=[]),s.imageUrls.push(E.proto.AIRichResponseImageURL.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseGridImageMetadata)return e;var a=new E.proto.AIRichResponseGridImageMetadata;if(e.gridImageUrl!=null){if(typeof e.gridImageUrl!="object")throw TypeError(".proto.AIRichResponseGridImageMetadata.gridImageUrl: object expected");a.gridImageUrl=E.proto.AIRichResponseImageURL.fromObject(e.gridImageUrl)}if(e.imageUrls){if(!Array.isArray(e.imageUrls))throw TypeError(".proto.AIRichResponseGridImageMetadata.imageUrls: array expected");a.imageUrls=[];for(var A=0;A>>3){case 1:{s.imagePreviewUrl=e.string();break}case 2:{s.imageHighResUrl=e.string();break}case 3:{s.sourceUrl=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseImageURL)return e;var a=new E.proto.AIRichResponseImageURL;return e.imagePreviewUrl!=null&&(a.imagePreviewUrl=String(e.imagePreviewUrl)),e.imageHighResUrl!=null&&(a.imageHighResUrl=String(e.imageHighResUrl)),e.sourceUrl!=null&&(a.sourceUrl=String(e.sourceUrl)),a},r.toObject=function(e,a){a||(a={});var A={};return e.imagePreviewUrl!=null&&e.hasOwnProperty("imagePreviewUrl")&&(A.imagePreviewUrl=e.imagePreviewUrl,a.oneofs&&(A._imagePreviewUrl="imagePreviewUrl")),e.imageHighResUrl!=null&&e.hasOwnProperty("imageHighResUrl")&&(A.imageHighResUrl=e.imageHighResUrl,a.oneofs&&(A._imageHighResUrl="imageHighResUrl")),e.sourceUrl!=null&&e.hasOwnProperty("sourceUrl")&&(A.sourceUrl=e.sourceUrl,a.oneofs&&(A._sourceUrl="sourceUrl")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseImageURL"},r})(),n.AIRichResponseInlineImageMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.imageUrl=E.proto.AIRichResponseImageURL.decode(e,e.uint32());break}case 2:{s.imageText=e.string();break}case 3:{s.alignment=e.int32();break}case 4:{s.tapLinkUrl=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseInlineImageMetadata)return e;var a=new E.proto.AIRichResponseInlineImageMetadata;if(e.imageUrl!=null){if(typeof e.imageUrl!="object")throw TypeError(".proto.AIRichResponseInlineImageMetadata.imageUrl: object expected");a.imageUrl=E.proto.AIRichResponseImageURL.fromObject(e.imageUrl)}switch(e.imageText!=null&&(a.imageText=String(e.imageText)),e.alignment){default:if(typeof e.alignment=="number"){a.alignment=e.alignment;break}break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_LEADING_ALIGNED":case 0:a.alignment=0;break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_TRAILING_ALIGNED":case 1:a.alignment=1;break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_CENTER_ALIGNED":case 2:a.alignment=2;break}return e.tapLinkUrl!=null&&(a.tapLinkUrl=String(e.tapLinkUrl)),a},r.toObject=function(e,a){a||(a={});var A={};return e.imageUrl!=null&&e.hasOwnProperty("imageUrl")&&(A.imageUrl=E.proto.AIRichResponseImageURL.toObject(e.imageUrl,a),a.oneofs&&(A._imageUrl="imageUrl")),e.imageText!=null&&e.hasOwnProperty("imageText")&&(A.imageText=e.imageText,a.oneofs&&(A._imageText="imageText")),e.alignment!=null&&e.hasOwnProperty("alignment")&&(A.alignment=a.enums===String?E.proto.AIRichResponseInlineImageMetadata.AIRichResponseImageAlignment[e.alignment]===void 0?e.alignment:E.proto.AIRichResponseInlineImageMetadata.AIRichResponseImageAlignment[e.alignment]:e.alignment,a.oneofs&&(A._alignment="alignment")),e.tapLinkUrl!=null&&e.hasOwnProperty("tapLinkUrl")&&(A.tapLinkUrl=e.tapLinkUrl,a.oneofs&&(A._tapLinkUrl="tapLinkUrl")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseInlineImageMetadata"},r.AIRichResponseImageAlignment=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_IMAGE_LAYOUT_LEADING_ALIGNED"]=0,e[i[1]="AI_RICH_RESPONSE_IMAGE_LAYOUT_TRAILING_ALIGNED"]=1,e[i[2]="AI_RICH_RESPONSE_IMAGE_LAYOUT_CENTER_ALIGNED"]=2,e})(),r})(),n.AIRichResponseLatexMetadata=(function(){function r(i){if(this.expressions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.text=e.string();break}case 2:{s.expressions&&s.expressions.length||(s.expressions=[]),s.expressions.push(E.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseLatexMetadata)return e;var a=new E.proto.AIRichResponseLatexMetadata;if(e.text!=null&&(a.text=String(e.text)),e.expressions){if(!Array.isArray(e.expressions))throw TypeError(".proto.AIRichResponseLatexMetadata.expressions: array expected");a.expressions=[];for(var A=0;A>>3){case 1:{c.latexExpression=A.string();break}case 2:{c.url=A.string();break}case 3:{c.width=A.double();break}case 4:{c.height=A.double();break}case 5:{c.fontHeight=A.double();break}case 6:{c.imageTopPadding=A.double();break}case 7:{c.imageLeadingPadding=A.double();break}case 8:{c.imageBottomPadding=A.double();break}case 9:{c.imageTrailingPadding=A.double();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression)return A;var t=new E.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression;return A.latexExpression!=null&&(t.latexExpression=String(A.latexExpression)),A.url!=null&&(t.url=String(A.url)),A.width!=null&&(t.width=Number(A.width)),A.height!=null&&(t.height=Number(A.height)),A.fontHeight!=null&&(t.fontHeight=Number(A.fontHeight)),A.imageTopPadding!=null&&(t.imageTopPadding=Number(A.imageTopPadding)),A.imageLeadingPadding!=null&&(t.imageLeadingPadding=Number(A.imageLeadingPadding)),A.imageBottomPadding!=null&&(t.imageBottomPadding=Number(A.imageBottomPadding)),A.imageTrailingPadding!=null&&(t.imageTrailingPadding=Number(A.imageTrailingPadding)),t},i.toObject=function(A,t){t||(t={});var s={};return A.latexExpression!=null&&A.hasOwnProperty("latexExpression")&&(s.latexExpression=A.latexExpression,t.oneofs&&(s._latexExpression="latexExpression")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=t.json&&!isFinite(A.width)?String(A.width):A.width,t.oneofs&&(s._width="width")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=t.json&&!isFinite(A.height)?String(A.height):A.height,t.oneofs&&(s._height="height")),A.fontHeight!=null&&A.hasOwnProperty("fontHeight")&&(s.fontHeight=t.json&&!isFinite(A.fontHeight)?String(A.fontHeight):A.fontHeight,t.oneofs&&(s._fontHeight="fontHeight")),A.imageTopPadding!=null&&A.hasOwnProperty("imageTopPadding")&&(s.imageTopPadding=t.json&&!isFinite(A.imageTopPadding)?String(A.imageTopPadding):A.imageTopPadding,t.oneofs&&(s._imageTopPadding="imageTopPadding")),A.imageLeadingPadding!=null&&A.hasOwnProperty("imageLeadingPadding")&&(s.imageLeadingPadding=t.json&&!isFinite(A.imageLeadingPadding)?String(A.imageLeadingPadding):A.imageLeadingPadding,t.oneofs&&(s._imageLeadingPadding="imageLeadingPadding")),A.imageBottomPadding!=null&&A.hasOwnProperty("imageBottomPadding")&&(s.imageBottomPadding=t.json&&!isFinite(A.imageBottomPadding)?String(A.imageBottomPadding):A.imageBottomPadding,t.oneofs&&(s._imageBottomPadding="imageBottomPadding")),A.imageTrailingPadding!=null&&A.hasOwnProperty("imageTrailingPadding")&&(s.imageTrailingPadding=t.json&&!isFinite(A.imageTrailingPadding)?String(A.imageTrailingPadding):A.imageTrailingPadding,t.oneofs&&(s._imageTrailingPadding="imageTrailingPadding")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression"},i})(),r})(),n.AIRichResponseMapMetadata=(function(){function r(i){if(this.annotations=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.centerLatitude=e.double();break}case 2:{s.centerLongitude=e.double();break}case 3:{s.latitudeDelta=e.double();break}case 4:{s.longitudeDelta=e.double();break}case 5:{s.annotations&&s.annotations.length||(s.annotations=[]),s.annotations.push(E.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation.decode(e,e.uint32()));break}case 6:{s.showInfoList=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseMapMetadata)return e;var a=new E.proto.AIRichResponseMapMetadata;if(e.centerLatitude!=null&&(a.centerLatitude=Number(e.centerLatitude)),e.centerLongitude!=null&&(a.centerLongitude=Number(e.centerLongitude)),e.latitudeDelta!=null&&(a.latitudeDelta=Number(e.latitudeDelta)),e.longitudeDelta!=null&&(a.longitudeDelta=Number(e.longitudeDelta)),e.annotations){if(!Array.isArray(e.annotations))throw TypeError(".proto.AIRichResponseMapMetadata.annotations: array expected");a.annotations=[];for(var A=0;A>>3){case 1:{c.annotationNumber=A.uint32();break}case 2:{c.latitude=A.double();break}case 3:{c.longitude=A.double();break}case 4:{c.title=A.string();break}case 5:{c.body=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation)return A;var t=new E.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation;return A.annotationNumber!=null&&(t.annotationNumber=A.annotationNumber>>>0),A.latitude!=null&&(t.latitude=Number(A.latitude)),A.longitude!=null&&(t.longitude=Number(A.longitude)),A.title!=null&&(t.title=String(A.title)),A.body!=null&&(t.body=String(A.body)),t},i.toObject=function(A,t){t||(t={});var s={};return A.annotationNumber!=null&&A.hasOwnProperty("annotationNumber")&&(s.annotationNumber=A.annotationNumber,t.oneofs&&(s._annotationNumber="annotationNumber")),A.latitude!=null&&A.hasOwnProperty("latitude")&&(s.latitude=t.json&&!isFinite(A.latitude)?String(A.latitude):A.latitude,t.oneofs&&(s._latitude="latitude")),A.longitude!=null&&A.hasOwnProperty("longitude")&&(s.longitude=t.json&&!isFinite(A.longitude)?String(A.longitude):A.longitude,t.oneofs&&(s._longitude="longitude")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,t.oneofs&&(s._body="body")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation"},i})(),r})(),n.AIRichResponseMessage=(function(){function r(i){if(this.submessages=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageType=e.int32();break}case 2:{s.submessages&&s.submessages.length||(s.submessages=[]),s.submessages.push(E.proto.AIRichResponseSubMessage.decode(e,e.uint32()));break}case 3:{s.unifiedResponse=E.proto.AIRichResponseUnifiedResponse.decode(e,e.uint32());break}case 4:{s.contextInfo=E.proto.ContextInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseMessage)return e;var a=new E.proto.AIRichResponseMessage;switch(e.messageType){default:if(typeof e.messageType=="number"){a.messageType=e.messageType;break}break;case"AI_RICH_RESPONSE_TYPE_UNKNOWN":case 0:a.messageType=0;break;case"AI_RICH_RESPONSE_TYPE_STANDARD":case 1:a.messageType=1;break}if(e.submessages){if(!Array.isArray(e.submessages))throw TypeError(".proto.AIRichResponseMessage.submessages: array expected");a.submessages=[];for(var A=0;A>>3){case 1:{s.messageType=e.int32();break}case 2:{s.gridImageMetadata=E.proto.AIRichResponseGridImageMetadata.decode(e,e.uint32());break}case 3:{s.messageText=e.string();break}case 4:{s.imageMetadata=E.proto.AIRichResponseInlineImageMetadata.decode(e,e.uint32());break}case 5:{s.codeMetadata=E.proto.AIRichResponseCodeMetadata.decode(e,e.uint32());break}case 6:{s.tableMetadata=E.proto.AIRichResponseTableMetadata.decode(e,e.uint32());break}case 7:{s.dynamicMetadata=E.proto.AIRichResponseDynamicMetadata.decode(e,e.uint32());break}case 8:{s.latexMetadata=E.proto.AIRichResponseLatexMetadata.decode(e,e.uint32());break}case 9:{s.mapMetadata=E.proto.AIRichResponseMapMetadata.decode(e,e.uint32());break}case 10:{s.contentItemsMetadata=E.proto.AIRichResponseContentItemsMetadata.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseSubMessage)return e;var a=new E.proto.AIRichResponseSubMessage;switch(e.messageType){default:if(typeof e.messageType=="number"){a.messageType=e.messageType;break}break;case"AI_RICH_RESPONSE_UNKNOWN":case 0:a.messageType=0;break;case"AI_RICH_RESPONSE_GRID_IMAGE":case 1:a.messageType=1;break;case"AI_RICH_RESPONSE_TEXT":case 2:a.messageType=2;break;case"AI_RICH_RESPONSE_INLINE_IMAGE":case 3:a.messageType=3;break;case"AI_RICH_RESPONSE_TABLE":case 4:a.messageType=4;break;case"AI_RICH_RESPONSE_CODE":case 5:a.messageType=5;break;case"AI_RICH_RESPONSE_DYNAMIC":case 6:a.messageType=6;break;case"AI_RICH_RESPONSE_MAP":case 7:a.messageType=7;break;case"AI_RICH_RESPONSE_LATEX":case 8:a.messageType=8;break;case"AI_RICH_RESPONSE_CONTENT_ITEMS":case 9:a.messageType=9;break}if(e.gridImageMetadata!=null){if(typeof e.gridImageMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.gridImageMetadata: object expected");a.gridImageMetadata=E.proto.AIRichResponseGridImageMetadata.fromObject(e.gridImageMetadata)}if(e.messageText!=null&&(a.messageText=String(e.messageText)),e.imageMetadata!=null){if(typeof e.imageMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.imageMetadata: object expected");a.imageMetadata=E.proto.AIRichResponseInlineImageMetadata.fromObject(e.imageMetadata)}if(e.codeMetadata!=null){if(typeof e.codeMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.codeMetadata: object expected");a.codeMetadata=E.proto.AIRichResponseCodeMetadata.fromObject(e.codeMetadata)}if(e.tableMetadata!=null){if(typeof e.tableMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.tableMetadata: object expected");a.tableMetadata=E.proto.AIRichResponseTableMetadata.fromObject(e.tableMetadata)}if(e.dynamicMetadata!=null){if(typeof e.dynamicMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.dynamicMetadata: object expected");a.dynamicMetadata=E.proto.AIRichResponseDynamicMetadata.fromObject(e.dynamicMetadata)}if(e.latexMetadata!=null){if(typeof e.latexMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.latexMetadata: object expected");a.latexMetadata=E.proto.AIRichResponseLatexMetadata.fromObject(e.latexMetadata)}if(e.mapMetadata!=null){if(typeof e.mapMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.mapMetadata: object expected");a.mapMetadata=E.proto.AIRichResponseMapMetadata.fromObject(e.mapMetadata)}if(e.contentItemsMetadata!=null){if(typeof e.contentItemsMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.contentItemsMetadata: object expected");a.contentItemsMetadata=E.proto.AIRichResponseContentItemsMetadata.fromObject(e.contentItemsMetadata)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.messageType!=null&&e.hasOwnProperty("messageType")&&(A.messageType=a.enums===String?E.proto.AIRichResponseSubMessageType[e.messageType]===void 0?e.messageType:E.proto.AIRichResponseSubMessageType[e.messageType]:e.messageType,a.oneofs&&(A._messageType="messageType")),e.gridImageMetadata!=null&&e.hasOwnProperty("gridImageMetadata")&&(A.gridImageMetadata=E.proto.AIRichResponseGridImageMetadata.toObject(e.gridImageMetadata,a),a.oneofs&&(A._gridImageMetadata="gridImageMetadata")),e.messageText!=null&&e.hasOwnProperty("messageText")&&(A.messageText=e.messageText,a.oneofs&&(A._messageText="messageText")),e.imageMetadata!=null&&e.hasOwnProperty("imageMetadata")&&(A.imageMetadata=E.proto.AIRichResponseInlineImageMetadata.toObject(e.imageMetadata,a),a.oneofs&&(A._imageMetadata="imageMetadata")),e.codeMetadata!=null&&e.hasOwnProperty("codeMetadata")&&(A.codeMetadata=E.proto.AIRichResponseCodeMetadata.toObject(e.codeMetadata,a),a.oneofs&&(A._codeMetadata="codeMetadata")),e.tableMetadata!=null&&e.hasOwnProperty("tableMetadata")&&(A.tableMetadata=E.proto.AIRichResponseTableMetadata.toObject(e.tableMetadata,a),a.oneofs&&(A._tableMetadata="tableMetadata")),e.dynamicMetadata!=null&&e.hasOwnProperty("dynamicMetadata")&&(A.dynamicMetadata=E.proto.AIRichResponseDynamicMetadata.toObject(e.dynamicMetadata,a),a.oneofs&&(A._dynamicMetadata="dynamicMetadata")),e.latexMetadata!=null&&e.hasOwnProperty("latexMetadata")&&(A.latexMetadata=E.proto.AIRichResponseLatexMetadata.toObject(e.latexMetadata,a),a.oneofs&&(A._latexMetadata="latexMetadata")),e.mapMetadata!=null&&e.hasOwnProperty("mapMetadata")&&(A.mapMetadata=E.proto.AIRichResponseMapMetadata.toObject(e.mapMetadata,a),a.oneofs&&(A._mapMetadata="mapMetadata")),e.contentItemsMetadata!=null&&e.hasOwnProperty("contentItemsMetadata")&&(A.contentItemsMetadata=E.proto.AIRichResponseContentItemsMetadata.toObject(e.contentItemsMetadata,a),a.oneofs&&(A._contentItemsMetadata="contentItemsMetadata")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseSubMessage"},r})(),n.AIRichResponseSubMessageType=(function(){let r={},o=Object.create(r);return o[r[0]="AI_RICH_RESPONSE_UNKNOWN"]=0,o[r[1]="AI_RICH_RESPONSE_GRID_IMAGE"]=1,o[r[2]="AI_RICH_RESPONSE_TEXT"]=2,o[r[3]="AI_RICH_RESPONSE_INLINE_IMAGE"]=3,o[r[4]="AI_RICH_RESPONSE_TABLE"]=4,o[r[5]="AI_RICH_RESPONSE_CODE"]=5,o[r[6]="AI_RICH_RESPONSE_DYNAMIC"]=6,o[r[7]="AI_RICH_RESPONSE_MAP"]=7,o[r[8]="AI_RICH_RESPONSE_LATEX"]=8,o[r[9]="AI_RICH_RESPONSE_CONTENT_ITEMS"]=9,o})(),n.AIRichResponseTableMetadata=(function(){function r(i){if(this.rows=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rows&&s.rows.length||(s.rows=[]),s.rows.push(E.proto.AIRichResponseTableMetadata.AIRichResponseTableRow.decode(e,e.uint32()));break}case 2:{s.title=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseTableMetadata)return e;var a=new E.proto.AIRichResponseTableMetadata;if(e.rows){if(!Array.isArray(e.rows))throw TypeError(".proto.AIRichResponseTableMetadata.rows: array expected");a.rows=[];for(var A=0;A>>3){case 1:{c.items&&c.items.length||(c.items=[]),c.items.push(A.string());break}case 2:{c.isHeading=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIRichResponseTableMetadata.AIRichResponseTableRow)return A;var t=new E.proto.AIRichResponseTableMetadata.AIRichResponseTableRow;if(A.items){if(!Array.isArray(A.items))throw TypeError(".proto.AIRichResponseTableMetadata.AIRichResponseTableRow.items: array expected");t.items=[];for(var s=0;s>>3){case 1:{s.data=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIRichResponseUnifiedResponse)return e;var a=new E.proto.AIRichResponseUnifiedResponse;return e.data!=null&&(typeof e.data=="string"?I.base64.decode(e.data,a.data=I.newBuffer(I.base64.length(e.data)),0):e.data.length>=0&&(a.data=e.data)),a},r.toObject=function(e,a){a||(a={});var A={};return e.data!=null&&e.hasOwnProperty("data")&&(A.data=a.bytes===String?I.base64.encode(e.data,0,e.data.length):a.bytes===Array?Array.prototype.slice.call(e.data):e.data,a.oneofs&&(A._data="data")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseUnifiedResponse"},r})(),n.AIThreadInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.serverInfo=E.proto.AIThreadInfo.AIThreadServerInfo.decode(e,e.uint32());break}case 2:{s.clientInfo=E.proto.AIThreadInfo.AIThreadClientInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AIThreadInfo)return e;var a=new E.proto.AIThreadInfo;if(e.serverInfo!=null){if(typeof e.serverInfo!="object")throw TypeError(".proto.AIThreadInfo.serverInfo: object expected");a.serverInfo=E.proto.AIThreadInfo.AIThreadServerInfo.fromObject(e.serverInfo)}if(e.clientInfo!=null){if(typeof e.clientInfo!="object")throw TypeError(".proto.AIThreadInfo.clientInfo: object expected");a.clientInfo=E.proto.AIThreadInfo.AIThreadClientInfo.fromObject(e.clientInfo)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.serverInfo!=null&&e.hasOwnProperty("serverInfo")&&(A.serverInfo=E.proto.AIThreadInfo.AIThreadServerInfo.toObject(e.serverInfo,a),a.oneofs&&(A._serverInfo="serverInfo")),e.clientInfo!=null&&e.hasOwnProperty("clientInfo")&&(A.clientInfo=E.proto.AIThreadInfo.AIThreadClientInfo.toObject(e.clientInfo,a),a.oneofs&&(A._clientInfo="clientInfo")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIThreadInfo"},r.AIThreadClientInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.type=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIThreadInfo.AIThreadClientInfo)return A;var t=new E.proto.AIThreadInfo.AIThreadClientInfo;switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"UNKNOWN":case 0:t.type=0;break;case"DEFAULT":case 1:t.type=1;break;case"INCOGNITO":case 2:t.type=2;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.AIThreadInfo.AIThreadClientInfo.AIThreadType[A.type]===void 0?A.type:E.proto.AIThreadInfo.AIThreadClientInfo.AIThreadType[A.type]:A.type,t.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIThreadInfo.AIThreadClientInfo"},i.AIThreadType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="DEFAULT"]=1,A[a[2]="INCOGNITO"]=2,A})(),i})(),r.AIThreadServerInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.title=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.AIThreadInfo.AIThreadServerInfo)return A;var t=new E.proto.AIThreadInfo.AIThreadServerInfo;return A.title!=null&&(t.title=String(A.title)),t},i.toObject=function(A,t){t||(t={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIThreadInfo.AIThreadServerInfo"},i})(),r})(),n.Account=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lid=e.string();break}case 2:{s.username=e.string();break}case 3:{s.countryCode=e.string();break}case 4:{s.isUsernameDeleted=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Account)return e;var a=new E.proto.Account;return e.lid!=null&&(a.lid=String(e.lid)),e.username!=null&&(a.username=String(e.username)),e.countryCode!=null&&(a.countryCode=String(e.countryCode)),e.isUsernameDeleted!=null&&(a.isUsernameDeleted=!!e.isUsernameDeleted),a},r.toObject=function(e,a){a||(a={});var A={};return e.lid!=null&&e.hasOwnProperty("lid")&&(A.lid=e.lid,a.oneofs&&(A._lid="lid")),e.username!=null&&e.hasOwnProperty("username")&&(A.username=e.username,a.oneofs&&(A._username="username")),e.countryCode!=null&&e.hasOwnProperty("countryCode")&&(A.countryCode=e.countryCode,a.oneofs&&(A._countryCode="countryCode")),e.isUsernameDeleted!=null&&e.hasOwnProperty("isUsernameDeleted")&&(A.isUsernameDeleted=e.isUsernameDeleted,a.oneofs&&(A._isUsernameDeleted="isUsernameDeleted")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Account"},r})(),n.ActionLink=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.url=e.string();break}case 2:{s.buttonTitle=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ActionLink)return e;var a=new E.proto.ActionLink;return e.url!=null&&(a.url=String(e.url)),e.buttonTitle!=null&&(a.buttonTitle=String(e.buttonTitle)),a},r.toObject=function(e,a){a||(a={});var A={};return e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.buttonTitle!=null&&e.hasOwnProperty("buttonTitle")&&(A.buttonTitle=e.buttonTitle,a.oneofs&&(A._buttonTitle="buttonTitle")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ActionLink"},r})(),n.AutoDownloadSettings=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.downloadImages=e.bool();break}case 2:{s.downloadAudio=e.bool();break}case 3:{s.downloadVideo=e.bool();break}case 4:{s.downloadDocuments=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AutoDownloadSettings)return e;var a=new E.proto.AutoDownloadSettings;return e.downloadImages!=null&&(a.downloadImages=!!e.downloadImages),e.downloadAudio!=null&&(a.downloadAudio=!!e.downloadAudio),e.downloadVideo!=null&&(a.downloadVideo=!!e.downloadVideo),e.downloadDocuments!=null&&(a.downloadDocuments=!!e.downloadDocuments),a},r.toObject=function(e,a){a||(a={});var A={};return e.downloadImages!=null&&e.hasOwnProperty("downloadImages")&&(A.downloadImages=e.downloadImages,a.oneofs&&(A._downloadImages="downloadImages")),e.downloadAudio!=null&&e.hasOwnProperty("downloadAudio")&&(A.downloadAudio=e.downloadAudio,a.oneofs&&(A._downloadAudio="downloadAudio")),e.downloadVideo!=null&&e.hasOwnProperty("downloadVideo")&&(A.downloadVideo=e.downloadVideo,a.oneofs&&(A._downloadVideo="downloadVideo")),e.downloadDocuments!=null&&e.hasOwnProperty("downloadDocuments")&&(A.downloadDocuments=e.downloadDocuments,a.oneofs&&(A._downloadDocuments="downloadDocuments")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AutoDownloadSettings"},r})(),n.AvatarUserSettings=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.fbid=e.string();break}case 2:{s.password=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.AvatarUserSettings)return e;var a=new E.proto.AvatarUserSettings;return e.fbid!=null&&(a.fbid=String(e.fbid)),e.password!=null&&(a.password=String(e.password)),a},r.toObject=function(e,a){a||(a={});var A={};return e.fbid!=null&&e.hasOwnProperty("fbid")&&(A.fbid=e.fbid,a.oneofs&&(A._fbid="fbid")),e.password!=null&&e.hasOwnProperty("password")&&(A.password=e.password,a.oneofs&&(A._password="password")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AvatarUserSettings"},r})(),n.BizAccountLinkInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.whatsappBizAcctFbid=e.uint64();break}case 2:{s.whatsappAcctNumber=e.string();break}case 3:{s.issueTime=e.uint64();break}case 4:{s.hostStorage=e.int32();break}case 5:{s.accountType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BizAccountLinkInfo)return e;var a=new E.proto.BizAccountLinkInfo;switch(e.whatsappBizAcctFbid!=null&&(I.Long?(a.whatsappBizAcctFbid=I.Long.fromValue(e.whatsappBizAcctFbid)).unsigned=!0:typeof e.whatsappBizAcctFbid=="string"?a.whatsappBizAcctFbid=parseInt(e.whatsappBizAcctFbid,10):typeof e.whatsappBizAcctFbid=="number"?a.whatsappBizAcctFbid=e.whatsappBizAcctFbid:typeof e.whatsappBizAcctFbid=="object"&&(a.whatsappBizAcctFbid=new I.LongBits(e.whatsappBizAcctFbid.low>>>0,e.whatsappBizAcctFbid.high>>>0).toNumber(!0))),e.whatsappAcctNumber!=null&&(a.whatsappAcctNumber=String(e.whatsappAcctNumber)),e.issueTime!=null&&(I.Long?(a.issueTime=I.Long.fromValue(e.issueTime)).unsigned=!0:typeof e.issueTime=="string"?a.issueTime=parseInt(e.issueTime,10):typeof e.issueTime=="number"?a.issueTime=e.issueTime:typeof e.issueTime=="object"&&(a.issueTime=new I.LongBits(e.issueTime.low>>>0,e.issueTime.high>>>0).toNumber(!0))),e.hostStorage){default:if(typeof e.hostStorage=="number"){a.hostStorage=e.hostStorage;break}break;case"ON_PREMISE":case 0:a.hostStorage=0;break;case"FACEBOOK":case 1:a.hostStorage=1;break}switch(e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"ENTERPRISE":case 0:a.accountType=0;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.whatsappBizAcctFbid!=null&&e.hasOwnProperty("whatsappBizAcctFbid")&&(typeof e.whatsappBizAcctFbid=="number"?A.whatsappBizAcctFbid=a.longs===String?String(e.whatsappBizAcctFbid):e.whatsappBizAcctFbid:A.whatsappBizAcctFbid=a.longs===String?re(e.whatsappBizAcctFbid,!0):a.longs===Number?ae(e.whatsappBizAcctFbid,!0):e.whatsappBizAcctFbid,a.oneofs&&(A._whatsappBizAcctFbid="whatsappBizAcctFbid")),e.whatsappAcctNumber!=null&&e.hasOwnProperty("whatsappAcctNumber")&&(A.whatsappAcctNumber=e.whatsappAcctNumber,a.oneofs&&(A._whatsappAcctNumber="whatsappAcctNumber")),e.issueTime!=null&&e.hasOwnProperty("issueTime")&&(typeof e.issueTime=="number"?A.issueTime=a.longs===String?String(e.issueTime):e.issueTime:A.issueTime=a.longs===String?re(e.issueTime,!0):a.longs===Number?ae(e.issueTime,!0):e.issueTime,a.oneofs&&(A._issueTime="issueTime")),e.hostStorage!=null&&e.hasOwnProperty("hostStorage")&&(A.hostStorage=a.enums===String?E.proto.BizAccountLinkInfo.HostStorageType[e.hostStorage]===void 0?e.hostStorage:E.proto.BizAccountLinkInfo.HostStorageType[e.hostStorage]:e.hostStorage,a.oneofs&&(A._hostStorage="hostStorage")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?E.proto.BizAccountLinkInfo.AccountType[e.accountType]===void 0?e.accountType:E.proto.BizAccountLinkInfo.AccountType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizAccountLinkInfo"},r.AccountType=(function(){let i={},e=Object.create(i);return e[i[0]="ENTERPRISE"]=0,e})(),r.HostStorageType=(function(){let i={},e=Object.create(i);return e[i[0]="ON_PREMISE"]=0,e[i[1]="FACEBOOK"]=1,e})(),r})(),n.BizAccountPayload=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.vnameCert=E.proto.VerifiedNameCertificate.decode(e,e.uint32());break}case 2:{s.bizAcctLinkInfo=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BizAccountPayload)return e;var a=new E.proto.BizAccountPayload;if(e.vnameCert!=null){if(typeof e.vnameCert!="object")throw TypeError(".proto.BizAccountPayload.vnameCert: object expected");a.vnameCert=E.proto.VerifiedNameCertificate.fromObject(e.vnameCert)}return e.bizAcctLinkInfo!=null&&(typeof e.bizAcctLinkInfo=="string"?I.base64.decode(e.bizAcctLinkInfo,a.bizAcctLinkInfo=I.newBuffer(I.base64.length(e.bizAcctLinkInfo)),0):e.bizAcctLinkInfo.length>=0&&(a.bizAcctLinkInfo=e.bizAcctLinkInfo)),a},r.toObject=function(e,a){a||(a={});var A={};return e.vnameCert!=null&&e.hasOwnProperty("vnameCert")&&(A.vnameCert=E.proto.VerifiedNameCertificate.toObject(e.vnameCert,a),a.oneofs&&(A._vnameCert="vnameCert")),e.bizAcctLinkInfo!=null&&e.hasOwnProperty("bizAcctLinkInfo")&&(A.bizAcctLinkInfo=a.bytes===String?I.base64.encode(e.bizAcctLinkInfo,0,e.bizAcctLinkInfo.length):a.bytes===Array?Array.prototype.slice.call(e.bizAcctLinkInfo):e.bizAcctLinkInfo,a.oneofs&&(A._bizAcctLinkInfo="bizAcctLinkInfo")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizAccountPayload"},r})(),n.BizIdentityInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.vlevel=e.int32();break}case 2:{s.vnameCert=E.proto.VerifiedNameCertificate.decode(e,e.uint32());break}case 3:{s.signed=e.bool();break}case 4:{s.revoked=e.bool();break}case 5:{s.hostStorage=e.int32();break}case 6:{s.actualActors=e.int32();break}case 7:{s.privacyModeTs=e.uint64();break}case 8:{s.featureControls=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BizIdentityInfo)return e;var a=new E.proto.BizIdentityInfo;switch(e.vlevel){default:if(typeof e.vlevel=="number"){a.vlevel=e.vlevel;break}break;case"UNKNOWN":case 0:a.vlevel=0;break;case"LOW":case 1:a.vlevel=1;break;case"HIGH":case 2:a.vlevel=2;break}if(e.vnameCert!=null){if(typeof e.vnameCert!="object")throw TypeError(".proto.BizIdentityInfo.vnameCert: object expected");a.vnameCert=E.proto.VerifiedNameCertificate.fromObject(e.vnameCert)}switch(e.signed!=null&&(a.signed=!!e.signed),e.revoked!=null&&(a.revoked=!!e.revoked),e.hostStorage){default:if(typeof e.hostStorage=="number"){a.hostStorage=e.hostStorage;break}break;case"ON_PREMISE":case 0:a.hostStorage=0;break;case"FACEBOOK":case 1:a.hostStorage=1;break}switch(e.actualActors){default:if(typeof e.actualActors=="number"){a.actualActors=e.actualActors;break}break;case"SELF":case 0:a.actualActors=0;break;case"BSP":case 1:a.actualActors=1;break}return e.privacyModeTs!=null&&(I.Long?(a.privacyModeTs=I.Long.fromValue(e.privacyModeTs)).unsigned=!0:typeof e.privacyModeTs=="string"?a.privacyModeTs=parseInt(e.privacyModeTs,10):typeof e.privacyModeTs=="number"?a.privacyModeTs=e.privacyModeTs:typeof e.privacyModeTs=="object"&&(a.privacyModeTs=new I.LongBits(e.privacyModeTs.low>>>0,e.privacyModeTs.high>>>0).toNumber(!0))),e.featureControls!=null&&(I.Long?(a.featureControls=I.Long.fromValue(e.featureControls)).unsigned=!0:typeof e.featureControls=="string"?a.featureControls=parseInt(e.featureControls,10):typeof e.featureControls=="number"?a.featureControls=e.featureControls:typeof e.featureControls=="object"&&(a.featureControls=new I.LongBits(e.featureControls.low>>>0,e.featureControls.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};return e.vlevel!=null&&e.hasOwnProperty("vlevel")&&(A.vlevel=a.enums===String?E.proto.BizIdentityInfo.VerifiedLevelValue[e.vlevel]===void 0?e.vlevel:E.proto.BizIdentityInfo.VerifiedLevelValue[e.vlevel]:e.vlevel,a.oneofs&&(A._vlevel="vlevel")),e.vnameCert!=null&&e.hasOwnProperty("vnameCert")&&(A.vnameCert=E.proto.VerifiedNameCertificate.toObject(e.vnameCert,a),a.oneofs&&(A._vnameCert="vnameCert")),e.signed!=null&&e.hasOwnProperty("signed")&&(A.signed=e.signed,a.oneofs&&(A._signed="signed")),e.revoked!=null&&e.hasOwnProperty("revoked")&&(A.revoked=e.revoked,a.oneofs&&(A._revoked="revoked")),e.hostStorage!=null&&e.hasOwnProperty("hostStorage")&&(A.hostStorage=a.enums===String?E.proto.BizIdentityInfo.HostStorageType[e.hostStorage]===void 0?e.hostStorage:E.proto.BizIdentityInfo.HostStorageType[e.hostStorage]:e.hostStorage,a.oneofs&&(A._hostStorage="hostStorage")),e.actualActors!=null&&e.hasOwnProperty("actualActors")&&(A.actualActors=a.enums===String?E.proto.BizIdentityInfo.ActualActorsType[e.actualActors]===void 0?e.actualActors:E.proto.BizIdentityInfo.ActualActorsType[e.actualActors]:e.actualActors,a.oneofs&&(A._actualActors="actualActors")),e.privacyModeTs!=null&&e.hasOwnProperty("privacyModeTs")&&(typeof e.privacyModeTs=="number"?A.privacyModeTs=a.longs===String?String(e.privacyModeTs):e.privacyModeTs:A.privacyModeTs=a.longs===String?re(e.privacyModeTs,!0):a.longs===Number?ae(e.privacyModeTs,!0):e.privacyModeTs,a.oneofs&&(A._privacyModeTs="privacyModeTs")),e.featureControls!=null&&e.hasOwnProperty("featureControls")&&(typeof e.featureControls=="number"?A.featureControls=a.longs===String?String(e.featureControls):e.featureControls:A.featureControls=a.longs===String?re(e.featureControls,!0):a.longs===Number?ae(e.featureControls,!0):e.featureControls,a.oneofs&&(A._featureControls="featureControls")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizIdentityInfo"},r.ActualActorsType=(function(){let i={},e=Object.create(i);return e[i[0]="SELF"]=0,e[i[1]="BSP"]=1,e})(),r.HostStorageType=(function(){let i={},e=Object.create(i);return e[i[0]="ON_PREMISE"]=0,e[i[1]="FACEBOOK"]=1,e})(),r.VerifiedLevelValue=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="LOW"]=1,e[i[2]="HIGH"]=2,e})(),r})(),n.BotAgeCollectionMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.ageCollectionEligible=e.bool();break}case 2:{s.shouldTriggerAgeCollectionOnClient=e.bool();break}case 3:{s.ageCollectionType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotAgeCollectionMetadata)return e;var a=new E.proto.BotAgeCollectionMetadata;switch(e.ageCollectionEligible!=null&&(a.ageCollectionEligible=!!e.ageCollectionEligible),e.shouldTriggerAgeCollectionOnClient!=null&&(a.shouldTriggerAgeCollectionOnClient=!!e.shouldTriggerAgeCollectionOnClient),e.ageCollectionType){default:if(typeof e.ageCollectionType=="number"){a.ageCollectionType=e.ageCollectionType;break}break;case"O18_BINARY":case 0:a.ageCollectionType=0;break;case"WAFFLE":case 1:a.ageCollectionType=1;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.ageCollectionEligible!=null&&e.hasOwnProperty("ageCollectionEligible")&&(A.ageCollectionEligible=e.ageCollectionEligible,a.oneofs&&(A._ageCollectionEligible="ageCollectionEligible")),e.shouldTriggerAgeCollectionOnClient!=null&&e.hasOwnProperty("shouldTriggerAgeCollectionOnClient")&&(A.shouldTriggerAgeCollectionOnClient=e.shouldTriggerAgeCollectionOnClient,a.oneofs&&(A._shouldTriggerAgeCollectionOnClient="shouldTriggerAgeCollectionOnClient")),e.ageCollectionType!=null&&e.hasOwnProperty("ageCollectionType")&&(A.ageCollectionType=a.enums===String?E.proto.BotAgeCollectionMetadata.AgeCollectionType[e.ageCollectionType]===void 0?e.ageCollectionType:E.proto.BotAgeCollectionMetadata.AgeCollectionType[e.ageCollectionType]:e.ageCollectionType,a.oneofs&&(A._ageCollectionType="ageCollectionType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotAgeCollectionMetadata"},r.AgeCollectionType=(function(){let i={},e=Object.create(i);return e[i[0]="O18_BINARY"]=0,e[i[1]="WAFFLE"]=1,e})(),r})(),n.BotAvatarMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sentiment=e.uint32();break}case 2:{s.behaviorGraph=e.string();break}case 3:{s.action=e.uint32();break}case 4:{s.intensity=e.uint32();break}case 5:{s.wordCount=e.uint32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotAvatarMetadata)return e;var a=new E.proto.BotAvatarMetadata;return e.sentiment!=null&&(a.sentiment=e.sentiment>>>0),e.behaviorGraph!=null&&(a.behaviorGraph=String(e.behaviorGraph)),e.action!=null&&(a.action=e.action>>>0),e.intensity!=null&&(a.intensity=e.intensity>>>0),e.wordCount!=null&&(a.wordCount=e.wordCount>>>0),a},r.toObject=function(e,a){a||(a={});var A={};return e.sentiment!=null&&e.hasOwnProperty("sentiment")&&(A.sentiment=e.sentiment,a.oneofs&&(A._sentiment="sentiment")),e.behaviorGraph!=null&&e.hasOwnProperty("behaviorGraph")&&(A.behaviorGraph=e.behaviorGraph,a.oneofs&&(A._behaviorGraph="behaviorGraph")),e.action!=null&&e.hasOwnProperty("action")&&(A.action=e.action,a.oneofs&&(A._action="action")),e.intensity!=null&&e.hasOwnProperty("intensity")&&(A.intensity=e.intensity,a.oneofs&&(A._intensity="intensity")),e.wordCount!=null&&e.hasOwnProperty("wordCount")&&(A.wordCount=e.wordCount,a.oneofs&&(A._wordCount="wordCount")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotAvatarMetadata"},r})(),n.BotCapabilityMetadata=(function(){function r(o){if(this.capabilities=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{if(t.capabilities&&t.capabilities.length||(t.capabilities=[]),(s&7)===2)for(var g=i.uint32()+i.pos;i.pos>>3){case 1:{s.messageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.kind=e.int32();break}case 3:{s.text=e.string();break}case 4:{s.kindNegative=e.uint64();break}case 5:{s.kindPositive=e.uint64();break}case 6:{s.kindReport=e.int32();break}case 7:{s.sideBySideSurveyMetadata=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotFeedbackMessage)return e;var a=new E.proto.BotFeedbackMessage;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.BotFeedbackMessage.messageKey: object expected");a.messageKey=E.proto.MessageKey.fromObject(e.messageKey)}switch(e.kind){default:if(typeof e.kind=="number"){a.kind=e.kind;break}break;case"BOT_FEEDBACK_POSITIVE":case 0:a.kind=0;break;case"BOT_FEEDBACK_NEGATIVE_GENERIC":case 1:a.kind=1;break;case"BOT_FEEDBACK_NEGATIVE_HELPFUL":case 2:a.kind=2;break;case"BOT_FEEDBACK_NEGATIVE_INTERESTING":case 3:a.kind=3;break;case"BOT_FEEDBACK_NEGATIVE_ACCURATE":case 4:a.kind=4;break;case"BOT_FEEDBACK_NEGATIVE_SAFE":case 5:a.kind=5;break;case"BOT_FEEDBACK_NEGATIVE_OTHER":case 6:a.kind=6;break;case"BOT_FEEDBACK_NEGATIVE_REFUSED":case 7:a.kind=7;break;case"BOT_FEEDBACK_NEGATIVE_NOT_VISUALLY_APPEALING":case 8:a.kind=8;break;case"BOT_FEEDBACK_NEGATIVE_NOT_RELEVANT_TO_TEXT":case 9:a.kind=9;break;case"BOT_FEEDBACK_NEGATIVE_PERSONALIZED":case 10:a.kind=10;break;case"BOT_FEEDBACK_NEGATIVE_CLARITY":case 11:a.kind=11;break;case"BOT_FEEDBACK_NEGATIVE_DOESNT_LOOK_LIKE_THE_PERSON":case 12:a.kind=12;break;case"BOT_FEEDBACK_NEGATIVE_HALLUCINATION_INTERNAL_ONLY":case 13:a.kind=13;break;case"BOT_FEEDBACK_NEGATIVE":case 14:a.kind=14;break}switch(e.text!=null&&(a.text=String(e.text)),e.kindNegative!=null&&(I.Long?(a.kindNegative=I.Long.fromValue(e.kindNegative)).unsigned=!0:typeof e.kindNegative=="string"?a.kindNegative=parseInt(e.kindNegative,10):typeof e.kindNegative=="number"?a.kindNegative=e.kindNegative:typeof e.kindNegative=="object"&&(a.kindNegative=new I.LongBits(e.kindNegative.low>>>0,e.kindNegative.high>>>0).toNumber(!0))),e.kindPositive!=null&&(I.Long?(a.kindPositive=I.Long.fromValue(e.kindPositive)).unsigned=!0:typeof e.kindPositive=="string"?a.kindPositive=parseInt(e.kindPositive,10):typeof e.kindPositive=="number"?a.kindPositive=e.kindPositive:typeof e.kindPositive=="object"&&(a.kindPositive=new I.LongBits(e.kindPositive.low>>>0,e.kindPositive.high>>>0).toNumber(!0))),e.kindReport){default:if(typeof e.kindReport=="number"){a.kindReport=e.kindReport;break}break;case"NONE":case 0:a.kindReport=0;break;case"GENERIC":case 1:a.kindReport=1;break}if(e.sideBySideSurveyMetadata!=null){if(typeof e.sideBySideSurveyMetadata!="object")throw TypeError(".proto.BotFeedbackMessage.sideBySideSurveyMetadata: object expected");a.sideBySideSurveyMetadata=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.fromObject(e.sideBySideSurveyMetadata)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=E.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.kind!=null&&e.hasOwnProperty("kind")&&(A.kind=a.enums===String?E.proto.BotFeedbackMessage.BotFeedbackKind[e.kind]===void 0?e.kind:E.proto.BotFeedbackMessage.BotFeedbackKind[e.kind]:e.kind,a.oneofs&&(A._kind="kind")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),e.kindNegative!=null&&e.hasOwnProperty("kindNegative")&&(typeof e.kindNegative=="number"?A.kindNegative=a.longs===String?String(e.kindNegative):e.kindNegative:A.kindNegative=a.longs===String?re(e.kindNegative,!0):a.longs===Number?ae(e.kindNegative,!0):e.kindNegative,a.oneofs&&(A._kindNegative="kindNegative")),e.kindPositive!=null&&e.hasOwnProperty("kindPositive")&&(typeof e.kindPositive=="number"?A.kindPositive=a.longs===String?String(e.kindPositive):e.kindPositive:A.kindPositive=a.longs===String?re(e.kindPositive,!0):a.longs===Number?ae(e.kindPositive,!0):e.kindPositive,a.oneofs&&(A._kindPositive="kindPositive")),e.kindReport!=null&&e.hasOwnProperty("kindReport")&&(A.kindReport=a.enums===String?E.proto.BotFeedbackMessage.ReportKind[e.kindReport]===void 0?e.kindReport:E.proto.BotFeedbackMessage.ReportKind[e.kindReport]:e.kindReport,a.oneofs&&(A._kindReport="kindReport")),e.sideBySideSurveyMetadata!=null&&e.hasOwnProperty("sideBySideSurveyMetadata")&&(A.sideBySideSurveyMetadata=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.toObject(e.sideBySideSurveyMetadata,a),a.oneofs&&(A._sideBySideSurveyMetadata="sideBySideSurveyMetadata")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotFeedbackMessage"},r.BotFeedbackKind=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_FEEDBACK_POSITIVE"]=0,e[i[1]="BOT_FEEDBACK_NEGATIVE_GENERIC"]=1,e[i[2]="BOT_FEEDBACK_NEGATIVE_HELPFUL"]=2,e[i[3]="BOT_FEEDBACK_NEGATIVE_INTERESTING"]=3,e[i[4]="BOT_FEEDBACK_NEGATIVE_ACCURATE"]=4,e[i[5]="BOT_FEEDBACK_NEGATIVE_SAFE"]=5,e[i[6]="BOT_FEEDBACK_NEGATIVE_OTHER"]=6,e[i[7]="BOT_FEEDBACK_NEGATIVE_REFUSED"]=7,e[i[8]="BOT_FEEDBACK_NEGATIVE_NOT_VISUALLY_APPEALING"]=8,e[i[9]="BOT_FEEDBACK_NEGATIVE_NOT_RELEVANT_TO_TEXT"]=9,e[i[10]="BOT_FEEDBACK_NEGATIVE_PERSONALIZED"]=10,e[i[11]="BOT_FEEDBACK_NEGATIVE_CLARITY"]=11,e[i[12]="BOT_FEEDBACK_NEGATIVE_DOESNT_LOOK_LIKE_THE_PERSON"]=12,e[i[13]="BOT_FEEDBACK_NEGATIVE_HALLUCINATION_INTERNAL_ONLY"]=13,e[i[14]="BOT_FEEDBACK_NEGATIVE"]=14,e})(),r.BotFeedbackKindMultipleNegative=(function(){let i={},e=Object.create(i);return e[i[1]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_GENERIC"]=1,e[i[2]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_HELPFUL"]=2,e[i[4]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_INTERESTING"]=4,e[i[8]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_ACCURATE"]=8,e[i[16]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_SAFE"]=16,e[i[32]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_OTHER"]=32,e[i[64]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_REFUSED"]=64,e[i[128]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_VISUALLY_APPEALING"]=128,e[i[256]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_RELEVANT_TO_TEXT"]=256,e})(),r.BotFeedbackKindMultiplePositive=(function(){let i={},e=Object.create(i);return e[i[1]="BOT_FEEDBACK_MULTIPLE_POSITIVE_GENERIC"]=1,e})(),r.ReportKind=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="GENERIC"]=1,e})(),r.SideBySideSurveyMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.selectedRequestId=A.string();break}case 2:{c.surveyId=A.uint32();break}case 3:{c.simonSessionFbid=A.string();break}case 4:{c.responseOtid=A.string();break}case 5:{c.responseTimestampMsString=A.string();break}case 6:{c.isSelectedResponsePrimary=A.bool();break}case 7:{c.messageIdToEdit=A.string();break}case 8:{c.analyticsData=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.decode(A,A.uint32());break}case 9:{c.metaAiAnalyticsData=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata)return A;var t=new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata;if(A.selectedRequestId!=null&&(t.selectedRequestId=String(A.selectedRequestId)),A.surveyId!=null&&(t.surveyId=A.surveyId>>>0),A.simonSessionFbid!=null&&(t.simonSessionFbid=String(A.simonSessionFbid)),A.responseOtid!=null&&(t.responseOtid=String(A.responseOtid)),A.responseTimestampMsString!=null&&(t.responseTimestampMsString=String(A.responseTimestampMsString)),A.isSelectedResponsePrimary!=null&&(t.isSelectedResponsePrimary=!!A.isSelectedResponsePrimary),A.messageIdToEdit!=null&&(t.messageIdToEdit=String(A.messageIdToEdit)),A.analyticsData!=null){if(typeof A.analyticsData!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.analyticsData: object expected");t.analyticsData=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.fromObject(A.analyticsData)}if(A.metaAiAnalyticsData!=null){if(typeof A.metaAiAnalyticsData!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.metaAiAnalyticsData: object expected");t.metaAiAnalyticsData=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.fromObject(A.metaAiAnalyticsData)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.selectedRequestId!=null&&A.hasOwnProperty("selectedRequestId")&&(s.selectedRequestId=A.selectedRequestId,t.oneofs&&(s._selectedRequestId="selectedRequestId")),A.surveyId!=null&&A.hasOwnProperty("surveyId")&&(s.surveyId=A.surveyId,t.oneofs&&(s._surveyId="surveyId")),A.simonSessionFbid!=null&&A.hasOwnProperty("simonSessionFbid")&&(s.simonSessionFbid=A.simonSessionFbid,t.oneofs&&(s._simonSessionFbid="simonSessionFbid")),A.responseOtid!=null&&A.hasOwnProperty("responseOtid")&&(s.responseOtid=A.responseOtid,t.oneofs&&(s._responseOtid="responseOtid")),A.responseTimestampMsString!=null&&A.hasOwnProperty("responseTimestampMsString")&&(s.responseTimestampMsString=A.responseTimestampMsString,t.oneofs&&(s._responseTimestampMsString="responseTimestampMsString")),A.isSelectedResponsePrimary!=null&&A.hasOwnProperty("isSelectedResponsePrimary")&&(s.isSelectedResponsePrimary=A.isSelectedResponsePrimary,t.oneofs&&(s._isSelectedResponsePrimary="isSelectedResponsePrimary")),A.messageIdToEdit!=null&&A.hasOwnProperty("messageIdToEdit")&&(s.messageIdToEdit=A.messageIdToEdit,t.oneofs&&(s._messageIdToEdit="messageIdToEdit")),A.analyticsData!=null&&A.hasOwnProperty("analyticsData")&&(s.analyticsData=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.toObject(A.analyticsData,t),t.oneofs&&(s._analyticsData="analyticsData")),A.metaAiAnalyticsData!=null&&A.hasOwnProperty("metaAiAnalyticsData")&&(s.metaAiAnalyticsData=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.toObject(A.metaAiAnalyticsData,t),t.oneofs&&(s._metaAiAnalyticsData="metaAiAnalyticsData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata"},i.SideBySideSurveyAnalyticsData=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.tessaEvent=s.string();break}case 2:{p.tessaSessionFbid=s.string();break}case 3:{p.simonSessionFbid=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData)return s;var g=new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData;return s.tessaEvent!=null&&(g.tessaEvent=String(s.tessaEvent)),s.tessaSessionFbid!=null&&(g.tessaSessionFbid=String(s.tessaSessionFbid)),s.simonSessionFbid!=null&&(g.simonSessionFbid=String(s.simonSessionFbid)),g},a.toObject=function(s,g){g||(g={});var c={};return s.tessaEvent!=null&&s.hasOwnProperty("tessaEvent")&&(c.tessaEvent=s.tessaEvent,g.oneofs&&(c._tessaEvent="tessaEvent")),s.tessaSessionFbid!=null&&s.hasOwnProperty("tessaSessionFbid")&&(c.tessaSessionFbid=s.tessaSessionFbid,g.oneofs&&(c._tessaSessionFbid="tessaSessionFbid")),s.simonSessionFbid!=null&&s.hasOwnProperty("simonSessionFbid")&&(c.simonSessionFbid=s.simonSessionFbid,g.oneofs&&(c._simonSessionFbid="simonSessionFbid")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData"},a})(),i.SidebySideSurveyMetaAiAnalyticsData=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.surveyId=s.uint32();break}case 2:{p.primaryResponseId=s.string();break}case 3:{p.testArmName=s.string();break}case 4:{p.timestampMsString=s.string();break}case 5:{p.ctaImpressionEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.decode(s,s.uint32());break}case 6:{p.ctaClickEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.decode(s,s.uint32());break}case 7:{p.cardImpressionEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.decode(s,s.uint32());break}case 8:{p.responseEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.decode(s,s.uint32());break}case 9:{p.abandonEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData)return s;var g=new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData;if(s.surveyId!=null&&(g.surveyId=s.surveyId>>>0),s.primaryResponseId!=null&&(g.primaryResponseId=String(s.primaryResponseId)),s.testArmName!=null&&(g.testArmName=String(s.testArmName)),s.timestampMsString!=null&&(g.timestampMsString=String(s.timestampMsString)),s.ctaImpressionEvent!=null){if(typeof s.ctaImpressionEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.ctaImpressionEvent: object expected");g.ctaImpressionEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.fromObject(s.ctaImpressionEvent)}if(s.ctaClickEvent!=null){if(typeof s.ctaClickEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.ctaClickEvent: object expected");g.ctaClickEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.fromObject(s.ctaClickEvent)}if(s.cardImpressionEvent!=null){if(typeof s.cardImpressionEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.cardImpressionEvent: object expected");g.cardImpressionEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.fromObject(s.cardImpressionEvent)}if(s.responseEvent!=null){if(typeof s.responseEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.responseEvent: object expected");g.responseEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.fromObject(s.responseEvent)}if(s.abandonEvent!=null){if(typeof s.abandonEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.abandonEvent: object expected");g.abandonEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.fromObject(s.abandonEvent)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.surveyId!=null&&s.hasOwnProperty("surveyId")&&(c.surveyId=s.surveyId,g.oneofs&&(c._surveyId="surveyId")),s.primaryResponseId!=null&&s.hasOwnProperty("primaryResponseId")&&(c.primaryResponseId=s.primaryResponseId,g.oneofs&&(c._primaryResponseId="primaryResponseId")),s.testArmName!=null&&s.hasOwnProperty("testArmName")&&(c.testArmName=s.testArmName,g.oneofs&&(c._testArmName="testArmName")),s.timestampMsString!=null&&s.hasOwnProperty("timestampMsString")&&(c.timestampMsString=s.timestampMsString,g.oneofs&&(c._timestampMsString="timestampMsString")),s.ctaImpressionEvent!=null&&s.hasOwnProperty("ctaImpressionEvent")&&(c.ctaImpressionEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.toObject(s.ctaImpressionEvent,g),g.oneofs&&(c._ctaImpressionEvent="ctaImpressionEvent")),s.ctaClickEvent!=null&&s.hasOwnProperty("ctaClickEvent")&&(c.ctaClickEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.toObject(s.ctaClickEvent,g),g.oneofs&&(c._ctaClickEvent="ctaClickEvent")),s.cardImpressionEvent!=null&&s.hasOwnProperty("cardImpressionEvent")&&(c.cardImpressionEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.toObject(s.cardImpressionEvent,g),g.oneofs&&(c._cardImpressionEvent="cardImpressionEvent")),s.responseEvent!=null&&s.hasOwnProperty("responseEvent")&&(c.responseEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.toObject(s.responseEvent,g),g.oneofs&&(c._responseEvent="responseEvent")),s.abandonEvent!=null&&s.hasOwnProperty("abandonEvent")&&(c.abandonEvent=E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.toObject(s.abandonEvent,g),g.oneofs&&(c._abandonEvent="abandonEvent")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData"},a.SideBySideSurveyAbandonEventData=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.abandonDwellTimeMsString=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData)return c;var l=new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData;return c.abandonDwellTimeMsString!=null&&(l.abandonDwellTimeMsString=String(c.abandonDwellTimeMsString)),l},t.toObject=function(c,l){l||(l={});var p={};return c.abandonDwellTimeMsString!=null&&c.hasOwnProperty("abandonDwellTimeMsString")&&(p.abandonDwellTimeMsString=c.abandonDwellTimeMsString,l.oneofs&&(p._abandonDwellTimeMsString="abandonDwellTimeMsString")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData"},t})(),a.SideBySideSurveyCTAClickEventData=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.isSurveyExpired=c.bool();break}case 2:{Q.clickDwellTimeMsString=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData)return c;var l=new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData;return c.isSurveyExpired!=null&&(l.isSurveyExpired=!!c.isSurveyExpired),c.clickDwellTimeMsString!=null&&(l.clickDwellTimeMsString=String(c.clickDwellTimeMsString)),l},t.toObject=function(c,l){l||(l={});var p={};return c.isSurveyExpired!=null&&c.hasOwnProperty("isSurveyExpired")&&(p.isSurveyExpired=c.isSurveyExpired,l.oneofs&&(p._isSurveyExpired="isSurveyExpired")),c.clickDwellTimeMsString!=null&&c.hasOwnProperty("clickDwellTimeMsString")&&(p.clickDwellTimeMsString=c.clickDwellTimeMsString,l.oneofs&&(p._clickDwellTimeMsString="clickDwellTimeMsString")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData"},t})(),a.SideBySideSurveyCTAImpressionEventData=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.isSurveyExpired=c.bool();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData)return c;var l=new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData;return c.isSurveyExpired!=null&&(l.isSurveyExpired=!!c.isSurveyExpired),l},t.toObject=function(c,l){l||(l={});var p={};return c.isSurveyExpired!=null&&c.hasOwnProperty("isSurveyExpired")&&(p.isSurveyExpired=c.isSurveyExpired,l.oneofs&&(p._isSurveyExpired="isSurveyExpired")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData"},t})(),a.SideBySideSurveyCardImpressionEventData=(function(){function t(s){if(s)for(var g=Object.keys(s),c=0;c>>3){default:g.skipType(Q&7);break}}return B},t.fromObject=function(g){return g instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData?g:new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData},t.toObject=function(){return{}},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(g){return g===void 0&&(g="type.googleapis.com"),g+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData"},t})(),a.SideBySideSurveyResponseEventData=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.responseDwellTimeMsString=c.string();break}case 2:{Q.selectedResponseId=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData)return c;var l=new E.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData;return c.responseDwellTimeMsString!=null&&(l.responseDwellTimeMsString=String(c.responseDwellTimeMsString)),c.selectedResponseId!=null&&(l.selectedResponseId=String(c.selectedResponseId)),l},t.toObject=function(c,l){l||(l={});var p={};return c.responseDwellTimeMsString!=null&&c.hasOwnProperty("responseDwellTimeMsString")&&(p.responseDwellTimeMsString=c.responseDwellTimeMsString,l.oneofs&&(p._responseDwellTimeMsString="responseDwellTimeMsString")),c.selectedResponseId!=null&&c.hasOwnProperty("selectedResponseId")&&(p.selectedResponseId=c.selectedResponseId,l.oneofs&&(p._selectedResponseId="selectedResponseId")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData"},t})(),a})(),i})(),r})(),n.BotImagineMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.imagineType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotImagineMetadata)return e;var a=new E.proto.BotImagineMetadata;switch(e.imagineType){default:if(typeof e.imagineType=="number"){a.imagineType=e.imagineType;break}break;case"UNKNOWN":case 0:a.imagineType=0;break;case"IMAGINE":case 1:a.imagineType=1;break;case"MEMU":case 2:a.imagineType=2;break;case"FLASH":case 3:a.imagineType=3;break;case"EDIT":case 4:a.imagineType=4;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.imagineType!=null&&e.hasOwnProperty("imagineType")&&(A.imagineType=a.enums===String?E.proto.BotImagineMetadata.ImagineType[e.imagineType]===void 0?e.imagineType:E.proto.BotImagineMetadata.ImagineType[e.imagineType]:e.imagineType,a.oneofs&&(A._imagineType="imagineType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotImagineMetadata"},r.ImagineType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="IMAGINE"]=1,e[i[2]="MEMU"]=2,e[i[3]="FLASH"]=3,e[i[4]="EDIT"]=4,e})(),r})(),n.BotLinkedAccount=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotLinkedAccount)return e;var a=new E.proto.BotLinkedAccount;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"BOT_LINKED_ACCOUNT_TYPE_1P":case 0:a.type=0;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?E.proto.BotLinkedAccount.BotLinkedAccountType[e.type]===void 0?e.type:E.proto.BotLinkedAccount.BotLinkedAccountType[e.type]:e.type,a.oneofs&&(A._type="type")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotLinkedAccount"},r.BotLinkedAccountType=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_LINKED_ACCOUNT_TYPE_1P"]=0,e})(),r})(),n.BotLinkedAccountsMetadata=(function(){function r(i){if(this.accounts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.accounts&&s.accounts.length||(s.accounts=[]),s.accounts.push(E.proto.BotLinkedAccount.decode(e,e.uint32()));break}case 2:{s.acAuthTokens=e.bytes();break}case 3:{s.acErrorCode=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotLinkedAccountsMetadata)return e;var a=new E.proto.BotLinkedAccountsMetadata;if(e.accounts){if(!Array.isArray(e.accounts))throw TypeError(".proto.BotLinkedAccountsMetadata.accounts: array expected");a.accounts=[];for(var A=0;A=0&&(a.acAuthTokens=e.acAuthTokens)),e.acErrorCode!=null&&(a.acErrorCode=e.acErrorCode|0),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.accounts=[]),e.accounts&&e.accounts.length){A.accounts=[];for(var t=0;t>>3){case 1:{s.fileSha256=e.string();break}case 2:{s.mediaKey=e.string();break}case 3:{s.fileEncSha256=e.string();break}case 4:{s.directPath=e.string();break}case 5:{s.mediaKeyTimestamp=e.int64();break}case 6:{s.mimetype=e.string();break}case 7:{s.orientationType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotMediaMetadata)return e;var a=new E.proto.BotMediaMetadata;switch(e.fileSha256!=null&&(a.fileSha256=String(e.fileSha256)),e.mediaKey!=null&&(a.mediaKey=String(e.mediaKey)),e.fileEncSha256!=null&&(a.fileEncSha256=String(e.fileEncSha256)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.mediaKeyTimestamp!=null&&(I.Long?(a.mediaKeyTimestamp=I.Long.fromValue(e.mediaKeyTimestamp)).unsigned=!1:typeof e.mediaKeyTimestamp=="string"?a.mediaKeyTimestamp=parseInt(e.mediaKeyTimestamp,10):typeof e.mediaKeyTimestamp=="number"?a.mediaKeyTimestamp=e.mediaKeyTimestamp:typeof e.mediaKeyTimestamp=="object"&&(a.mediaKeyTimestamp=new I.LongBits(e.mediaKeyTimestamp.low>>>0,e.mediaKeyTimestamp.high>>>0).toNumber())),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.orientationType){default:if(typeof e.orientationType=="number"){a.orientationType=e.orientationType;break}break;case"CENTER":case 1:a.orientationType=1;break;case"LEFT":case 2:a.orientationType=2;break;case"RIGHT":case 3:a.orientationType=3;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.mediaKeyTimestamp!=null&&e.hasOwnProperty("mediaKeyTimestamp")&&(typeof e.mediaKeyTimestamp=="number"?A.mediaKeyTimestamp=a.longs===String?String(e.mediaKeyTimestamp):e.mediaKeyTimestamp:A.mediaKeyTimestamp=a.longs===String?re(e.mediaKeyTimestamp):a.longs===Number?ae(e.mediaKeyTimestamp):e.mediaKeyTimestamp,a.oneofs&&(A._mediaKeyTimestamp="mediaKeyTimestamp")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.orientationType!=null&&e.hasOwnProperty("orientationType")&&(A.orientationType=a.enums===String?E.proto.BotMediaMetadata.OrientationType[e.orientationType]===void 0?e.orientationType:E.proto.BotMediaMetadata.OrientationType[e.orientationType]:e.orientationType,a.oneofs&&(A._orientationType="orientationType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMediaMetadata"},r.OrientationType=(function(){let i={},e=Object.create(i);return e[i[1]="CENTER"]=1,e[i[2]="LEFT"]=2,e[i[3]="RIGHT"]=3,e})(),r})(),n.BotMemoryFact=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.fact=e.string();break}case 2:{s.factId=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotMemoryFact)return e;var a=new E.proto.BotMemoryFact;return e.fact!=null&&(a.fact=String(e.fact)),e.factId!=null&&(a.factId=String(e.factId)),a},r.toObject=function(e,a){a||(a={});var A={};return e.fact!=null&&e.hasOwnProperty("fact")&&(A.fact=e.fact,a.oneofs&&(A._fact="fact")),e.factId!=null&&e.hasOwnProperty("factId")&&(A.factId=e.factId,a.oneofs&&(A._factId="factId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMemoryFact"},r})(),n.BotMemoryMetadata=(function(){function r(i){if(this.addedFacts=[],this.removedFacts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.addedFacts&&s.addedFacts.length||(s.addedFacts=[]),s.addedFacts.push(E.proto.BotMemoryFact.decode(e,e.uint32()));break}case 2:{s.removedFacts&&s.removedFacts.length||(s.removedFacts=[]),s.removedFacts.push(E.proto.BotMemoryFact.decode(e,e.uint32()));break}case 3:{s.disclaimer=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotMemoryMetadata)return e;var a=new E.proto.BotMemoryMetadata;if(e.addedFacts){if(!Array.isArray(e.addedFacts))throw TypeError(".proto.BotMemoryMetadata.addedFacts: array expected");a.addedFacts=[];for(var A=0;A>>3){case 1:{t.faceImages&&t.faceImages.length||(t.faceImages=[]),t.faceImages.push(E.proto.BotMediaMetadata.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.BotMemuMetadata)return i;var e=new E.proto.BotMemuMetadata;if(i.faceImages){if(!Array.isArray(i.faceImages))throw TypeError(".proto.BotMemuMetadata.faceImages: array expected");e.faceImages=[];for(var a=0;a>>3){case 1:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotMessageOrigin)return e;var a=new E.proto.BotMessageOrigin;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED":case 0:a.type=0;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?E.proto.BotMessageOrigin.BotMessageOriginType[e.type]===void 0?e.type:E.proto.BotMessageOrigin.BotMessageOriginType[e.type]:e.type,a.oneofs&&(A._type="type")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMessageOrigin"},r.BotMessageOriginType=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED"]=0,e})(),r})(),n.BotMessageOriginMetadata=(function(){function r(o){if(this.origins=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.origins&&t.origins.length||(t.origins=[]),t.origins.push(E.proto.BotMessageOrigin.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.BotMessageOriginMetadata)return i;var e=new E.proto.BotMessageOriginMetadata;if(i.origins){if(!Array.isArray(i.origins))throw TypeError(".proto.BotMessageOriginMetadata.origins: array expected");e.origins=[];for(var a=0;a>>3){case 1:{s.botEntryPointOrigin=e.int32();break}case 2:{s.forwardScore=e.uint32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotMessageSharingInfo)return e;var a=new E.proto.BotMessageSharingInfo;switch(e.botEntryPointOrigin){default:if(typeof e.botEntryPointOrigin=="number"){a.botEntryPointOrigin=e.botEntryPointOrigin;break}break;case"UNDEFINED_ENTRY_POINT":case 0:a.botEntryPointOrigin=0;break;case"FAVICON":case 1:a.botEntryPointOrigin=1;break;case"CHATLIST":case 2:a.botEntryPointOrigin=2;break;case"AISEARCH_NULL_STATE_PAPER_PLANE":case 3:a.botEntryPointOrigin=3;break;case"AISEARCH_NULL_STATE_SUGGESTION":case 4:a.botEntryPointOrigin=4;break;case"AISEARCH_TYPE_AHEAD_SUGGESTION":case 5:a.botEntryPointOrigin=5;break;case"AISEARCH_TYPE_AHEAD_PAPER_PLANE":case 6:a.botEntryPointOrigin=6;break;case"AISEARCH_TYPE_AHEAD_RESULT_CHATLIST":case 7:a.botEntryPointOrigin=7;break;case"AISEARCH_TYPE_AHEAD_RESULT_MESSAGES":case 8:a.botEntryPointOrigin=8;break;case"AIVOICE_SEARCH_BAR":case 9:a.botEntryPointOrigin=9;break;case"AIVOICE_FAVICON":case 10:a.botEntryPointOrigin=10;break;case"AISTUDIO":case 11:a.botEntryPointOrigin=11;break;case"DEEPLINK":case 12:a.botEntryPointOrigin=12;break;case"NOTIFICATION":case 13:a.botEntryPointOrigin=13;break;case"PROFILE_MESSAGE_BUTTON":case 14:a.botEntryPointOrigin=14;break;case"FORWARD":case 15:a.botEntryPointOrigin=15;break;case"APP_SHORTCUT":case 16:a.botEntryPointOrigin=16;break;case"FF_FAMILY":case 17:a.botEntryPointOrigin=17;break;case"AI_TAB":case 18:a.botEntryPointOrigin=18;break;case"AI_HOME":case 19:a.botEntryPointOrigin=19;break;case"AI_DEEPLINK_IMMERSIVE":case 20:a.botEntryPointOrigin=20;break;case"AI_DEEPLINK":case 21:a.botEntryPointOrigin=21;break;case"META_AI_CHAT_SHORTCUT_AI_STUDIO":case 22:a.botEntryPointOrigin=22;break;case"UGC_CHAT_SHORTCUT_AI_STUDIO":case 23:a.botEntryPointOrigin=23;break;case"NEW_CHAT_AI_STUDIO":case 24:a.botEntryPointOrigin=24;break;case"AIVOICE_FAVICON_CALL_HISTORY":case 25:a.botEntryPointOrigin=25;break;case"ASK_META_AI_CONTEXT_MENU":case 26:a.botEntryPointOrigin=26;break;case"ASK_META_AI_CONTEXT_MENU_1ON1":case 27:a.botEntryPointOrigin=27;break;case"ASK_META_AI_CONTEXT_MENU_GROUP":case 28:a.botEntryPointOrigin=28;break;case"INVOKE_META_AI_1ON1":case 29:a.botEntryPointOrigin=29;break;case"INVOKE_META_AI_GROUP":case 30:a.botEntryPointOrigin=30;break;case"META_AI_FORWARD":case 31:a.botEntryPointOrigin=31;break;case"NEW_CHAT_AI_CONTACT":case 32:a.botEntryPointOrigin=32;break;case"MESSAGE_QUICK_ACTION_1_ON_1_CHAT":case 33:a.botEntryPointOrigin=33;break;case"MESSAGE_QUICK_ACTION_GROUP_CHAT":case 34:a.botEntryPointOrigin=34;break;case"ATTACHMENT_TRAY_1_ON_1_CHAT":case 35:a.botEntryPointOrigin=35;break;case"ATTACHMENT_TRAY_GROUP_CHAT":case 36:a.botEntryPointOrigin=36;break;case"ASK_META_AI_MEDIA_VIEWER_1ON1":case 37:a.botEntryPointOrigin=37;break;case"ASK_META_AI_MEDIA_VIEWER_GROUP":case 38:a.botEntryPointOrigin=38;break}return e.forwardScore!=null&&(a.forwardScore=e.forwardScore>>>0),a},r.toObject=function(e,a){a||(a={});var A={};return e.botEntryPointOrigin!=null&&e.hasOwnProperty("botEntryPointOrigin")&&(A.botEntryPointOrigin=a.enums===String?E.proto.BotMetricsEntryPoint[e.botEntryPointOrigin]===void 0?e.botEntryPointOrigin:E.proto.BotMetricsEntryPoint[e.botEntryPointOrigin]:e.botEntryPointOrigin,a.oneofs&&(A._botEntryPointOrigin="botEntryPointOrigin")),e.forwardScore!=null&&e.hasOwnProperty("forwardScore")&&(A.forwardScore=e.forwardScore,a.oneofs&&(A._forwardScore="forwardScore")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMessageSharingInfo"},r})(),n.BotMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.avatarMetadata=E.proto.BotAvatarMetadata.decode(e,e.uint32());break}case 2:{s.personaId=e.string();break}case 3:{s.pluginMetadata=E.proto.BotPluginMetadata.decode(e,e.uint32());break}case 4:{s.suggestedPromptMetadata=E.proto.BotSuggestedPromptMetadata.decode(e,e.uint32());break}case 5:{s.invokerJid=e.string();break}case 6:{s.sessionMetadata=E.proto.BotSessionMetadata.decode(e,e.uint32());break}case 7:{s.memuMetadata=E.proto.BotMemuMetadata.decode(e,e.uint32());break}case 8:{s.timezone=e.string();break}case 9:{s.reminderMetadata=E.proto.BotReminderMetadata.decode(e,e.uint32());break}case 10:{s.modelMetadata=E.proto.BotModelMetadata.decode(e,e.uint32());break}case 11:{s.messageDisclaimerText=e.string();break}case 12:{s.progressIndicatorMetadata=E.proto.BotProgressIndicatorMetadata.decode(e,e.uint32());break}case 13:{s.capabilityMetadata=E.proto.BotCapabilityMetadata.decode(e,e.uint32());break}case 14:{s.imagineMetadata=E.proto.BotImagineMetadata.decode(e,e.uint32());break}case 15:{s.memoryMetadata=E.proto.BotMemoryMetadata.decode(e,e.uint32());break}case 16:{s.renderingMetadata=E.proto.BotRenderingMetadata.decode(e,e.uint32());break}case 17:{s.botMetricsMetadata=E.proto.BotMetricsMetadata.decode(e,e.uint32());break}case 18:{s.botLinkedAccountsMetadata=E.proto.BotLinkedAccountsMetadata.decode(e,e.uint32());break}case 19:{s.richResponseSourcesMetadata=E.proto.BotSourcesMetadata.decode(e,e.uint32());break}case 20:{s.aiConversationContext=e.bytes();break}case 21:{s.botPromotionMessageMetadata=E.proto.BotPromotionMessageMetadata.decode(e,e.uint32());break}case 22:{s.botModeSelectionMetadata=E.proto.BotModeSelectionMetadata.decode(e,e.uint32());break}case 23:{s.botQuotaMetadata=E.proto.BotQuotaMetadata.decode(e,e.uint32());break}case 24:{s.botAgeCollectionMetadata=E.proto.BotAgeCollectionMetadata.decode(e,e.uint32());break}case 25:{s.conversationStarterPromptId=e.string();break}case 26:{s.botResponseId=e.string();break}case 27:{s.verificationMetadata=E.proto.BotSignatureVerificationMetadata.decode(e,e.uint32());break}case 28:{s.unifiedResponseMutation=E.proto.BotUnifiedResponseMutation.decode(e,e.uint32());break}case 29:{s.botMessageOriginMetadata=E.proto.BotMessageOriginMetadata.decode(e,e.uint32());break}case 30:{s.inThreadSurveyMetadata=E.proto.InThreadSurveyMetadata.decode(e,e.uint32());break}case 31:{s.botThreadInfo=E.proto.AIThreadInfo.decode(e,e.uint32());break}case 32:{s.regenerateMetadata=E.proto.AIRegenerateMetadata.decode(e,e.uint32());break}case 33:{s.sessionTransparencyMetadata=E.proto.SessionTransparencyMetadata.decode(e,e.uint32());break}case 999:{s.internalMetadata=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotMetadata)return e;var a=new E.proto.BotMetadata;if(e.avatarMetadata!=null){if(typeof e.avatarMetadata!="object")throw TypeError(".proto.BotMetadata.avatarMetadata: object expected");a.avatarMetadata=E.proto.BotAvatarMetadata.fromObject(e.avatarMetadata)}if(e.personaId!=null&&(a.personaId=String(e.personaId)),e.pluginMetadata!=null){if(typeof e.pluginMetadata!="object")throw TypeError(".proto.BotMetadata.pluginMetadata: object expected");a.pluginMetadata=E.proto.BotPluginMetadata.fromObject(e.pluginMetadata)}if(e.suggestedPromptMetadata!=null){if(typeof e.suggestedPromptMetadata!="object")throw TypeError(".proto.BotMetadata.suggestedPromptMetadata: object expected");a.suggestedPromptMetadata=E.proto.BotSuggestedPromptMetadata.fromObject(e.suggestedPromptMetadata)}if(e.invokerJid!=null&&(a.invokerJid=String(e.invokerJid)),e.sessionMetadata!=null){if(typeof e.sessionMetadata!="object")throw TypeError(".proto.BotMetadata.sessionMetadata: object expected");a.sessionMetadata=E.proto.BotSessionMetadata.fromObject(e.sessionMetadata)}if(e.memuMetadata!=null){if(typeof e.memuMetadata!="object")throw TypeError(".proto.BotMetadata.memuMetadata: object expected");a.memuMetadata=E.proto.BotMemuMetadata.fromObject(e.memuMetadata)}if(e.timezone!=null&&(a.timezone=String(e.timezone)),e.reminderMetadata!=null){if(typeof e.reminderMetadata!="object")throw TypeError(".proto.BotMetadata.reminderMetadata: object expected");a.reminderMetadata=E.proto.BotReminderMetadata.fromObject(e.reminderMetadata)}if(e.modelMetadata!=null){if(typeof e.modelMetadata!="object")throw TypeError(".proto.BotMetadata.modelMetadata: object expected");a.modelMetadata=E.proto.BotModelMetadata.fromObject(e.modelMetadata)}if(e.messageDisclaimerText!=null&&(a.messageDisclaimerText=String(e.messageDisclaimerText)),e.progressIndicatorMetadata!=null){if(typeof e.progressIndicatorMetadata!="object")throw TypeError(".proto.BotMetadata.progressIndicatorMetadata: object expected");a.progressIndicatorMetadata=E.proto.BotProgressIndicatorMetadata.fromObject(e.progressIndicatorMetadata)}if(e.capabilityMetadata!=null){if(typeof e.capabilityMetadata!="object")throw TypeError(".proto.BotMetadata.capabilityMetadata: object expected");a.capabilityMetadata=E.proto.BotCapabilityMetadata.fromObject(e.capabilityMetadata)}if(e.imagineMetadata!=null){if(typeof e.imagineMetadata!="object")throw TypeError(".proto.BotMetadata.imagineMetadata: object expected");a.imagineMetadata=E.proto.BotImagineMetadata.fromObject(e.imagineMetadata)}if(e.memoryMetadata!=null){if(typeof e.memoryMetadata!="object")throw TypeError(".proto.BotMetadata.memoryMetadata: object expected");a.memoryMetadata=E.proto.BotMemoryMetadata.fromObject(e.memoryMetadata)}if(e.renderingMetadata!=null){if(typeof e.renderingMetadata!="object")throw TypeError(".proto.BotMetadata.renderingMetadata: object expected");a.renderingMetadata=E.proto.BotRenderingMetadata.fromObject(e.renderingMetadata)}if(e.botMetricsMetadata!=null){if(typeof e.botMetricsMetadata!="object")throw TypeError(".proto.BotMetadata.botMetricsMetadata: object expected");a.botMetricsMetadata=E.proto.BotMetricsMetadata.fromObject(e.botMetricsMetadata)}if(e.botLinkedAccountsMetadata!=null){if(typeof e.botLinkedAccountsMetadata!="object")throw TypeError(".proto.BotMetadata.botLinkedAccountsMetadata: object expected");a.botLinkedAccountsMetadata=E.proto.BotLinkedAccountsMetadata.fromObject(e.botLinkedAccountsMetadata)}if(e.richResponseSourcesMetadata!=null){if(typeof e.richResponseSourcesMetadata!="object")throw TypeError(".proto.BotMetadata.richResponseSourcesMetadata: object expected");a.richResponseSourcesMetadata=E.proto.BotSourcesMetadata.fromObject(e.richResponseSourcesMetadata)}if(e.aiConversationContext!=null&&(typeof e.aiConversationContext=="string"?I.base64.decode(e.aiConversationContext,a.aiConversationContext=I.newBuffer(I.base64.length(e.aiConversationContext)),0):e.aiConversationContext.length>=0&&(a.aiConversationContext=e.aiConversationContext)),e.botPromotionMessageMetadata!=null){if(typeof e.botPromotionMessageMetadata!="object")throw TypeError(".proto.BotMetadata.botPromotionMessageMetadata: object expected");a.botPromotionMessageMetadata=E.proto.BotPromotionMessageMetadata.fromObject(e.botPromotionMessageMetadata)}if(e.botModeSelectionMetadata!=null){if(typeof e.botModeSelectionMetadata!="object")throw TypeError(".proto.BotMetadata.botModeSelectionMetadata: object expected");a.botModeSelectionMetadata=E.proto.BotModeSelectionMetadata.fromObject(e.botModeSelectionMetadata)}if(e.botQuotaMetadata!=null){if(typeof e.botQuotaMetadata!="object")throw TypeError(".proto.BotMetadata.botQuotaMetadata: object expected");a.botQuotaMetadata=E.proto.BotQuotaMetadata.fromObject(e.botQuotaMetadata)}if(e.botAgeCollectionMetadata!=null){if(typeof e.botAgeCollectionMetadata!="object")throw TypeError(".proto.BotMetadata.botAgeCollectionMetadata: object expected");a.botAgeCollectionMetadata=E.proto.BotAgeCollectionMetadata.fromObject(e.botAgeCollectionMetadata)}if(e.conversationStarterPromptId!=null&&(a.conversationStarterPromptId=String(e.conversationStarterPromptId)),e.botResponseId!=null&&(a.botResponseId=String(e.botResponseId)),e.verificationMetadata!=null){if(typeof e.verificationMetadata!="object")throw TypeError(".proto.BotMetadata.verificationMetadata: object expected");a.verificationMetadata=E.proto.BotSignatureVerificationMetadata.fromObject(e.verificationMetadata)}if(e.unifiedResponseMutation!=null){if(typeof e.unifiedResponseMutation!="object")throw TypeError(".proto.BotMetadata.unifiedResponseMutation: object expected");a.unifiedResponseMutation=E.proto.BotUnifiedResponseMutation.fromObject(e.unifiedResponseMutation)}if(e.botMessageOriginMetadata!=null){if(typeof e.botMessageOriginMetadata!="object")throw TypeError(".proto.BotMetadata.botMessageOriginMetadata: object expected");a.botMessageOriginMetadata=E.proto.BotMessageOriginMetadata.fromObject(e.botMessageOriginMetadata)}if(e.inThreadSurveyMetadata!=null){if(typeof e.inThreadSurveyMetadata!="object")throw TypeError(".proto.BotMetadata.inThreadSurveyMetadata: object expected");a.inThreadSurveyMetadata=E.proto.InThreadSurveyMetadata.fromObject(e.inThreadSurveyMetadata)}if(e.botThreadInfo!=null){if(typeof e.botThreadInfo!="object")throw TypeError(".proto.BotMetadata.botThreadInfo: object expected");a.botThreadInfo=E.proto.AIThreadInfo.fromObject(e.botThreadInfo)}if(e.regenerateMetadata!=null){if(typeof e.regenerateMetadata!="object")throw TypeError(".proto.BotMetadata.regenerateMetadata: object expected");a.regenerateMetadata=E.proto.AIRegenerateMetadata.fromObject(e.regenerateMetadata)}if(e.sessionTransparencyMetadata!=null){if(typeof e.sessionTransparencyMetadata!="object")throw TypeError(".proto.BotMetadata.sessionTransparencyMetadata: object expected");a.sessionTransparencyMetadata=E.proto.SessionTransparencyMetadata.fromObject(e.sessionTransparencyMetadata)}return e.internalMetadata!=null&&(typeof e.internalMetadata=="string"?I.base64.decode(e.internalMetadata,a.internalMetadata=I.newBuffer(I.base64.length(e.internalMetadata)),0):e.internalMetadata.length>=0&&(a.internalMetadata=e.internalMetadata)),a},r.toObject=function(e,a){a||(a={});var A={};return e.avatarMetadata!=null&&e.hasOwnProperty("avatarMetadata")&&(A.avatarMetadata=E.proto.BotAvatarMetadata.toObject(e.avatarMetadata,a),a.oneofs&&(A._avatarMetadata="avatarMetadata")),e.personaId!=null&&e.hasOwnProperty("personaId")&&(A.personaId=e.personaId,a.oneofs&&(A._personaId="personaId")),e.pluginMetadata!=null&&e.hasOwnProperty("pluginMetadata")&&(A.pluginMetadata=E.proto.BotPluginMetadata.toObject(e.pluginMetadata,a),a.oneofs&&(A._pluginMetadata="pluginMetadata")),e.suggestedPromptMetadata!=null&&e.hasOwnProperty("suggestedPromptMetadata")&&(A.suggestedPromptMetadata=E.proto.BotSuggestedPromptMetadata.toObject(e.suggestedPromptMetadata,a),a.oneofs&&(A._suggestedPromptMetadata="suggestedPromptMetadata")),e.invokerJid!=null&&e.hasOwnProperty("invokerJid")&&(A.invokerJid=e.invokerJid,a.oneofs&&(A._invokerJid="invokerJid")),e.sessionMetadata!=null&&e.hasOwnProperty("sessionMetadata")&&(A.sessionMetadata=E.proto.BotSessionMetadata.toObject(e.sessionMetadata,a),a.oneofs&&(A._sessionMetadata="sessionMetadata")),e.memuMetadata!=null&&e.hasOwnProperty("memuMetadata")&&(A.memuMetadata=E.proto.BotMemuMetadata.toObject(e.memuMetadata,a),a.oneofs&&(A._memuMetadata="memuMetadata")),e.timezone!=null&&e.hasOwnProperty("timezone")&&(A.timezone=e.timezone,a.oneofs&&(A._timezone="timezone")),e.reminderMetadata!=null&&e.hasOwnProperty("reminderMetadata")&&(A.reminderMetadata=E.proto.BotReminderMetadata.toObject(e.reminderMetadata,a),a.oneofs&&(A._reminderMetadata="reminderMetadata")),e.modelMetadata!=null&&e.hasOwnProperty("modelMetadata")&&(A.modelMetadata=E.proto.BotModelMetadata.toObject(e.modelMetadata,a),a.oneofs&&(A._modelMetadata="modelMetadata")),e.messageDisclaimerText!=null&&e.hasOwnProperty("messageDisclaimerText")&&(A.messageDisclaimerText=e.messageDisclaimerText,a.oneofs&&(A._messageDisclaimerText="messageDisclaimerText")),e.progressIndicatorMetadata!=null&&e.hasOwnProperty("progressIndicatorMetadata")&&(A.progressIndicatorMetadata=E.proto.BotProgressIndicatorMetadata.toObject(e.progressIndicatorMetadata,a),a.oneofs&&(A._progressIndicatorMetadata="progressIndicatorMetadata")),e.capabilityMetadata!=null&&e.hasOwnProperty("capabilityMetadata")&&(A.capabilityMetadata=E.proto.BotCapabilityMetadata.toObject(e.capabilityMetadata,a),a.oneofs&&(A._capabilityMetadata="capabilityMetadata")),e.imagineMetadata!=null&&e.hasOwnProperty("imagineMetadata")&&(A.imagineMetadata=E.proto.BotImagineMetadata.toObject(e.imagineMetadata,a),a.oneofs&&(A._imagineMetadata="imagineMetadata")),e.memoryMetadata!=null&&e.hasOwnProperty("memoryMetadata")&&(A.memoryMetadata=E.proto.BotMemoryMetadata.toObject(e.memoryMetadata,a),a.oneofs&&(A._memoryMetadata="memoryMetadata")),e.renderingMetadata!=null&&e.hasOwnProperty("renderingMetadata")&&(A.renderingMetadata=E.proto.BotRenderingMetadata.toObject(e.renderingMetadata,a),a.oneofs&&(A._renderingMetadata="renderingMetadata")),e.botMetricsMetadata!=null&&e.hasOwnProperty("botMetricsMetadata")&&(A.botMetricsMetadata=E.proto.BotMetricsMetadata.toObject(e.botMetricsMetadata,a),a.oneofs&&(A._botMetricsMetadata="botMetricsMetadata")),e.botLinkedAccountsMetadata!=null&&e.hasOwnProperty("botLinkedAccountsMetadata")&&(A.botLinkedAccountsMetadata=E.proto.BotLinkedAccountsMetadata.toObject(e.botLinkedAccountsMetadata,a),a.oneofs&&(A._botLinkedAccountsMetadata="botLinkedAccountsMetadata")),e.richResponseSourcesMetadata!=null&&e.hasOwnProperty("richResponseSourcesMetadata")&&(A.richResponseSourcesMetadata=E.proto.BotSourcesMetadata.toObject(e.richResponseSourcesMetadata,a),a.oneofs&&(A._richResponseSourcesMetadata="richResponseSourcesMetadata")),e.aiConversationContext!=null&&e.hasOwnProperty("aiConversationContext")&&(A.aiConversationContext=a.bytes===String?I.base64.encode(e.aiConversationContext,0,e.aiConversationContext.length):a.bytes===Array?Array.prototype.slice.call(e.aiConversationContext):e.aiConversationContext,a.oneofs&&(A._aiConversationContext="aiConversationContext")),e.botPromotionMessageMetadata!=null&&e.hasOwnProperty("botPromotionMessageMetadata")&&(A.botPromotionMessageMetadata=E.proto.BotPromotionMessageMetadata.toObject(e.botPromotionMessageMetadata,a),a.oneofs&&(A._botPromotionMessageMetadata="botPromotionMessageMetadata")),e.botModeSelectionMetadata!=null&&e.hasOwnProperty("botModeSelectionMetadata")&&(A.botModeSelectionMetadata=E.proto.BotModeSelectionMetadata.toObject(e.botModeSelectionMetadata,a),a.oneofs&&(A._botModeSelectionMetadata="botModeSelectionMetadata")),e.botQuotaMetadata!=null&&e.hasOwnProperty("botQuotaMetadata")&&(A.botQuotaMetadata=E.proto.BotQuotaMetadata.toObject(e.botQuotaMetadata,a),a.oneofs&&(A._botQuotaMetadata="botQuotaMetadata")),e.botAgeCollectionMetadata!=null&&e.hasOwnProperty("botAgeCollectionMetadata")&&(A.botAgeCollectionMetadata=E.proto.BotAgeCollectionMetadata.toObject(e.botAgeCollectionMetadata,a),a.oneofs&&(A._botAgeCollectionMetadata="botAgeCollectionMetadata")),e.conversationStarterPromptId!=null&&e.hasOwnProperty("conversationStarterPromptId")&&(A.conversationStarterPromptId=e.conversationStarterPromptId,a.oneofs&&(A._conversationStarterPromptId="conversationStarterPromptId")),e.botResponseId!=null&&e.hasOwnProperty("botResponseId")&&(A.botResponseId=e.botResponseId,a.oneofs&&(A._botResponseId="botResponseId")),e.verificationMetadata!=null&&e.hasOwnProperty("verificationMetadata")&&(A.verificationMetadata=E.proto.BotSignatureVerificationMetadata.toObject(e.verificationMetadata,a),a.oneofs&&(A._verificationMetadata="verificationMetadata")),e.unifiedResponseMutation!=null&&e.hasOwnProperty("unifiedResponseMutation")&&(A.unifiedResponseMutation=E.proto.BotUnifiedResponseMutation.toObject(e.unifiedResponseMutation,a),a.oneofs&&(A._unifiedResponseMutation="unifiedResponseMutation")),e.botMessageOriginMetadata!=null&&e.hasOwnProperty("botMessageOriginMetadata")&&(A.botMessageOriginMetadata=E.proto.BotMessageOriginMetadata.toObject(e.botMessageOriginMetadata,a),a.oneofs&&(A._botMessageOriginMetadata="botMessageOriginMetadata")),e.inThreadSurveyMetadata!=null&&e.hasOwnProperty("inThreadSurveyMetadata")&&(A.inThreadSurveyMetadata=E.proto.InThreadSurveyMetadata.toObject(e.inThreadSurveyMetadata,a),a.oneofs&&(A._inThreadSurveyMetadata="inThreadSurveyMetadata")),e.botThreadInfo!=null&&e.hasOwnProperty("botThreadInfo")&&(A.botThreadInfo=E.proto.AIThreadInfo.toObject(e.botThreadInfo,a),a.oneofs&&(A._botThreadInfo="botThreadInfo")),e.regenerateMetadata!=null&&e.hasOwnProperty("regenerateMetadata")&&(A.regenerateMetadata=E.proto.AIRegenerateMetadata.toObject(e.regenerateMetadata,a),a.oneofs&&(A._regenerateMetadata="regenerateMetadata")),e.sessionTransparencyMetadata!=null&&e.hasOwnProperty("sessionTransparencyMetadata")&&(A.sessionTransparencyMetadata=E.proto.SessionTransparencyMetadata.toObject(e.sessionTransparencyMetadata,a),a.oneofs&&(A._sessionTransparencyMetadata="sessionTransparencyMetadata")),e.internalMetadata!=null&&e.hasOwnProperty("internalMetadata")&&(A.internalMetadata=a.bytes===String?I.base64.encode(e.internalMetadata,0,e.internalMetadata.length):a.bytes===Array?Array.prototype.slice.call(e.internalMetadata):e.internalMetadata,a.oneofs&&(A._internalMetadata="internalMetadata")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMetadata"},r})(),n.BotMetricsEntryPoint=(function(){let r={},o=Object.create(r);return o[r[0]="UNDEFINED_ENTRY_POINT"]=0,o[r[1]="FAVICON"]=1,o[r[2]="CHATLIST"]=2,o[r[3]="AISEARCH_NULL_STATE_PAPER_PLANE"]=3,o[r[4]="AISEARCH_NULL_STATE_SUGGESTION"]=4,o[r[5]="AISEARCH_TYPE_AHEAD_SUGGESTION"]=5,o[r[6]="AISEARCH_TYPE_AHEAD_PAPER_PLANE"]=6,o[r[7]="AISEARCH_TYPE_AHEAD_RESULT_CHATLIST"]=7,o[r[8]="AISEARCH_TYPE_AHEAD_RESULT_MESSAGES"]=8,o[r[9]="AIVOICE_SEARCH_BAR"]=9,o[r[10]="AIVOICE_FAVICON"]=10,o[r[11]="AISTUDIO"]=11,o[r[12]="DEEPLINK"]=12,o[r[13]="NOTIFICATION"]=13,o[r[14]="PROFILE_MESSAGE_BUTTON"]=14,o[r[15]="FORWARD"]=15,o[r[16]="APP_SHORTCUT"]=16,o[r[17]="FF_FAMILY"]=17,o[r[18]="AI_TAB"]=18,o[r[19]="AI_HOME"]=19,o[r[20]="AI_DEEPLINK_IMMERSIVE"]=20,o[r[21]="AI_DEEPLINK"]=21,o[r[22]="META_AI_CHAT_SHORTCUT_AI_STUDIO"]=22,o[r[23]="UGC_CHAT_SHORTCUT_AI_STUDIO"]=23,o[r[24]="NEW_CHAT_AI_STUDIO"]=24,o[r[25]="AIVOICE_FAVICON_CALL_HISTORY"]=25,o[r[26]="ASK_META_AI_CONTEXT_MENU"]=26,o[r[27]="ASK_META_AI_CONTEXT_MENU_1ON1"]=27,o[r[28]="ASK_META_AI_CONTEXT_MENU_GROUP"]=28,o[r[29]="INVOKE_META_AI_1ON1"]=29,o[r[30]="INVOKE_META_AI_GROUP"]=30,o[r[31]="META_AI_FORWARD"]=31,o[r[32]="NEW_CHAT_AI_CONTACT"]=32,o[r[33]="MESSAGE_QUICK_ACTION_1_ON_1_CHAT"]=33,o[r[34]="MESSAGE_QUICK_ACTION_GROUP_CHAT"]=34,o[r[35]="ATTACHMENT_TRAY_1_ON_1_CHAT"]=35,o[r[36]="ATTACHMENT_TRAY_GROUP_CHAT"]=36,o[r[37]="ASK_META_AI_MEDIA_VIEWER_1ON1"]=37,o[r[38]="ASK_META_AI_MEDIA_VIEWER_GROUP"]=38,o})(),n.BotMetricsMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.destinationId=e.string();break}case 2:{s.destinationEntryPoint=e.int32();break}case 3:{s.threadOrigin=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotMetricsMetadata)return e;var a=new E.proto.BotMetricsMetadata;switch(e.destinationId!=null&&(a.destinationId=String(e.destinationId)),e.destinationEntryPoint){default:if(typeof e.destinationEntryPoint=="number"){a.destinationEntryPoint=e.destinationEntryPoint;break}break;case"UNDEFINED_ENTRY_POINT":case 0:a.destinationEntryPoint=0;break;case"FAVICON":case 1:a.destinationEntryPoint=1;break;case"CHATLIST":case 2:a.destinationEntryPoint=2;break;case"AISEARCH_NULL_STATE_PAPER_PLANE":case 3:a.destinationEntryPoint=3;break;case"AISEARCH_NULL_STATE_SUGGESTION":case 4:a.destinationEntryPoint=4;break;case"AISEARCH_TYPE_AHEAD_SUGGESTION":case 5:a.destinationEntryPoint=5;break;case"AISEARCH_TYPE_AHEAD_PAPER_PLANE":case 6:a.destinationEntryPoint=6;break;case"AISEARCH_TYPE_AHEAD_RESULT_CHATLIST":case 7:a.destinationEntryPoint=7;break;case"AISEARCH_TYPE_AHEAD_RESULT_MESSAGES":case 8:a.destinationEntryPoint=8;break;case"AIVOICE_SEARCH_BAR":case 9:a.destinationEntryPoint=9;break;case"AIVOICE_FAVICON":case 10:a.destinationEntryPoint=10;break;case"AISTUDIO":case 11:a.destinationEntryPoint=11;break;case"DEEPLINK":case 12:a.destinationEntryPoint=12;break;case"NOTIFICATION":case 13:a.destinationEntryPoint=13;break;case"PROFILE_MESSAGE_BUTTON":case 14:a.destinationEntryPoint=14;break;case"FORWARD":case 15:a.destinationEntryPoint=15;break;case"APP_SHORTCUT":case 16:a.destinationEntryPoint=16;break;case"FF_FAMILY":case 17:a.destinationEntryPoint=17;break;case"AI_TAB":case 18:a.destinationEntryPoint=18;break;case"AI_HOME":case 19:a.destinationEntryPoint=19;break;case"AI_DEEPLINK_IMMERSIVE":case 20:a.destinationEntryPoint=20;break;case"AI_DEEPLINK":case 21:a.destinationEntryPoint=21;break;case"META_AI_CHAT_SHORTCUT_AI_STUDIO":case 22:a.destinationEntryPoint=22;break;case"UGC_CHAT_SHORTCUT_AI_STUDIO":case 23:a.destinationEntryPoint=23;break;case"NEW_CHAT_AI_STUDIO":case 24:a.destinationEntryPoint=24;break;case"AIVOICE_FAVICON_CALL_HISTORY":case 25:a.destinationEntryPoint=25;break;case"ASK_META_AI_CONTEXT_MENU":case 26:a.destinationEntryPoint=26;break;case"ASK_META_AI_CONTEXT_MENU_1ON1":case 27:a.destinationEntryPoint=27;break;case"ASK_META_AI_CONTEXT_MENU_GROUP":case 28:a.destinationEntryPoint=28;break;case"INVOKE_META_AI_1ON1":case 29:a.destinationEntryPoint=29;break;case"INVOKE_META_AI_GROUP":case 30:a.destinationEntryPoint=30;break;case"META_AI_FORWARD":case 31:a.destinationEntryPoint=31;break;case"NEW_CHAT_AI_CONTACT":case 32:a.destinationEntryPoint=32;break;case"MESSAGE_QUICK_ACTION_1_ON_1_CHAT":case 33:a.destinationEntryPoint=33;break;case"MESSAGE_QUICK_ACTION_GROUP_CHAT":case 34:a.destinationEntryPoint=34;break;case"ATTACHMENT_TRAY_1_ON_1_CHAT":case 35:a.destinationEntryPoint=35;break;case"ATTACHMENT_TRAY_GROUP_CHAT":case 36:a.destinationEntryPoint=36;break;case"ASK_META_AI_MEDIA_VIEWER_1ON1":case 37:a.destinationEntryPoint=37;break;case"ASK_META_AI_MEDIA_VIEWER_GROUP":case 38:a.destinationEntryPoint=38;break}switch(e.threadOrigin){default:if(typeof e.threadOrigin=="number"){a.threadOrigin=e.threadOrigin;break}break;case"AI_TAB_THREAD":case 1:a.threadOrigin=1;break;case"AI_HOME_THREAD":case 2:a.threadOrigin=2;break;case"AI_DEEPLINK_IMMERSIVE_THREAD":case 3:a.threadOrigin=3;break;case"AI_DEEPLINK_THREAD":case 4:a.threadOrigin=4;break;case"ASK_META_AI_CONTEXT_MENU_THREAD":case 5:a.threadOrigin=5;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.destinationId!=null&&e.hasOwnProperty("destinationId")&&(A.destinationId=e.destinationId,a.oneofs&&(A._destinationId="destinationId")),e.destinationEntryPoint!=null&&e.hasOwnProperty("destinationEntryPoint")&&(A.destinationEntryPoint=a.enums===String?E.proto.BotMetricsEntryPoint[e.destinationEntryPoint]===void 0?e.destinationEntryPoint:E.proto.BotMetricsEntryPoint[e.destinationEntryPoint]:e.destinationEntryPoint,a.oneofs&&(A._destinationEntryPoint="destinationEntryPoint")),e.threadOrigin!=null&&e.hasOwnProperty("threadOrigin")&&(A.threadOrigin=a.enums===String?E.proto.BotMetricsThreadEntryPoint[e.threadOrigin]===void 0?e.threadOrigin:E.proto.BotMetricsThreadEntryPoint[e.threadOrigin]:e.threadOrigin,a.oneofs&&(A._threadOrigin="threadOrigin")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMetricsMetadata"},r})(),n.BotMetricsThreadEntryPoint=(function(){let r={},o=Object.create(r);return o[r[1]="AI_TAB_THREAD"]=1,o[r[2]="AI_HOME_THREAD"]=2,o[r[3]="AI_DEEPLINK_IMMERSIVE_THREAD"]=3,o[r[4]="AI_DEEPLINK_THREAD"]=4,o[r[5]="ASK_META_AI_CONTEXT_MENU_THREAD"]=5,o})(),n.BotModeSelectionMetadata=(function(){function r(o){if(this.mode=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{if(t.mode&&t.mode.length||(t.mode=[]),(s&7)===2)for(var g=i.uint32()+i.pos;i.pos>>3){case 1:{s.modelType=e.int32();break}case 2:{s.premiumModelStatus=e.int32();break}case 3:{s.modelNameOverride=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotModelMetadata)return e;var a=new E.proto.BotModelMetadata;switch(e.modelType){default:if(typeof e.modelType=="number"){a.modelType=e.modelType;break}break;case"UNKNOWN_TYPE":case 0:a.modelType=0;break;case"LLAMA_PROD":case 1:a.modelType=1;break;case"LLAMA_PROD_PREMIUM":case 2:a.modelType=2;break}switch(e.premiumModelStatus){default:if(typeof e.premiumModelStatus=="number"){a.premiumModelStatus=e.premiumModelStatus;break}break;case"UNKNOWN_STATUS":case 0:a.premiumModelStatus=0;break;case"AVAILABLE":case 1:a.premiumModelStatus=1;break;case"QUOTA_EXCEED_LIMIT":case 2:a.premiumModelStatus=2;break}return e.modelNameOverride!=null&&(a.modelNameOverride=String(e.modelNameOverride)),a},r.toObject=function(e,a){a||(a={});var A={};return e.modelType!=null&&e.hasOwnProperty("modelType")&&(A.modelType=a.enums===String?E.proto.BotModelMetadata.ModelType[e.modelType]===void 0?e.modelType:E.proto.BotModelMetadata.ModelType[e.modelType]:e.modelType,a.oneofs&&(A._modelType="modelType")),e.premiumModelStatus!=null&&e.hasOwnProperty("premiumModelStatus")&&(A.premiumModelStatus=a.enums===String?E.proto.BotModelMetadata.PremiumModelStatus[e.premiumModelStatus]===void 0?e.premiumModelStatus:E.proto.BotModelMetadata.PremiumModelStatus[e.premiumModelStatus]:e.premiumModelStatus,a.oneofs&&(A._premiumModelStatus="premiumModelStatus")),e.modelNameOverride!=null&&e.hasOwnProperty("modelNameOverride")&&(A.modelNameOverride=e.modelNameOverride,a.oneofs&&(A._modelNameOverride="modelNameOverride")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotModelMetadata"},r.ModelType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="LLAMA_PROD"]=1,e[i[2]="LLAMA_PROD_PREMIUM"]=2,e})(),r.PremiumModelStatus=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_STATUS"]=0,e[i[1]="AVAILABLE"]=1,e[i[2]="QUOTA_EXCEED_LIMIT"]=2,e})(),r})(),n.BotPluginMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.provider=e.int32();break}case 2:{s.pluginType=e.int32();break}case 3:{s.thumbnailCdnUrl=e.string();break}case 4:{s.profilePhotoCdnUrl=e.string();break}case 5:{s.searchProviderUrl=e.string();break}case 6:{s.referenceIndex=e.uint32();break}case 7:{s.expectedLinksCount=e.uint32();break}case 9:{s.searchQuery=e.string();break}case 10:{s.parentPluginMessageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 11:{s.deprecatedField=e.int32();break}case 12:{s.parentPluginType=e.int32();break}case 13:{s.faviconCdnUrl=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotPluginMetadata)return e;var a=new E.proto.BotPluginMetadata;switch(e.provider){default:if(typeof e.provider=="number"){a.provider=e.provider;break}break;case"UNKNOWN":case 0:a.provider=0;break;case"BING":case 1:a.provider=1;break;case"GOOGLE":case 2:a.provider=2;break;case"SUPPORT":case 3:a.provider=3;break}switch(e.pluginType){default:if(typeof e.pluginType=="number"){a.pluginType=e.pluginType;break}break;case"UNKNOWN_PLUGIN":case 0:a.pluginType=0;break;case"REELS":case 1:a.pluginType=1;break;case"SEARCH":case 2:a.pluginType=2;break}if(e.thumbnailCdnUrl!=null&&(a.thumbnailCdnUrl=String(e.thumbnailCdnUrl)),e.profilePhotoCdnUrl!=null&&(a.profilePhotoCdnUrl=String(e.profilePhotoCdnUrl)),e.searchProviderUrl!=null&&(a.searchProviderUrl=String(e.searchProviderUrl)),e.referenceIndex!=null&&(a.referenceIndex=e.referenceIndex>>>0),e.expectedLinksCount!=null&&(a.expectedLinksCount=e.expectedLinksCount>>>0),e.searchQuery!=null&&(a.searchQuery=String(e.searchQuery)),e.parentPluginMessageKey!=null){if(typeof e.parentPluginMessageKey!="object")throw TypeError(".proto.BotPluginMetadata.parentPluginMessageKey: object expected");a.parentPluginMessageKey=E.proto.MessageKey.fromObject(e.parentPluginMessageKey)}switch(e.deprecatedField){default:if(typeof e.deprecatedField=="number"){a.deprecatedField=e.deprecatedField;break}break;case"UNKNOWN_PLUGIN":case 0:a.deprecatedField=0;break;case"REELS":case 1:a.deprecatedField=1;break;case"SEARCH":case 2:a.deprecatedField=2;break}switch(e.parentPluginType){default:if(typeof e.parentPluginType=="number"){a.parentPluginType=e.parentPluginType;break}break;case"UNKNOWN_PLUGIN":case 0:a.parentPluginType=0;break;case"REELS":case 1:a.parentPluginType=1;break;case"SEARCH":case 2:a.parentPluginType=2;break}return e.faviconCdnUrl!=null&&(a.faviconCdnUrl=String(e.faviconCdnUrl)),a},r.toObject=function(e,a){a||(a={});var A={};return e.provider!=null&&e.hasOwnProperty("provider")&&(A.provider=a.enums===String?E.proto.BotPluginMetadata.SearchProvider[e.provider]===void 0?e.provider:E.proto.BotPluginMetadata.SearchProvider[e.provider]:e.provider,a.oneofs&&(A._provider="provider")),e.pluginType!=null&&e.hasOwnProperty("pluginType")&&(A.pluginType=a.enums===String?E.proto.BotPluginMetadata.PluginType[e.pluginType]===void 0?e.pluginType:E.proto.BotPluginMetadata.PluginType[e.pluginType]:e.pluginType,a.oneofs&&(A._pluginType="pluginType")),e.thumbnailCdnUrl!=null&&e.hasOwnProperty("thumbnailCdnUrl")&&(A.thumbnailCdnUrl=e.thumbnailCdnUrl,a.oneofs&&(A._thumbnailCdnUrl="thumbnailCdnUrl")),e.profilePhotoCdnUrl!=null&&e.hasOwnProperty("profilePhotoCdnUrl")&&(A.profilePhotoCdnUrl=e.profilePhotoCdnUrl,a.oneofs&&(A._profilePhotoCdnUrl="profilePhotoCdnUrl")),e.searchProviderUrl!=null&&e.hasOwnProperty("searchProviderUrl")&&(A.searchProviderUrl=e.searchProviderUrl,a.oneofs&&(A._searchProviderUrl="searchProviderUrl")),e.referenceIndex!=null&&e.hasOwnProperty("referenceIndex")&&(A.referenceIndex=e.referenceIndex,a.oneofs&&(A._referenceIndex="referenceIndex")),e.expectedLinksCount!=null&&e.hasOwnProperty("expectedLinksCount")&&(A.expectedLinksCount=e.expectedLinksCount,a.oneofs&&(A._expectedLinksCount="expectedLinksCount")),e.searchQuery!=null&&e.hasOwnProperty("searchQuery")&&(A.searchQuery=e.searchQuery,a.oneofs&&(A._searchQuery="searchQuery")),e.parentPluginMessageKey!=null&&e.hasOwnProperty("parentPluginMessageKey")&&(A.parentPluginMessageKey=E.proto.MessageKey.toObject(e.parentPluginMessageKey,a),a.oneofs&&(A._parentPluginMessageKey="parentPluginMessageKey")),e.deprecatedField!=null&&e.hasOwnProperty("deprecatedField")&&(A.deprecatedField=a.enums===String?E.proto.BotPluginMetadata.PluginType[e.deprecatedField]===void 0?e.deprecatedField:E.proto.BotPluginMetadata.PluginType[e.deprecatedField]:e.deprecatedField,a.oneofs&&(A._deprecatedField="deprecatedField")),e.parentPluginType!=null&&e.hasOwnProperty("parentPluginType")&&(A.parentPluginType=a.enums===String?E.proto.BotPluginMetadata.PluginType[e.parentPluginType]===void 0?e.parentPluginType:E.proto.BotPluginMetadata.PluginType[e.parentPluginType]:e.parentPluginType,a.oneofs&&(A._parentPluginType="parentPluginType")),e.faviconCdnUrl!=null&&e.hasOwnProperty("faviconCdnUrl")&&(A.faviconCdnUrl=e.faviconCdnUrl,a.oneofs&&(A._faviconCdnUrl="faviconCdnUrl")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPluginMetadata"},r.PluginType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_PLUGIN"]=0,e[i[1]="REELS"]=1,e[i[2]="SEARCH"]=2,e})(),r.SearchProvider=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="BING"]=1,e[i[2]="GOOGLE"]=2,e[i[3]="SUPPORT"]=3,e})(),r})(),n.BotProgressIndicatorMetadata=(function(){function r(i){if(this.stepsMetadata=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.progressDescription=e.string();break}case 2:{s.stepsMetadata&&s.stepsMetadata.length||(s.stepsMetadata=[]),s.stepsMetadata.push(E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotProgressIndicatorMetadata)return e;var a=new E.proto.BotProgressIndicatorMetadata;if(e.progressDescription!=null&&(a.progressDescription=String(e.progressDescription)),e.stepsMetadata){if(!Array.isArray(e.stepsMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.stepsMetadata: array expected");a.stepsMetadata=[];for(var A=0;A>>3){case 1:{c.statusTitle=A.string();break}case 2:{c.statusBody=A.string();break}case 3:{c.sourcesMetadata&&c.sourcesMetadata.length||(c.sourcesMetadata=[]),c.sourcesMetadata.push(E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.decode(A,A.uint32()));break}case 4:{c.status=A.int32();break}case 5:{c.isReasoning=A.bool();break}case 6:{c.isEnhancedSearch=A.bool();break}case 7:{c.sections&&c.sections.length||(c.sections=[]),c.sections.push(E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata.decode(A,A.uint32()));break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata)return A;var t=new E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata;if(A.statusTitle!=null&&(t.statusTitle=String(A.statusTitle)),A.statusBody!=null&&(t.statusBody=String(A.statusBody)),A.sourcesMetadata){if(!Array.isArray(A.sourcesMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.sourcesMetadata: array expected");t.sourcesMetadata=[];for(var s=0;s>>3){case 1:{p.title=s.string();break}case 2:{p.provider=s.int32();break}case 3:{p.sourceUrl=s.string();break}case 4:{p.favIconUrl=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata)return s;var g=new E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata;switch(s.title!=null&&(g.title=String(s.title)),s.provider){default:if(typeof s.provider=="number"){g.provider=s.provider;break}break;case"UNKNOWN_PROVIDER":case 0:g.provider=0;break;case"OTHER":case 1:g.provider=1;break;case"GOOGLE":case 2:g.provider=2;break;case"BING":case 3:g.provider=3;break}return s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.favIconUrl!=null&&(g.favIconUrl=String(s.favIconUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.provider!=null&&s.hasOwnProperty("provider")&&(c.provider=g.enums===String?E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotSearchSourceProvider[s.provider]===void 0?s.provider:E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotSearchSourceProvider[s.provider]:s.provider,g.oneofs&&(c._provider="provider")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.favIconUrl!=null&&s.hasOwnProperty("favIconUrl")&&(c.favIconUrl=s.favIconUrl,g.oneofs&&(c._favIconUrl="favIconUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata"},a})(),i.BotPlanningSearchSourcesMetadata=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.sourceTitle=s.string();break}case 2:{p.provider=s.int32();break}case 3:{p.sourceUrl=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata)return s;var g=new E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata;switch(s.sourceTitle!=null&&(g.sourceTitle=String(s.sourceTitle)),s.provider){default:if(typeof s.provider=="number"){g.provider=s.provider;break}break;case"UNKNOWN":case 0:g.provider=0;break;case"OTHER":case 1:g.provider=1;break;case"GOOGLE":case 2:g.provider=2;break;case"BING":case 3:g.provider=3;break}return s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.sourceTitle!=null&&s.hasOwnProperty("sourceTitle")&&(c.sourceTitle=s.sourceTitle,g.oneofs&&(c._sourceTitle="sourceTitle")),s.provider!=null&&s.hasOwnProperty("provider")&&(c.provider=g.enums===String?E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.BotPlanningSearchSourceProvider[s.provider]===void 0?s.provider:E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.BotPlanningSearchSourceProvider[s.provider]:s.provider,g.oneofs&&(c._provider="provider")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata"},a.BotPlanningSearchSourceProvider=(function(){let t={},s=Object.create(t);return s[t[0]="UNKNOWN"]=0,s[t[1]="OTHER"]=1,s[t[2]="GOOGLE"]=2,s[t[3]="BING"]=3,s})(),a})(),i.BotPlanningStepSectionMetadata=(function(){function a(t){if(this.sourcesMetadata=[],t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.sectionTitle=s.string();break}case 2:{p.sectionBody=s.string();break}case 3:{p.sourcesMetadata&&p.sourcesMetadata.length||(p.sourcesMetadata=[]),p.sourcesMetadata.push(E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata)return s;var g=new E.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata;if(s.sectionTitle!=null&&(g.sectionTitle=String(s.sectionTitle)),s.sectionBody!=null&&(g.sectionBody=String(s.sectionBody)),s.sourcesMetadata){if(!Array.isArray(s.sourcesMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata.sourcesMetadata: array expected");g.sourcesMetadata=[];for(var c=0;c>>3){case 1:{s.promotionType=e.int32();break}case 2:{s.buttonTitle=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotPromotionMessageMetadata)return e;var a=new E.proto.BotPromotionMessageMetadata;switch(e.promotionType){default:if(typeof e.promotionType=="number"){a.promotionType=e.promotionType;break}break;case"UNKNOWN_TYPE":case 0:a.promotionType=0;break;case"C50":case 1:a.promotionType=1;break;case"SURVEY_PLATFORM":case 2:a.promotionType=2;break}return e.buttonTitle!=null&&(a.buttonTitle=String(e.buttonTitle)),a},r.toObject=function(e,a){a||(a={});var A={};return e.promotionType!=null&&e.hasOwnProperty("promotionType")&&(A.promotionType=a.enums===String?E.proto.BotPromotionMessageMetadata.BotPromotionType[e.promotionType]===void 0?e.promotionType:E.proto.BotPromotionMessageMetadata.BotPromotionType[e.promotionType]:e.promotionType,a.oneofs&&(A._promotionType="promotionType")),e.buttonTitle!=null&&e.hasOwnProperty("buttonTitle")&&(A.buttonTitle=e.buttonTitle,a.oneofs&&(A._buttonTitle="buttonTitle")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPromotionMessageMetadata"},r.BotPromotionType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="C50"]=1,e[i[2]="SURVEY_PLATFORM"]=2,e})(),r})(),n.BotPromptSuggestion=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.prompt=e.string();break}case 2:{s.promptId=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotPromptSuggestion)return e;var a=new E.proto.BotPromptSuggestion;return e.prompt!=null&&(a.prompt=String(e.prompt)),e.promptId!=null&&(a.promptId=String(e.promptId)),a},r.toObject=function(e,a){a||(a={});var A={};return e.prompt!=null&&e.hasOwnProperty("prompt")&&(A.prompt=e.prompt,a.oneofs&&(A._prompt="prompt")),e.promptId!=null&&e.hasOwnProperty("promptId")&&(A.promptId=e.promptId,a.oneofs&&(A._promptId="promptId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPromptSuggestion"},r})(),n.BotPromptSuggestions=(function(){function r(o){if(this.suggestions=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.suggestions&&t.suggestions.length||(t.suggestions=[]),t.suggestions.push(E.proto.BotPromptSuggestion.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.BotPromptSuggestions)return i;var e=new E.proto.BotPromptSuggestions;if(i.suggestions){if(!Array.isArray(i.suggestions))throw TypeError(".proto.BotPromptSuggestions.suggestions: array expected");e.suggestions=[];for(var a=0;a>>3){case 1:{t.botFeatureQuotaMetadata&&t.botFeatureQuotaMetadata.length||(t.botFeatureQuotaMetadata=[]),t.botFeatureQuotaMetadata.push(E.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.BotQuotaMetadata)return i;var e=new E.proto.BotQuotaMetadata;if(i.botFeatureQuotaMetadata){if(!Array.isArray(i.botFeatureQuotaMetadata))throw TypeError(".proto.BotQuotaMetadata.botFeatureQuotaMetadata: array expected");e.botFeatureQuotaMetadata=[];for(var a=0;a>>3){case 1:{g.featureType=a.int32();break}case 2:{g.remainingQuota=a.uint32();break}case 3:{g.expirationTimestamp=a.uint64();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof E.proto.BotQuotaMetadata.BotFeatureQuotaMetadata)return a;var A=new E.proto.BotQuotaMetadata.BotFeatureQuotaMetadata;switch(a.featureType){default:if(typeof a.featureType=="number"){A.featureType=a.featureType;break}break;case"UNKNOWN_FEATURE":case 0:A.featureType=0;break;case"REASONING_FEATURE":case 1:A.featureType=1;break}return a.remainingQuota!=null&&(A.remainingQuota=a.remainingQuota>>>0),a.expirationTimestamp!=null&&(I.Long?(A.expirationTimestamp=I.Long.fromValue(a.expirationTimestamp)).unsigned=!0:typeof a.expirationTimestamp=="string"?A.expirationTimestamp=parseInt(a.expirationTimestamp,10):typeof a.expirationTimestamp=="number"?A.expirationTimestamp=a.expirationTimestamp:typeof a.expirationTimestamp=="object"&&(A.expirationTimestamp=new I.LongBits(a.expirationTimestamp.low>>>0,a.expirationTimestamp.high>>>0).toNumber(!0))),A},o.toObject=function(a,A){A||(A={});var t={};return a.featureType!=null&&a.hasOwnProperty("featureType")&&(t.featureType=A.enums===String?E.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.BotFeatureType[a.featureType]===void 0?a.featureType:E.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.BotFeatureType[a.featureType]:a.featureType,A.oneofs&&(t._featureType="featureType")),a.remainingQuota!=null&&a.hasOwnProperty("remainingQuota")&&(t.remainingQuota=a.remainingQuota,A.oneofs&&(t._remainingQuota="remainingQuota")),a.expirationTimestamp!=null&&a.hasOwnProperty("expirationTimestamp")&&(typeof a.expirationTimestamp=="number"?t.expirationTimestamp=A.longs===String?String(a.expirationTimestamp):a.expirationTimestamp:t.expirationTimestamp=A.longs===String?re(a.expirationTimestamp,!0):A.longs===Number?ae(a.expirationTimestamp,!0):a.expirationTimestamp,A.oneofs&&(t._expirationTimestamp="expirationTimestamp")),t},o.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.BotQuotaMetadata.BotFeatureQuotaMetadata"},o.BotFeatureType=(function(){let e={},a=Object.create(e);return a[e[0]="UNKNOWN_FEATURE"]=0,a[e[1]="REASONING_FEATURE"]=1,a})(),o})(),r})(),n.BotReminderMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.requestMessageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.action=e.int32();break}case 3:{s.name=e.string();break}case 4:{s.nextTriggerTimestamp=e.uint64();break}case 5:{s.frequency=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotReminderMetadata)return e;var a=new E.proto.BotReminderMetadata;if(e.requestMessageKey!=null){if(typeof e.requestMessageKey!="object")throw TypeError(".proto.BotReminderMetadata.requestMessageKey: object expected");a.requestMessageKey=E.proto.MessageKey.fromObject(e.requestMessageKey)}switch(e.action){default:if(typeof e.action=="number"){a.action=e.action;break}break;case"NOTIFY":case 1:a.action=1;break;case"CREATE":case 2:a.action=2;break;case"DELETE":case 3:a.action=3;break;case"UPDATE":case 4:a.action=4;break}switch(e.name!=null&&(a.name=String(e.name)),e.nextTriggerTimestamp!=null&&(I.Long?(a.nextTriggerTimestamp=I.Long.fromValue(e.nextTriggerTimestamp)).unsigned=!0:typeof e.nextTriggerTimestamp=="string"?a.nextTriggerTimestamp=parseInt(e.nextTriggerTimestamp,10):typeof e.nextTriggerTimestamp=="number"?a.nextTriggerTimestamp=e.nextTriggerTimestamp:typeof e.nextTriggerTimestamp=="object"&&(a.nextTriggerTimestamp=new I.LongBits(e.nextTriggerTimestamp.low>>>0,e.nextTriggerTimestamp.high>>>0).toNumber(!0))),e.frequency){default:if(typeof e.frequency=="number"){a.frequency=e.frequency;break}break;case"ONCE":case 1:a.frequency=1;break;case"DAILY":case 2:a.frequency=2;break;case"WEEKLY":case 3:a.frequency=3;break;case"BIWEEKLY":case 4:a.frequency=4;break;case"MONTHLY":case 5:a.frequency=5;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.requestMessageKey!=null&&e.hasOwnProperty("requestMessageKey")&&(A.requestMessageKey=E.proto.MessageKey.toObject(e.requestMessageKey,a),a.oneofs&&(A._requestMessageKey="requestMessageKey")),e.action!=null&&e.hasOwnProperty("action")&&(A.action=a.enums===String?E.proto.BotReminderMetadata.ReminderAction[e.action]===void 0?e.action:E.proto.BotReminderMetadata.ReminderAction[e.action]:e.action,a.oneofs&&(A._action="action")),e.name!=null&&e.hasOwnProperty("name")&&(A.name=e.name,a.oneofs&&(A._name="name")),e.nextTriggerTimestamp!=null&&e.hasOwnProperty("nextTriggerTimestamp")&&(typeof e.nextTriggerTimestamp=="number"?A.nextTriggerTimestamp=a.longs===String?String(e.nextTriggerTimestamp):e.nextTriggerTimestamp:A.nextTriggerTimestamp=a.longs===String?re(e.nextTriggerTimestamp,!0):a.longs===Number?ae(e.nextTriggerTimestamp,!0):e.nextTriggerTimestamp,a.oneofs&&(A._nextTriggerTimestamp="nextTriggerTimestamp")),e.frequency!=null&&e.hasOwnProperty("frequency")&&(A.frequency=a.enums===String?E.proto.BotReminderMetadata.ReminderFrequency[e.frequency]===void 0?e.frequency:E.proto.BotReminderMetadata.ReminderFrequency[e.frequency]:e.frequency,a.oneofs&&(A._frequency="frequency")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotReminderMetadata"},r.ReminderAction=(function(){let i={},e=Object.create(i);return e[i[1]="NOTIFY"]=1,e[i[2]="CREATE"]=2,e[i[3]="DELETE"]=3,e[i[4]="UPDATE"]=4,e})(),r.ReminderFrequency=(function(){let i={},e=Object.create(i);return e[i[1]="ONCE"]=1,e[i[2]="DAILY"]=2,e[i[3]="WEEKLY"]=3,e[i[4]="BIWEEKLY"]=4,e[i[5]="MONTHLY"]=5,e})(),r})(),n.BotRenderingMetadata=(function(){function r(o){if(this.keywords=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.keywords&&t.keywords.length||(t.keywords=[]),t.keywords.push(E.proto.BotRenderingMetadata.Keyword.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.BotRenderingMetadata)return i;var e=new E.proto.BotRenderingMetadata;if(i.keywords){if(!Array.isArray(i.keywords))throw TypeError(".proto.BotRenderingMetadata.keywords: array expected");e.keywords=[];for(var a=0;a>>3){case 1:{g.value=a.string();break}case 2:{g.associatedPrompts&&g.associatedPrompts.length||(g.associatedPrompts=[]),g.associatedPrompts.push(a.string());break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof E.proto.BotRenderingMetadata.Keyword)return a;var A=new E.proto.BotRenderingMetadata.Keyword;if(a.value!=null&&(A.value=String(a.value)),a.associatedPrompts){if(!Array.isArray(a.associatedPrompts))throw TypeError(".proto.BotRenderingMetadata.Keyword.associatedPrompts: array expected");A.associatedPrompts=[];for(var t=0;t>>3){case 1:{s.sessionId=e.string();break}case 2:{s.sessionSource=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotSessionMetadata)return e;var a=new E.proto.BotSessionMetadata;switch(e.sessionId!=null&&(a.sessionId=String(e.sessionId)),e.sessionSource){default:if(typeof e.sessionSource=="number"){a.sessionSource=e.sessionSource;break}break;case"NONE":case 0:a.sessionSource=0;break;case"NULL_STATE":case 1:a.sessionSource=1;break;case"TYPEAHEAD":case 2:a.sessionSource=2;break;case"USER_INPUT":case 3:a.sessionSource=3;break;case"EMU_FLASH":case 4:a.sessionSource=4;break;case"EMU_FLASH_FOLLOWUP":case 5:a.sessionSource=5;break;case"VOICE":case 6:a.sessionSource=6;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.sessionId!=null&&e.hasOwnProperty("sessionId")&&(A.sessionId=e.sessionId,a.oneofs&&(A._sessionId="sessionId")),e.sessionSource!=null&&e.hasOwnProperty("sessionSource")&&(A.sessionSource=a.enums===String?E.proto.BotSessionSource[e.sessionSource]===void 0?e.sessionSource:E.proto.BotSessionSource[e.sessionSource]:e.sessionSource,a.oneofs&&(A._sessionSource="sessionSource")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotSessionMetadata"},r})(),n.BotSessionSource=(function(){let r={},o=Object.create(r);return o[r[0]="NONE"]=0,o[r[1]="NULL_STATE"]=1,o[r[2]="TYPEAHEAD"]=2,o[r[3]="USER_INPUT"]=3,o[r[4]="EMU_FLASH"]=4,o[r[5]="EMU_FLASH_FOLLOWUP"]=5,o[r[6]="VOICE"]=6,o})(),n.BotSignatureVerificationMetadata=(function(){function r(o){if(this.proofs=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.proofs&&t.proofs.length||(t.proofs=[]),t.proofs.push(E.proto.BotSignatureVerificationUseCaseProof.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.BotSignatureVerificationMetadata)return i;var e=new E.proto.BotSignatureVerificationMetadata;if(i.proofs){if(!Array.isArray(i.proofs))throw TypeError(".proto.BotSignatureVerificationMetadata.proofs: array expected");e.proofs=[];for(var a=0;a>>3){case 1:{s.version=e.int32();break}case 2:{s.useCase=e.int32();break}case 3:{s.signature=e.bytes();break}case 4:{s.certificateChain&&s.certificateChain.length||(s.certificateChain=[]),s.certificateChain.push(e.bytes());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotSignatureVerificationUseCaseProof)return e;var a=new E.proto.BotSignatureVerificationUseCaseProof;switch(e.version!=null&&(a.version=e.version|0),e.useCase){default:if(typeof e.useCase=="number"){a.useCase=e.useCase;break}break;case"UNSPECIFIED":case 0:a.useCase=0;break;case"WA_BOT_MSG":case 1:a.useCase=1;break}if(e.signature!=null&&(typeof e.signature=="string"?I.base64.decode(e.signature,a.signature=I.newBuffer(I.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.certificateChain){if(!Array.isArray(e.certificateChain))throw TypeError(".proto.BotSignatureVerificationUseCaseProof.certificateChain: array expected");a.certificateChain=[];for(var A=0;A=0&&(a.certificateChain[A]=e.certificateChain[A])}return a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.certificateChain=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),e.useCase!=null&&e.hasOwnProperty("useCase")&&(A.useCase=a.enums===String?E.proto.BotSignatureVerificationUseCaseProof.BotSignatureUseCase[e.useCase]===void 0?e.useCase:E.proto.BotSignatureVerificationUseCaseProof.BotSignatureUseCase[e.useCase]:e.useCase,a.oneofs&&(A._useCase="useCase")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?I.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.certificateChain&&e.certificateChain.length){A.certificateChain=[];for(var t=0;t>>3){case 1:{t.sources&&t.sources.length||(t.sources=[]),t.sources.push(E.proto.BotSourcesMetadata.BotSourceItem.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.BotSourcesMetadata)return i;var e=new E.proto.BotSourcesMetadata;if(i.sources){if(!Array.isArray(i.sources))throw TypeError(".proto.BotSourcesMetadata.sources: array expected");e.sources=[];for(var a=0;a>>3){case 1:{g.provider=a.int32();break}case 2:{g.thumbnailCdnUrl=a.string();break}case 3:{g.sourceProviderUrl=a.string();break}case 4:{g.sourceQuery=a.string();break}case 5:{g.faviconCdnUrl=a.string();break}case 6:{g.citationNumber=a.uint32();break}case 7:{g.sourceTitle=a.string();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof E.proto.BotSourcesMetadata.BotSourceItem)return a;var A=new E.proto.BotSourcesMetadata.BotSourceItem;switch(a.provider){default:if(typeof a.provider=="number"){A.provider=a.provider;break}break;case"UNKNOWN":case 0:A.provider=0;break;case"BING":case 1:A.provider=1;break;case"GOOGLE":case 2:A.provider=2;break;case"SUPPORT":case 3:A.provider=3;break;case"OTHER":case 4:A.provider=4;break}return a.thumbnailCdnUrl!=null&&(A.thumbnailCdnUrl=String(a.thumbnailCdnUrl)),a.sourceProviderUrl!=null&&(A.sourceProviderUrl=String(a.sourceProviderUrl)),a.sourceQuery!=null&&(A.sourceQuery=String(a.sourceQuery)),a.faviconCdnUrl!=null&&(A.faviconCdnUrl=String(a.faviconCdnUrl)),a.citationNumber!=null&&(A.citationNumber=a.citationNumber>>>0),a.sourceTitle!=null&&(A.sourceTitle=String(a.sourceTitle)),A},o.toObject=function(a,A){A||(A={});var t={};return a.provider!=null&&a.hasOwnProperty("provider")&&(t.provider=A.enums===String?E.proto.BotSourcesMetadata.BotSourceItem.SourceProvider[a.provider]===void 0?a.provider:E.proto.BotSourcesMetadata.BotSourceItem.SourceProvider[a.provider]:a.provider,A.oneofs&&(t._provider="provider")),a.thumbnailCdnUrl!=null&&a.hasOwnProperty("thumbnailCdnUrl")&&(t.thumbnailCdnUrl=a.thumbnailCdnUrl,A.oneofs&&(t._thumbnailCdnUrl="thumbnailCdnUrl")),a.sourceProviderUrl!=null&&a.hasOwnProperty("sourceProviderUrl")&&(t.sourceProviderUrl=a.sourceProviderUrl,A.oneofs&&(t._sourceProviderUrl="sourceProviderUrl")),a.sourceQuery!=null&&a.hasOwnProperty("sourceQuery")&&(t.sourceQuery=a.sourceQuery,A.oneofs&&(t._sourceQuery="sourceQuery")),a.faviconCdnUrl!=null&&a.hasOwnProperty("faviconCdnUrl")&&(t.faviconCdnUrl=a.faviconCdnUrl,A.oneofs&&(t._faviconCdnUrl="faviconCdnUrl")),a.citationNumber!=null&&a.hasOwnProperty("citationNumber")&&(t.citationNumber=a.citationNumber,A.oneofs&&(t._citationNumber="citationNumber")),a.sourceTitle!=null&&a.hasOwnProperty("sourceTitle")&&(t.sourceTitle=a.sourceTitle,A.oneofs&&(t._sourceTitle="sourceTitle")),t},o.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.BotSourcesMetadata.BotSourceItem"},o.SourceProvider=(function(){let e={},a=Object.create(e);return a[e[0]="UNKNOWN"]=0,a[e[1]="BING"]=1,a[e[2]="GOOGLE"]=2,a[e[3]="SUPPORT"]=3,a[e[4]="OTHER"]=4,a})(),o})(),r})(),n.BotSuggestedPromptMetadata=(function(){function r(i){if(this.suggestedPrompts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.suggestedPrompts&&s.suggestedPrompts.length||(s.suggestedPrompts=[]),s.suggestedPrompts.push(e.string());break}case 2:{s.selectedPromptIndex=e.uint32();break}case 3:{s.promptSuggestions=E.proto.BotPromptSuggestions.decode(e,e.uint32());break}case 4:{s.selectedPromptId=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotSuggestedPromptMetadata)return e;var a=new E.proto.BotSuggestedPromptMetadata;if(e.suggestedPrompts){if(!Array.isArray(e.suggestedPrompts))throw TypeError(".proto.BotSuggestedPromptMetadata.suggestedPrompts: array expected");a.suggestedPrompts=[];for(var A=0;A>>0),e.promptSuggestions!=null){if(typeof e.promptSuggestions!="object")throw TypeError(".proto.BotSuggestedPromptMetadata.promptSuggestions: object expected");a.promptSuggestions=E.proto.BotPromptSuggestions.fromObject(e.promptSuggestions)}return e.selectedPromptId!=null&&(a.selectedPromptId=String(e.selectedPromptId)),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.suggestedPrompts=[]),e.suggestedPrompts&&e.suggestedPrompts.length){A.suggestedPrompts=[];for(var t=0;t>>3){case 1:{s.sbsMetadata=E.proto.BotUnifiedResponseMutation.SideBySideMetadata.decode(e,e.uint32());break}case 2:{s.mediaDetailsMetadataList&&s.mediaDetailsMetadataList.length||(s.mediaDetailsMetadataList=[]),s.mediaDetailsMetadataList.push(E.proto.BotUnifiedResponseMutation.MediaDetailsMetadata.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.BotUnifiedResponseMutation)return e;var a=new E.proto.BotUnifiedResponseMutation;if(e.sbsMetadata!=null){if(typeof e.sbsMetadata!="object")throw TypeError(".proto.BotUnifiedResponseMutation.sbsMetadata: object expected");a.sbsMetadata=E.proto.BotUnifiedResponseMutation.SideBySideMetadata.fromObject(e.sbsMetadata)}if(e.mediaDetailsMetadataList){if(!Array.isArray(e.mediaDetailsMetadataList))throw TypeError(".proto.BotUnifiedResponseMutation.mediaDetailsMetadataList: array expected");a.mediaDetailsMetadataList=[];for(var A=0;A>>3){case 1:{c.id=A.string();break}case 2:{c.highResMedia=E.proto.BotMediaMetadata.decode(A,A.uint32());break}case 3:{c.previewMedia=E.proto.BotMediaMetadata.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.BotUnifiedResponseMutation.MediaDetailsMetadata)return A;var t=new E.proto.BotUnifiedResponseMutation.MediaDetailsMetadata;if(A.id!=null&&(t.id=String(A.id)),A.highResMedia!=null){if(typeof A.highResMedia!="object")throw TypeError(".proto.BotUnifiedResponseMutation.MediaDetailsMetadata.highResMedia: object expected");t.highResMedia=E.proto.BotMediaMetadata.fromObject(A.highResMedia)}if(A.previewMedia!=null){if(typeof A.previewMedia!="object")throw TypeError(".proto.BotUnifiedResponseMutation.MediaDetailsMetadata.previewMedia: object expected");t.previewMedia=E.proto.BotMediaMetadata.fromObject(A.previewMedia)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,t.oneofs&&(s._id="id")),A.highResMedia!=null&&A.hasOwnProperty("highResMedia")&&(s.highResMedia=E.proto.BotMediaMetadata.toObject(A.highResMedia,t),t.oneofs&&(s._highResMedia="highResMedia")),A.previewMedia!=null&&A.hasOwnProperty("previewMedia")&&(s.previewMedia=E.proto.BotMediaMetadata.toObject(A.previewMedia,t),t.oneofs&&(s._previewMedia="previewMedia")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotUnifiedResponseMutation.MediaDetailsMetadata"},i})(),r.SideBySideMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.primaryResponseId=A.string();break}case 2:{c.surveyCtaHasRendered=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.BotUnifiedResponseMutation.SideBySideMetadata)return A;var t=new E.proto.BotUnifiedResponseMutation.SideBySideMetadata;return A.primaryResponseId!=null&&(t.primaryResponseId=String(A.primaryResponseId)),A.surveyCtaHasRendered!=null&&(t.surveyCtaHasRendered=!!A.surveyCtaHasRendered),t},i.toObject=function(A,t){t||(t={});var s={};return A.primaryResponseId!=null&&A.hasOwnProperty("primaryResponseId")&&(s.primaryResponseId=A.primaryResponseId,t.oneofs&&(s._primaryResponseId="primaryResponseId")),A.surveyCtaHasRendered!=null&&A.hasOwnProperty("surveyCtaHasRendered")&&(s.surveyCtaHasRendered=A.surveyCtaHasRendered,t.oneofs&&(s._surveyCtaHasRendered="surveyCtaHasRendered")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotUnifiedResponseMutation.SideBySideMetadata"},i})(),r})(),n.CallLogRecord=(function(){function r(i){if(this.participants=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.callResult=e.int32();break}case 2:{s.isDndMode=e.bool();break}case 3:{s.silenceReason=e.int32();break}case 4:{s.duration=e.int64();break}case 5:{s.startTime=e.int64();break}case 6:{s.isIncoming=e.bool();break}case 7:{s.isVideo=e.bool();break}case 8:{s.isCallLink=e.bool();break}case 9:{s.callLinkToken=e.string();break}case 10:{s.scheduledCallId=e.string();break}case 11:{s.callId=e.string();break}case 12:{s.callCreatorJid=e.string();break}case 13:{s.groupJid=e.string();break}case 14:{s.participants&&s.participants.length||(s.participants=[]),s.participants.push(E.proto.CallLogRecord.ParticipantInfo.decode(e,e.uint32()));break}case 15:{s.callType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.CallLogRecord)return e;var a=new E.proto.CallLogRecord;switch(e.callResult){default:if(typeof e.callResult=="number"){a.callResult=e.callResult;break}break;case"CONNECTED":case 0:a.callResult=0;break;case"REJECTED":case 1:a.callResult=1;break;case"CANCELLED":case 2:a.callResult=2;break;case"ACCEPTEDELSEWHERE":case 3:a.callResult=3;break;case"MISSED":case 4:a.callResult=4;break;case"INVALID":case 5:a.callResult=5;break;case"UNAVAILABLE":case 6:a.callResult=6;break;case"UPCOMING":case 7:a.callResult=7;break;case"FAILED":case 8:a.callResult=8;break;case"ABANDONED":case 9:a.callResult=9;break;case"ONGOING":case 10:a.callResult=10;break}switch(e.isDndMode!=null&&(a.isDndMode=!!e.isDndMode),e.silenceReason){default:if(typeof e.silenceReason=="number"){a.silenceReason=e.silenceReason;break}break;case"NONE":case 0:a.silenceReason=0;break;case"SCHEDULED":case 1:a.silenceReason=1;break;case"PRIVACY":case 2:a.silenceReason=2;break;case"LIGHTWEIGHT":case 3:a.silenceReason=3;break}if(e.duration!=null&&(I.Long?(a.duration=I.Long.fromValue(e.duration)).unsigned=!1:typeof e.duration=="string"?a.duration=parseInt(e.duration,10):typeof e.duration=="number"?a.duration=e.duration:typeof e.duration=="object"&&(a.duration=new I.LongBits(e.duration.low>>>0,e.duration.high>>>0).toNumber())),e.startTime!=null&&(I.Long?(a.startTime=I.Long.fromValue(e.startTime)).unsigned=!1:typeof e.startTime=="string"?a.startTime=parseInt(e.startTime,10):typeof e.startTime=="number"?a.startTime=e.startTime:typeof e.startTime=="object"&&(a.startTime=new I.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber())),e.isIncoming!=null&&(a.isIncoming=!!e.isIncoming),e.isVideo!=null&&(a.isVideo=!!e.isVideo),e.isCallLink!=null&&(a.isCallLink=!!e.isCallLink),e.callLinkToken!=null&&(a.callLinkToken=String(e.callLinkToken)),e.scheduledCallId!=null&&(a.scheduledCallId=String(e.scheduledCallId)),e.callId!=null&&(a.callId=String(e.callId)),e.callCreatorJid!=null&&(a.callCreatorJid=String(e.callCreatorJid)),e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.participants){if(!Array.isArray(e.participants))throw TypeError(".proto.CallLogRecord.participants: array expected");a.participants=[];for(var A=0;A>>3){case 1:{c.userJid=A.string();break}case 2:{c.callResult=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.CallLogRecord.ParticipantInfo)return A;var t=new E.proto.CallLogRecord.ParticipantInfo;switch(A.userJid!=null&&(t.userJid=String(A.userJid)),A.callResult){default:if(typeof A.callResult=="number"){t.callResult=A.callResult;break}break;case"CONNECTED":case 0:t.callResult=0;break;case"REJECTED":case 1:t.callResult=1;break;case"CANCELLED":case 2:t.callResult=2;break;case"ACCEPTEDELSEWHERE":case 3:t.callResult=3;break;case"MISSED":case 4:t.callResult=4;break;case"INVALID":case 5:t.callResult=5;break;case"UNAVAILABLE":case 6:t.callResult=6;break;case"UPCOMING":case 7:t.callResult=7;break;case"FAILED":case 8:t.callResult=8;break;case"ABANDONED":case 9:t.callResult=9;break;case"ONGOING":case 10:t.callResult=10;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.userJid!=null&&A.hasOwnProperty("userJid")&&(s.userJid=A.userJid,t.oneofs&&(s._userJid="userJid")),A.callResult!=null&&A.hasOwnProperty("callResult")&&(s.callResult=t.enums===String?E.proto.CallLogRecord.CallResult[A.callResult]===void 0?A.callResult:E.proto.CallLogRecord.CallResult[A.callResult]:A.callResult,t.oneofs&&(s._callResult="callResult")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.CallLogRecord.ParticipantInfo"},i})(),r.SilenceReason=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="SCHEDULED"]=1,e[i[2]="PRIVACY"]=2,e[i[3]="LIGHTWEIGHT"]=3,e})(),r})(),n.CertChain=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.leaf=E.proto.CertChain.NoiseCertificate.decode(e,e.uint32());break}case 2:{s.intermediate=E.proto.CertChain.NoiseCertificate.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.CertChain)return e;var a=new E.proto.CertChain;if(e.leaf!=null){if(typeof e.leaf!="object")throw TypeError(".proto.CertChain.leaf: object expected");a.leaf=E.proto.CertChain.NoiseCertificate.fromObject(e.leaf)}if(e.intermediate!=null){if(typeof e.intermediate!="object")throw TypeError(".proto.CertChain.intermediate: object expected");a.intermediate=E.proto.CertChain.NoiseCertificate.fromObject(e.intermediate)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.leaf!=null&&e.hasOwnProperty("leaf")&&(A.leaf=E.proto.CertChain.NoiseCertificate.toObject(e.leaf,a),a.oneofs&&(A._leaf="leaf")),e.intermediate!=null&&e.hasOwnProperty("intermediate")&&(A.intermediate=E.proto.CertChain.NoiseCertificate.toObject(e.intermediate,a),a.oneofs&&(A._intermediate="intermediate")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CertChain"},r.NoiseCertificate=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.details=A.bytes();break}case 2:{c.signature=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.CertChain.NoiseCertificate)return A;var t=new E.proto.CertChain.NoiseCertificate;return A.details!=null&&(typeof A.details=="string"?I.base64.decode(A.details,t.details=I.newBuffer(I.base64.length(A.details)),0):A.details.length>=0&&(t.details=A.details)),A.signature!=null&&(typeof A.signature=="string"?I.base64.decode(A.signature,t.signature=I.newBuffer(I.base64.length(A.signature)),0):A.signature.length>=0&&(t.signature=A.signature)),t},i.toObject=function(A,t){t||(t={});var s={};return A.details!=null&&A.hasOwnProperty("details")&&(s.details=t.bytes===String?I.base64.encode(A.details,0,A.details.length):t.bytes===Array?Array.prototype.slice.call(A.details):A.details,t.oneofs&&(s._details="details")),A.signature!=null&&A.hasOwnProperty("signature")&&(s.signature=t.bytes===String?I.base64.encode(A.signature,0,A.signature.length):t.bytes===Array?Array.prototype.slice.call(A.signature):A.signature,t.oneofs&&(s._signature="signature")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.CertChain.NoiseCertificate"},i.Details=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.serial=s.uint32();break}case 2:{p.issuerSerial=s.uint32();break}case 3:{p.key=s.bytes();break}case 4:{p.notBefore=s.uint64();break}case 5:{p.notAfter=s.uint64();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.CertChain.NoiseCertificate.Details)return s;var g=new E.proto.CertChain.NoiseCertificate.Details;return s.serial!=null&&(g.serial=s.serial>>>0),s.issuerSerial!=null&&(g.issuerSerial=s.issuerSerial>>>0),s.key!=null&&(typeof s.key=="string"?I.base64.decode(s.key,g.key=I.newBuffer(I.base64.length(s.key)),0):s.key.length>=0&&(g.key=s.key)),s.notBefore!=null&&(I.Long?(g.notBefore=I.Long.fromValue(s.notBefore)).unsigned=!0:typeof s.notBefore=="string"?g.notBefore=parseInt(s.notBefore,10):typeof s.notBefore=="number"?g.notBefore=s.notBefore:typeof s.notBefore=="object"&&(g.notBefore=new I.LongBits(s.notBefore.low>>>0,s.notBefore.high>>>0).toNumber(!0))),s.notAfter!=null&&(I.Long?(g.notAfter=I.Long.fromValue(s.notAfter)).unsigned=!0:typeof s.notAfter=="string"?g.notAfter=parseInt(s.notAfter,10):typeof s.notAfter=="number"?g.notAfter=s.notAfter:typeof s.notAfter=="object"&&(g.notAfter=new I.LongBits(s.notAfter.low>>>0,s.notAfter.high>>>0).toNumber(!0))),g},a.toObject=function(s,g){g||(g={});var c={};return s.serial!=null&&s.hasOwnProperty("serial")&&(c.serial=s.serial,g.oneofs&&(c._serial="serial")),s.issuerSerial!=null&&s.hasOwnProperty("issuerSerial")&&(c.issuerSerial=s.issuerSerial,g.oneofs&&(c._issuerSerial="issuerSerial")),s.key!=null&&s.hasOwnProperty("key")&&(c.key=g.bytes===String?I.base64.encode(s.key,0,s.key.length):g.bytes===Array?Array.prototype.slice.call(s.key):s.key,g.oneofs&&(c._key="key")),s.notBefore!=null&&s.hasOwnProperty("notBefore")&&(typeof s.notBefore=="number"?c.notBefore=g.longs===String?String(s.notBefore):s.notBefore:c.notBefore=g.longs===String?re(s.notBefore,!0):g.longs===Number?ae(s.notBefore,!0):s.notBefore,g.oneofs&&(c._notBefore="notBefore")),s.notAfter!=null&&s.hasOwnProperty("notAfter")&&(typeof s.notAfter=="number"?c.notAfter=g.longs===String?String(s.notAfter):s.notAfter:c.notAfter=g.longs===String?re(s.notAfter,!0):g.longs===Number?ae(s.notAfter,!0):s.notAfter,g.oneofs&&(c._notAfter="notAfter")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.CertChain.NoiseCertificate.Details"},a})(),i})(),r})(),n.ChatLockSettings=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.hideLockedChats=e.bool();break}case 2:{s.secretCode=E.proto.UserPassword.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ChatLockSettings)return e;var a=new E.proto.ChatLockSettings;if(e.hideLockedChats!=null&&(a.hideLockedChats=!!e.hideLockedChats),e.secretCode!=null){if(typeof e.secretCode!="object")throw TypeError(".proto.ChatLockSettings.secretCode: object expected");a.secretCode=E.proto.UserPassword.fromObject(e.secretCode)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.hideLockedChats!=null&&e.hasOwnProperty("hideLockedChats")&&(A.hideLockedChats=e.hideLockedChats,a.oneofs&&(A._hideLockedChats="hideLockedChats")),e.secretCode!=null&&e.hasOwnProperty("secretCode")&&(A.secretCode=E.proto.UserPassword.toObject(e.secretCode,a),a.oneofs&&(A._secretCode="secretCode")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ChatLockSettings"},r})(),n.ChatRowOpaqueData=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.draftMessage=E.proto.ChatRowOpaqueData.DraftMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ChatRowOpaqueData)return e;var a=new E.proto.ChatRowOpaqueData;if(e.draftMessage!=null){if(typeof e.draftMessage!="object")throw TypeError(".proto.ChatRowOpaqueData.draftMessage: object expected");a.draftMessage=E.proto.ChatRowOpaqueData.DraftMessage.fromObject(e.draftMessage)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.draftMessage!=null&&e.hasOwnProperty("draftMessage")&&(A.draftMessage=E.proto.ChatRowOpaqueData.DraftMessage.toObject(e.draftMessage,a),a.oneofs&&(A._draftMessage="draftMessage")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ChatRowOpaqueData"},r.DraftMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.text=A.string();break}case 2:{c.omittedUrl=A.string();break}case 3:{c.ctwaContextLinkData=E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.decode(A,A.uint32());break}case 4:{c.ctwaContext=E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.decode(A,A.uint32());break}case 5:{c.timestamp=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ChatRowOpaqueData.DraftMessage)return A;var t=new E.proto.ChatRowOpaqueData.DraftMessage;if(A.text!=null&&(t.text=String(A.text)),A.omittedUrl!=null&&(t.omittedUrl=String(A.omittedUrl)),A.ctwaContextLinkData!=null){if(typeof A.ctwaContextLinkData!="object")throw TypeError(".proto.ChatRowOpaqueData.DraftMessage.ctwaContextLinkData: object expected");t.ctwaContextLinkData=E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.fromObject(A.ctwaContextLinkData)}if(A.ctwaContext!=null){if(typeof A.ctwaContext!="object")throw TypeError(".proto.ChatRowOpaqueData.DraftMessage.ctwaContext: object expected");t.ctwaContext=E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.fromObject(A.ctwaContext)}return A.timestamp!=null&&(I.Long?(t.timestamp=I.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?t.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?t.timestamp=A.timestamp:typeof A.timestamp=="object"&&(t.timestamp=new I.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,t.oneofs&&(s._text="text")),A.omittedUrl!=null&&A.hasOwnProperty("omittedUrl")&&(s.omittedUrl=A.omittedUrl,t.oneofs&&(s._omittedUrl="omittedUrl")),A.ctwaContextLinkData!=null&&A.hasOwnProperty("ctwaContextLinkData")&&(s.ctwaContextLinkData=E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.toObject(A.ctwaContextLinkData,t),t.oneofs&&(s._ctwaContextLinkData="ctwaContextLinkData")),A.ctwaContext!=null&&A.hasOwnProperty("ctwaContext")&&(s.ctwaContext=E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.toObject(A.ctwaContext,t),t.oneofs&&(s._ctwaContext="ctwaContext")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=t.longs===String?String(A.timestamp):A.timestamp:s.timestamp=t.longs===String?re(A.timestamp):t.longs===Number?ae(A.timestamp):A.timestamp,t.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ChatRowOpaqueData.DraftMessage"},i.CtwaContextData=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.conversionSource=s.string();break}case 2:{p.conversionData=s.bytes();break}case 3:{p.sourceUrl=s.string();break}case 4:{p.sourceId=s.string();break}case 5:{p.sourceType=s.string();break}case 6:{p.title=s.string();break}case 7:{p.description=s.string();break}case 8:{p.thumbnail=s.string();break}case 9:{p.thumbnailUrl=s.string();break}case 10:{p.mediaType=s.int32();break}case 11:{p.mediaUrl=s.string();break}case 12:{p.isSuspiciousLink=s.bool();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData)return s;var g=new E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData;switch(s.conversionSource!=null&&(g.conversionSource=String(s.conversionSource)),s.conversionData!=null&&(typeof s.conversionData=="string"?I.base64.decode(s.conversionData,g.conversionData=I.newBuffer(I.base64.length(s.conversionData)),0):s.conversionData.length>=0&&(g.conversionData=s.conversionData)),s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.sourceId!=null&&(g.sourceId=String(s.sourceId)),s.sourceType!=null&&(g.sourceType=String(s.sourceType)),s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.thumbnail!=null&&(g.thumbnail=String(s.thumbnail)),s.thumbnailUrl!=null&&(g.thumbnailUrl=String(s.thumbnailUrl)),s.mediaType){default:if(typeof s.mediaType=="number"){g.mediaType=s.mediaType;break}break;case"NONE":case 0:g.mediaType=0;break;case"IMAGE":case 1:g.mediaType=1;break;case"VIDEO":case 2:g.mediaType=2;break}return s.mediaUrl!=null&&(g.mediaUrl=String(s.mediaUrl)),s.isSuspiciousLink!=null&&(g.isSuspiciousLink=!!s.isSuspiciousLink),g},a.toObject=function(s,g){g||(g={});var c={};return s.conversionSource!=null&&s.hasOwnProperty("conversionSource")&&(c.conversionSource=s.conversionSource,g.oneofs&&(c._conversionSource="conversionSource")),s.conversionData!=null&&s.hasOwnProperty("conversionData")&&(c.conversionData=g.bytes===String?I.base64.encode(s.conversionData,0,s.conversionData.length):g.bytes===Array?Array.prototype.slice.call(s.conversionData):s.conversionData,g.oneofs&&(c._conversionData="conversionData")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.sourceId!=null&&s.hasOwnProperty("sourceId")&&(c.sourceId=s.sourceId,g.oneofs&&(c._sourceId="sourceId")),s.sourceType!=null&&s.hasOwnProperty("sourceType")&&(c.sourceType=s.sourceType,g.oneofs&&(c._sourceType="sourceType")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.thumbnail!=null&&s.hasOwnProperty("thumbnail")&&(c.thumbnail=s.thumbnail,g.oneofs&&(c._thumbnail="thumbnail")),s.thumbnailUrl!=null&&s.hasOwnProperty("thumbnailUrl")&&(c.thumbnailUrl=s.thumbnailUrl,g.oneofs&&(c._thumbnailUrl="thumbnailUrl")),s.mediaType!=null&&s.hasOwnProperty("mediaType")&&(c.mediaType=g.enums===String?E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.ContextInfoExternalAdReplyInfoMediaType[s.mediaType]===void 0?s.mediaType:E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.ContextInfoExternalAdReplyInfoMediaType[s.mediaType]:s.mediaType,g.oneofs&&(c._mediaType="mediaType")),s.mediaUrl!=null&&s.hasOwnProperty("mediaUrl")&&(c.mediaUrl=s.mediaUrl,g.oneofs&&(c._mediaUrl="mediaUrl")),s.isSuspiciousLink!=null&&s.hasOwnProperty("isSuspiciousLink")&&(c.isSuspiciousLink=s.isSuspiciousLink,g.oneofs&&(c._isSuspiciousLink="isSuspiciousLink")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ChatRowOpaqueData.DraftMessage.CtwaContextData"},a.ContextInfoExternalAdReplyInfoMediaType=(function(){let t={},s=Object.create(t);return s[t[0]="NONE"]=0,s[t[1]="IMAGE"]=1,s[t[2]="VIDEO"]=2,s})(),a})(),i.CtwaContextLinkData=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.context=s.string();break}case 2:{p.sourceUrl=s.string();break}case 3:{p.icebreaker=s.string();break}case 4:{p.phone=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData)return s;var g=new E.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData;return s.context!=null&&(g.context=String(s.context)),s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.icebreaker!=null&&(g.icebreaker=String(s.icebreaker)),s.phone!=null&&(g.phone=String(s.phone)),g},a.toObject=function(s,g){g||(g={});var c={};return s.context!=null&&s.hasOwnProperty("context")&&(c.context=s.context,g.oneofs&&(c._context="context")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.icebreaker!=null&&s.hasOwnProperty("icebreaker")&&(c.icebreaker=s.icebreaker,g.oneofs&&(c._icebreaker="icebreaker")),s.phone!=null&&s.hasOwnProperty("phone")&&(c.phone=s.phone,g.oneofs&&(c._phone="phone")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData"},a})(),i})(),r})(),n.Citation=(function(){function r(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.title=i.string();break}case 2:{t.subtitle=i.string();break}case 3:{t.cmsId=i.string();break}case 4:{t.imageUrl=i.string();break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.Citation)return i;var e=new E.proto.Citation;return i.title!=null&&(e.title=String(i.title)),i.subtitle!=null&&(e.subtitle=String(i.subtitle)),i.cmsId!=null&&(e.cmsId=String(i.cmsId)),i.imageUrl!=null&&(e.imageUrl=String(i.imageUrl)),e},r.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(a.title="",a.subtitle="",a.cmsId="",a.imageUrl=""),i.title!=null&&i.hasOwnProperty("title")&&(a.title=i.title),i.subtitle!=null&&i.hasOwnProperty("subtitle")&&(a.subtitle=i.subtitle),i.cmsId!=null&&i.hasOwnProperty("cmsId")&&(a.cmsId=i.cmsId),i.imageUrl!=null&&i.hasOwnProperty("imageUrl")&&(a.imageUrl=i.imageUrl),a},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(i){return i===void 0&&(i="type.googleapis.com"),i+"/proto.Citation"},r})(),n.ClientPairingProps=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.isChatDbLidMigrated=e.bool();break}case 2:{s.isSyncdPureLidSession=e.bool();break}case 3:{s.isSyncdSnapshotRecoveryEnabled=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ClientPairingProps)return e;var a=new E.proto.ClientPairingProps;return e.isChatDbLidMigrated!=null&&(a.isChatDbLidMigrated=!!e.isChatDbLidMigrated),e.isSyncdPureLidSession!=null&&(a.isSyncdPureLidSession=!!e.isSyncdPureLidSession),e.isSyncdSnapshotRecoveryEnabled!=null&&(a.isSyncdSnapshotRecoveryEnabled=!!e.isSyncdSnapshotRecoveryEnabled),a},r.toObject=function(e,a){a||(a={});var A={};return e.isChatDbLidMigrated!=null&&e.hasOwnProperty("isChatDbLidMigrated")&&(A.isChatDbLidMigrated=e.isChatDbLidMigrated,a.oneofs&&(A._isChatDbLidMigrated="isChatDbLidMigrated")),e.isSyncdPureLidSession!=null&&e.hasOwnProperty("isSyncdPureLidSession")&&(A.isSyncdPureLidSession=e.isSyncdPureLidSession,a.oneofs&&(A._isSyncdPureLidSession="isSyncdPureLidSession")),e.isSyncdSnapshotRecoveryEnabled!=null&&e.hasOwnProperty("isSyncdSnapshotRecoveryEnabled")&&(A.isSyncdSnapshotRecoveryEnabled=e.isSyncdSnapshotRecoveryEnabled,a.oneofs&&(A._isSyncdSnapshotRecoveryEnabled="isSyncdSnapshotRecoveryEnabled")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ClientPairingProps"},r})(),n.ClientPayload=(function(){function r(i){if(this.shards=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.username=e.uint64();break}case 3:{s.passive=e.bool();break}case 5:{s.userAgent=E.proto.ClientPayload.UserAgent.decode(e,e.uint32());break}case 6:{s.webInfo=E.proto.ClientPayload.WebInfo.decode(e,e.uint32());break}case 7:{s.pushName=e.string();break}case 9:{s.sessionId=e.sfixed32();break}case 10:{s.shortConnect=e.bool();break}case 12:{s.connectType=e.int32();break}case 13:{s.connectReason=e.int32();break}case 14:{if(s.shards&&s.shards.length||(s.shards=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos>>0,e.username.high>>>0).toNumber(!0))),e.passive!=null&&(a.passive=!!e.passive),e.userAgent!=null){if(typeof e.userAgent!="object")throw TypeError(".proto.ClientPayload.userAgent: object expected");a.userAgent=E.proto.ClientPayload.UserAgent.fromObject(e.userAgent)}if(e.webInfo!=null){if(typeof e.webInfo!="object")throw TypeError(".proto.ClientPayload.webInfo: object expected");a.webInfo=E.proto.ClientPayload.WebInfo.fromObject(e.webInfo)}switch(e.pushName!=null&&(a.pushName=String(e.pushName)),e.sessionId!=null&&(a.sessionId=e.sessionId|0),e.shortConnect!=null&&(a.shortConnect=!!e.shortConnect),e.connectType){default:if(typeof e.connectType=="number"){a.connectType=e.connectType;break}break;case"CELLULAR_UNKNOWN":case 0:a.connectType=0;break;case"WIFI_UNKNOWN":case 1:a.connectType=1;break;case"CELLULAR_EDGE":case 100:a.connectType=100;break;case"CELLULAR_IDEN":case 101:a.connectType=101;break;case"CELLULAR_UMTS":case 102:a.connectType=102;break;case"CELLULAR_EVDO":case 103:a.connectType=103;break;case"CELLULAR_GPRS":case 104:a.connectType=104;break;case"CELLULAR_HSDPA":case 105:a.connectType=105;break;case"CELLULAR_HSUPA":case 106:a.connectType=106;break;case"CELLULAR_HSPA":case 107:a.connectType=107;break;case"CELLULAR_CDMA":case 108:a.connectType=108;break;case"CELLULAR_1XRTT":case 109:a.connectType=109;break;case"CELLULAR_EHRPD":case 110:a.connectType=110;break;case"CELLULAR_LTE":case 111:a.connectType=111;break;case"CELLULAR_HSPAP":case 112:a.connectType=112;break}switch(e.connectReason){default:if(typeof e.connectReason=="number"){a.connectReason=e.connectReason;break}break;case"PUSH":case 0:a.connectReason=0;break;case"USER_ACTIVATED":case 1:a.connectReason=1;break;case"SCHEDULED":case 2:a.connectReason=2;break;case"ERROR_RECONNECT":case 3:a.connectReason=3;break;case"NETWORK_SWITCH":case 4:a.connectReason=4;break;case"PING_RECONNECT":case 5:a.connectReason=5;break;case"UNKNOWN":case 6:a.connectReason=6;break}if(e.shards){if(!Array.isArray(e.shards))throw TypeError(".proto.ClientPayload.shards: array expected");a.shards=[];for(var A=0;A>>0),e.device!=null&&(a.device=e.device>>>0),e.devicePairingData!=null){if(typeof e.devicePairingData!="object")throw TypeError(".proto.ClientPayload.devicePairingData: object expected");a.devicePairingData=E.proto.ClientPayload.DevicePairingRegistrationData.fromObject(e.devicePairingData)}switch(e.product){default:if(typeof e.product=="number"){a.product=e.product;break}break;case"WHATSAPP":case 0:a.product=0;break;case"MESSENGER":case 1:a.product=1;break;case"INTEROP":case 2:a.product=2;break;case"INTEROP_MSGR":case 3:a.product=3;break;case"WHATSAPP_LID":case 4:a.product=4;break}switch(e.fbCat!=null&&(typeof e.fbCat=="string"?I.base64.decode(e.fbCat,a.fbCat=I.newBuffer(I.base64.length(e.fbCat)),0):e.fbCat.length>=0&&(a.fbCat=e.fbCat)),e.fbUserAgent!=null&&(typeof e.fbUserAgent=="string"?I.base64.decode(e.fbUserAgent,a.fbUserAgent=I.newBuffer(I.base64.length(e.fbUserAgent)),0):e.fbUserAgent.length>=0&&(a.fbUserAgent=e.fbUserAgent)),e.oc!=null&&(a.oc=!!e.oc),e.lc!=null&&(a.lc=e.lc|0),e.iosAppExtension){default:if(typeof e.iosAppExtension=="number"){a.iosAppExtension=e.iosAppExtension;break}break;case"SHARE_EXTENSION":case 0:a.iosAppExtension=0;break;case"SERVICE_EXTENSION":case 1:a.iosAppExtension=1;break;case"INTENTS_EXTENSION":case 2:a.iosAppExtension=2;break}if(e.fbAppId!=null&&(I.Long?(a.fbAppId=I.Long.fromValue(e.fbAppId)).unsigned=!0:typeof e.fbAppId=="string"?a.fbAppId=parseInt(e.fbAppId,10):typeof e.fbAppId=="number"?a.fbAppId=e.fbAppId:typeof e.fbAppId=="object"&&(a.fbAppId=new I.LongBits(e.fbAppId.low>>>0,e.fbAppId.high>>>0).toNumber(!0))),e.fbDeviceId!=null&&(typeof e.fbDeviceId=="string"?I.base64.decode(e.fbDeviceId,a.fbDeviceId=I.newBuffer(I.base64.length(e.fbDeviceId)),0):e.fbDeviceId.length>=0&&(a.fbDeviceId=e.fbDeviceId)),e.pull!=null&&(a.pull=!!e.pull),e.paddingBytes!=null&&(typeof e.paddingBytes=="string"?I.base64.decode(e.paddingBytes,a.paddingBytes=I.newBuffer(I.base64.length(e.paddingBytes)),0):e.paddingBytes.length>=0&&(a.paddingBytes=e.paddingBytes)),e.yearClass!=null&&(a.yearClass=e.yearClass|0),e.memClass!=null&&(a.memClass=e.memClass|0),e.interopData!=null){if(typeof e.interopData!="object")throw TypeError(".proto.ClientPayload.interopData: object expected");a.interopData=E.proto.ClientPayload.InteropData.fromObject(e.interopData)}switch(e.trafficAnonymization){default:if(typeof e.trafficAnonymization=="number"){a.trafficAnonymization=e.trafficAnonymization;break}break;case"OFF":case 0:a.trafficAnonymization=0;break;case"STANDARD":case 1:a.trafficAnonymization=1;break}switch(e.lidDbMigrated!=null&&(a.lidDbMigrated=!!e.lidDbMigrated),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"DEFAULT":case 0:a.accountType=0;break;case"GUEST":case 1:a.accountType=1;break}return e.connectionSequenceInfo!=null&&(a.connectionSequenceInfo=e.connectionSequenceInfo|0),e.paaLink!=null&&(a.paaLink=!!e.paaLink),e.preacksCount!=null&&(a.preacksCount=e.preacksCount|0),e.processingQueueSize!=null&&(a.processingQueueSize=e.processingQueueSize|0),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.shards=[]),e.username!=null&&e.hasOwnProperty("username")&&(typeof e.username=="number"?A.username=a.longs===String?String(e.username):e.username:A.username=a.longs===String?re(e.username,!0):a.longs===Number?ae(e.username,!0):e.username,a.oneofs&&(A._username="username")),e.passive!=null&&e.hasOwnProperty("passive")&&(A.passive=e.passive,a.oneofs&&(A._passive="passive")),e.userAgent!=null&&e.hasOwnProperty("userAgent")&&(A.userAgent=E.proto.ClientPayload.UserAgent.toObject(e.userAgent,a),a.oneofs&&(A._userAgent="userAgent")),e.webInfo!=null&&e.hasOwnProperty("webInfo")&&(A.webInfo=E.proto.ClientPayload.WebInfo.toObject(e.webInfo,a),a.oneofs&&(A._webInfo="webInfo")),e.pushName!=null&&e.hasOwnProperty("pushName")&&(A.pushName=e.pushName,a.oneofs&&(A._pushName="pushName")),e.sessionId!=null&&e.hasOwnProperty("sessionId")&&(A.sessionId=e.sessionId,a.oneofs&&(A._sessionId="sessionId")),e.shortConnect!=null&&e.hasOwnProperty("shortConnect")&&(A.shortConnect=e.shortConnect,a.oneofs&&(A._shortConnect="shortConnect")),e.connectType!=null&&e.hasOwnProperty("connectType")&&(A.connectType=a.enums===String?E.proto.ClientPayload.ConnectType[e.connectType]===void 0?e.connectType:E.proto.ClientPayload.ConnectType[e.connectType]:e.connectType,a.oneofs&&(A._connectType="connectType")),e.connectReason!=null&&e.hasOwnProperty("connectReason")&&(A.connectReason=a.enums===String?E.proto.ClientPayload.ConnectReason[e.connectReason]===void 0?e.connectReason:E.proto.ClientPayload.ConnectReason[e.connectReason]:e.connectReason,a.oneofs&&(A._connectReason="connectReason")),e.shards&&e.shards.length){A.shards=[];for(var t=0;t>>3){case 15:{c.dnsMethod=A.int32();break}case 16:{c.appCached=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ClientPayload.DNSSource)return A;var t=new E.proto.ClientPayload.DNSSource;switch(A.dnsMethod){default:if(typeof A.dnsMethod=="number"){t.dnsMethod=A.dnsMethod;break}break;case"SYSTEM":case 0:t.dnsMethod=0;break;case"GOOGLE":case 1:t.dnsMethod=1;break;case"HARDCODED":case 2:t.dnsMethod=2;break;case"OVERRIDE":case 3:t.dnsMethod=3;break;case"FALLBACK":case 4:t.dnsMethod=4;break;case"MNS":case 5:t.dnsMethod=5;break}return A.appCached!=null&&(t.appCached=!!A.appCached),t},i.toObject=function(A,t){t||(t={});var s={};return A.dnsMethod!=null&&A.hasOwnProperty("dnsMethod")&&(s.dnsMethod=t.enums===String?E.proto.ClientPayload.DNSSource.DNSResolutionMethod[A.dnsMethod]===void 0?A.dnsMethod:E.proto.ClientPayload.DNSSource.DNSResolutionMethod[A.dnsMethod]:A.dnsMethod,t.oneofs&&(s._dnsMethod="dnsMethod")),A.appCached!=null&&A.hasOwnProperty("appCached")&&(s.appCached=A.appCached,t.oneofs&&(s._appCached="appCached")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.DNSSource"},i.DNSResolutionMethod=(function(){let a={},A=Object.create(a);return A[a[0]="SYSTEM"]=0,A[a[1]="GOOGLE"]=1,A[a[2]="HARDCODED"]=2,A[a[3]="OVERRIDE"]=3,A[a[4]="FALLBACK"]=4,A[a[5]="MNS"]=5,A})(),i})(),r.DevicePairingRegistrationData=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.eRegid=A.bytes();break}case 2:{c.eKeytype=A.bytes();break}case 3:{c.eIdent=A.bytes();break}case 4:{c.eSkeyId=A.bytes();break}case 5:{c.eSkeyVal=A.bytes();break}case 6:{c.eSkeySig=A.bytes();break}case 7:{c.buildHash=A.bytes();break}case 8:{c.deviceProps=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ClientPayload.DevicePairingRegistrationData)return A;var t=new E.proto.ClientPayload.DevicePairingRegistrationData;return A.eRegid!=null&&(typeof A.eRegid=="string"?I.base64.decode(A.eRegid,t.eRegid=I.newBuffer(I.base64.length(A.eRegid)),0):A.eRegid.length>=0&&(t.eRegid=A.eRegid)),A.eKeytype!=null&&(typeof A.eKeytype=="string"?I.base64.decode(A.eKeytype,t.eKeytype=I.newBuffer(I.base64.length(A.eKeytype)),0):A.eKeytype.length>=0&&(t.eKeytype=A.eKeytype)),A.eIdent!=null&&(typeof A.eIdent=="string"?I.base64.decode(A.eIdent,t.eIdent=I.newBuffer(I.base64.length(A.eIdent)),0):A.eIdent.length>=0&&(t.eIdent=A.eIdent)),A.eSkeyId!=null&&(typeof A.eSkeyId=="string"?I.base64.decode(A.eSkeyId,t.eSkeyId=I.newBuffer(I.base64.length(A.eSkeyId)),0):A.eSkeyId.length>=0&&(t.eSkeyId=A.eSkeyId)),A.eSkeyVal!=null&&(typeof A.eSkeyVal=="string"?I.base64.decode(A.eSkeyVal,t.eSkeyVal=I.newBuffer(I.base64.length(A.eSkeyVal)),0):A.eSkeyVal.length>=0&&(t.eSkeyVal=A.eSkeyVal)),A.eSkeySig!=null&&(typeof A.eSkeySig=="string"?I.base64.decode(A.eSkeySig,t.eSkeySig=I.newBuffer(I.base64.length(A.eSkeySig)),0):A.eSkeySig.length>=0&&(t.eSkeySig=A.eSkeySig)),A.buildHash!=null&&(typeof A.buildHash=="string"?I.base64.decode(A.buildHash,t.buildHash=I.newBuffer(I.base64.length(A.buildHash)),0):A.buildHash.length>=0&&(t.buildHash=A.buildHash)),A.deviceProps!=null&&(typeof A.deviceProps=="string"?I.base64.decode(A.deviceProps,t.deviceProps=I.newBuffer(I.base64.length(A.deviceProps)),0):A.deviceProps.length>=0&&(t.deviceProps=A.deviceProps)),t},i.toObject=function(A,t){t||(t={});var s={};return A.eRegid!=null&&A.hasOwnProperty("eRegid")&&(s.eRegid=t.bytes===String?I.base64.encode(A.eRegid,0,A.eRegid.length):t.bytes===Array?Array.prototype.slice.call(A.eRegid):A.eRegid,t.oneofs&&(s._eRegid="eRegid")),A.eKeytype!=null&&A.hasOwnProperty("eKeytype")&&(s.eKeytype=t.bytes===String?I.base64.encode(A.eKeytype,0,A.eKeytype.length):t.bytes===Array?Array.prototype.slice.call(A.eKeytype):A.eKeytype,t.oneofs&&(s._eKeytype="eKeytype")),A.eIdent!=null&&A.hasOwnProperty("eIdent")&&(s.eIdent=t.bytes===String?I.base64.encode(A.eIdent,0,A.eIdent.length):t.bytes===Array?Array.prototype.slice.call(A.eIdent):A.eIdent,t.oneofs&&(s._eIdent="eIdent")),A.eSkeyId!=null&&A.hasOwnProperty("eSkeyId")&&(s.eSkeyId=t.bytes===String?I.base64.encode(A.eSkeyId,0,A.eSkeyId.length):t.bytes===Array?Array.prototype.slice.call(A.eSkeyId):A.eSkeyId,t.oneofs&&(s._eSkeyId="eSkeyId")),A.eSkeyVal!=null&&A.hasOwnProperty("eSkeyVal")&&(s.eSkeyVal=t.bytes===String?I.base64.encode(A.eSkeyVal,0,A.eSkeyVal.length):t.bytes===Array?Array.prototype.slice.call(A.eSkeyVal):A.eSkeyVal,t.oneofs&&(s._eSkeyVal="eSkeyVal")),A.eSkeySig!=null&&A.hasOwnProperty("eSkeySig")&&(s.eSkeySig=t.bytes===String?I.base64.encode(A.eSkeySig,0,A.eSkeySig.length):t.bytes===Array?Array.prototype.slice.call(A.eSkeySig):A.eSkeySig,t.oneofs&&(s._eSkeySig="eSkeySig")),A.buildHash!=null&&A.hasOwnProperty("buildHash")&&(s.buildHash=t.bytes===String?I.base64.encode(A.buildHash,0,A.buildHash.length):t.bytes===Array?Array.prototype.slice.call(A.buildHash):A.buildHash,t.oneofs&&(s._buildHash="buildHash")),A.deviceProps!=null&&A.hasOwnProperty("deviceProps")&&(s.deviceProps=t.bytes===String?I.base64.encode(A.deviceProps,0,A.deviceProps.length):t.bytes===Array?Array.prototype.slice.call(A.deviceProps):A.deviceProps,t.oneofs&&(s._deviceProps="deviceProps")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.DevicePairingRegistrationData"},i})(),r.IOSAppExtension=(function(){let i={},e=Object.create(i);return e[i[0]="SHARE_EXTENSION"]=0,e[i[1]="SERVICE_EXTENSION"]=1,e[i[2]="INTENTS_EXTENSION"]=2,e})(),r.InteropData=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.accountId=A.uint64();break}case 2:{c.token=A.bytes();break}case 3:{c.enableReadReceipts=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ClientPayload.InteropData)return A;var t=new E.proto.ClientPayload.InteropData;return A.accountId!=null&&(I.Long?(t.accountId=I.Long.fromValue(A.accountId)).unsigned=!0:typeof A.accountId=="string"?t.accountId=parseInt(A.accountId,10):typeof A.accountId=="number"?t.accountId=A.accountId:typeof A.accountId=="object"&&(t.accountId=new I.LongBits(A.accountId.low>>>0,A.accountId.high>>>0).toNumber(!0))),A.token!=null&&(typeof A.token=="string"?I.base64.decode(A.token,t.token=I.newBuffer(I.base64.length(A.token)),0):A.token.length>=0&&(t.token=A.token)),A.enableReadReceipts!=null&&(t.enableReadReceipts=!!A.enableReadReceipts),t},i.toObject=function(A,t){t||(t={});var s={};return A.accountId!=null&&A.hasOwnProperty("accountId")&&(typeof A.accountId=="number"?s.accountId=t.longs===String?String(A.accountId):A.accountId:s.accountId=t.longs===String?re(A.accountId,!0):t.longs===Number?ae(A.accountId,!0):A.accountId,t.oneofs&&(s._accountId="accountId")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=t.bytes===String?I.base64.encode(A.token,0,A.token.length):t.bytes===Array?Array.prototype.slice.call(A.token):A.token,t.oneofs&&(s._token="token")),A.enableReadReceipts!=null&&A.hasOwnProperty("enableReadReceipts")&&(s.enableReadReceipts=A.enableReadReceipts,t.oneofs&&(s._enableReadReceipts="enableReadReceipts")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.InteropData"},i})(),r.Product=(function(){let i={},e=Object.create(i);return e[i[0]="WHATSAPP"]=0,e[i[1]="MESSENGER"]=1,e[i[2]="INTEROP"]=2,e[i[3]="INTEROP_MSGR"]=3,e[i[4]="WHATSAPP_LID"]=4,e})(),r.TrafficAnonymization=(function(){let i={},e=Object.create(i);return e[i[0]="OFF"]=0,e[i[1]="STANDARD"]=1,e})(),r.UserAgent=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.platform=A.int32();break}case 2:{c.appVersion=E.proto.ClientPayload.UserAgent.AppVersion.decode(A,A.uint32());break}case 3:{c.mcc=A.string();break}case 4:{c.mnc=A.string();break}case 5:{c.osVersion=A.string();break}case 6:{c.manufacturer=A.string();break}case 7:{c.device=A.string();break}case 8:{c.osBuildNumber=A.string();break}case 9:{c.phoneId=A.string();break}case 10:{c.releaseChannel=A.int32();break}case 11:{c.localeLanguageIso6391=A.string();break}case 12:{c.localeCountryIso31661Alpha2=A.string();break}case 13:{c.deviceBoard=A.string();break}case 14:{c.deviceExpId=A.string();break}case 15:{c.deviceType=A.int32();break}case 16:{c.deviceModelType=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ClientPayload.UserAgent)return A;var t=new E.proto.ClientPayload.UserAgent;switch(A.platform){default:if(typeof A.platform=="number"){t.platform=A.platform;break}break;case"ANDROID":case 0:t.platform=0;break;case"IOS":case 1:t.platform=1;break;case"WINDOWS_PHONE":case 2:t.platform=2;break;case"BLACKBERRY":case 3:t.platform=3;break;case"BLACKBERRYX":case 4:t.platform=4;break;case"S40":case 5:t.platform=5;break;case"S60":case 6:t.platform=6;break;case"PYTHON_CLIENT":case 7:t.platform=7;break;case"TIZEN":case 8:t.platform=8;break;case"ENTERPRISE":case 9:t.platform=9;break;case"SMB_ANDROID":case 10:t.platform=10;break;case"KAIOS":case 11:t.platform=11;break;case"SMB_IOS":case 12:t.platform=12;break;case"WINDOWS":case 13:t.platform=13;break;case"WEB":case 14:t.platform=14;break;case"PORTAL":case 15:t.platform=15;break;case"GREEN_ANDROID":case 16:t.platform=16;break;case"GREEN_IPHONE":case 17:t.platform=17;break;case"BLUE_ANDROID":case 18:t.platform=18;break;case"BLUE_IPHONE":case 19:t.platform=19;break;case"FBLITE_ANDROID":case 20:t.platform=20;break;case"MLITE_ANDROID":case 21:t.platform=21;break;case"IGLITE_ANDROID":case 22:t.platform=22;break;case"PAGE":case 23:t.platform=23;break;case"MACOS":case 24:t.platform=24;break;case"OCULUS_MSG":case 25:t.platform=25;break;case"OCULUS_CALL":case 26:t.platform=26;break;case"MILAN":case 27:t.platform=27;break;case"CAPI":case 28:t.platform=28;break;case"WEAROS":case 29:t.platform=29;break;case"ARDEVICE":case 30:t.platform=30;break;case"VRDEVICE":case 31:t.platform=31;break;case"BLUE_WEB":case 32:t.platform=32;break;case"IPAD":case 33:t.platform=33;break;case"TEST":case 34:t.platform=34;break;case"SMART_GLASSES":case 35:t.platform=35;break;case"BLUE_VR":case 36:t.platform=36;break;case"AR_WRIST":case 37:t.platform=37;break}if(A.appVersion!=null){if(typeof A.appVersion!="object")throw TypeError(".proto.ClientPayload.UserAgent.appVersion: object expected");t.appVersion=E.proto.ClientPayload.UserAgent.AppVersion.fromObject(A.appVersion)}switch(A.mcc!=null&&(t.mcc=String(A.mcc)),A.mnc!=null&&(t.mnc=String(A.mnc)),A.osVersion!=null&&(t.osVersion=String(A.osVersion)),A.manufacturer!=null&&(t.manufacturer=String(A.manufacturer)),A.device!=null&&(t.device=String(A.device)),A.osBuildNumber!=null&&(t.osBuildNumber=String(A.osBuildNumber)),A.phoneId!=null&&(t.phoneId=String(A.phoneId)),A.releaseChannel){default:if(typeof A.releaseChannel=="number"){t.releaseChannel=A.releaseChannel;break}break;case"RELEASE":case 0:t.releaseChannel=0;break;case"BETA":case 1:t.releaseChannel=1;break;case"ALPHA":case 2:t.releaseChannel=2;break;case"DEBUG":case 3:t.releaseChannel=3;break}switch(A.localeLanguageIso6391!=null&&(t.localeLanguageIso6391=String(A.localeLanguageIso6391)),A.localeCountryIso31661Alpha2!=null&&(t.localeCountryIso31661Alpha2=String(A.localeCountryIso31661Alpha2)),A.deviceBoard!=null&&(t.deviceBoard=String(A.deviceBoard)),A.deviceExpId!=null&&(t.deviceExpId=String(A.deviceExpId)),A.deviceType){default:if(typeof A.deviceType=="number"){t.deviceType=A.deviceType;break}break;case"PHONE":case 0:t.deviceType=0;break;case"TABLET":case 1:t.deviceType=1;break;case"DESKTOP":case 2:t.deviceType=2;break;case"WEARABLE":case 3:t.deviceType=3;break;case"VR":case 4:t.deviceType=4;break}return A.deviceModelType!=null&&(t.deviceModelType=String(A.deviceModelType)),t},i.toObject=function(A,t){t||(t={});var s={};return A.platform!=null&&A.hasOwnProperty("platform")&&(s.platform=t.enums===String?E.proto.ClientPayload.UserAgent.Platform[A.platform]===void 0?A.platform:E.proto.ClientPayload.UserAgent.Platform[A.platform]:A.platform,t.oneofs&&(s._platform="platform")),A.appVersion!=null&&A.hasOwnProperty("appVersion")&&(s.appVersion=E.proto.ClientPayload.UserAgent.AppVersion.toObject(A.appVersion,t),t.oneofs&&(s._appVersion="appVersion")),A.mcc!=null&&A.hasOwnProperty("mcc")&&(s.mcc=A.mcc,t.oneofs&&(s._mcc="mcc")),A.mnc!=null&&A.hasOwnProperty("mnc")&&(s.mnc=A.mnc,t.oneofs&&(s._mnc="mnc")),A.osVersion!=null&&A.hasOwnProperty("osVersion")&&(s.osVersion=A.osVersion,t.oneofs&&(s._osVersion="osVersion")),A.manufacturer!=null&&A.hasOwnProperty("manufacturer")&&(s.manufacturer=A.manufacturer,t.oneofs&&(s._manufacturer="manufacturer")),A.device!=null&&A.hasOwnProperty("device")&&(s.device=A.device,t.oneofs&&(s._device="device")),A.osBuildNumber!=null&&A.hasOwnProperty("osBuildNumber")&&(s.osBuildNumber=A.osBuildNumber,t.oneofs&&(s._osBuildNumber="osBuildNumber")),A.phoneId!=null&&A.hasOwnProperty("phoneId")&&(s.phoneId=A.phoneId,t.oneofs&&(s._phoneId="phoneId")),A.releaseChannel!=null&&A.hasOwnProperty("releaseChannel")&&(s.releaseChannel=t.enums===String?E.proto.ClientPayload.UserAgent.ReleaseChannel[A.releaseChannel]===void 0?A.releaseChannel:E.proto.ClientPayload.UserAgent.ReleaseChannel[A.releaseChannel]:A.releaseChannel,t.oneofs&&(s._releaseChannel="releaseChannel")),A.localeLanguageIso6391!=null&&A.hasOwnProperty("localeLanguageIso6391")&&(s.localeLanguageIso6391=A.localeLanguageIso6391,t.oneofs&&(s._localeLanguageIso6391="localeLanguageIso6391")),A.localeCountryIso31661Alpha2!=null&&A.hasOwnProperty("localeCountryIso31661Alpha2")&&(s.localeCountryIso31661Alpha2=A.localeCountryIso31661Alpha2,t.oneofs&&(s._localeCountryIso31661Alpha2="localeCountryIso31661Alpha2")),A.deviceBoard!=null&&A.hasOwnProperty("deviceBoard")&&(s.deviceBoard=A.deviceBoard,t.oneofs&&(s._deviceBoard="deviceBoard")),A.deviceExpId!=null&&A.hasOwnProperty("deviceExpId")&&(s.deviceExpId=A.deviceExpId,t.oneofs&&(s._deviceExpId="deviceExpId")),A.deviceType!=null&&A.hasOwnProperty("deviceType")&&(s.deviceType=t.enums===String?E.proto.ClientPayload.UserAgent.DeviceType[A.deviceType]===void 0?A.deviceType:E.proto.ClientPayload.UserAgent.DeviceType[A.deviceType]:A.deviceType,t.oneofs&&(s._deviceType="deviceType")),A.deviceModelType!=null&&A.hasOwnProperty("deviceModelType")&&(s.deviceModelType=A.deviceModelType,t.oneofs&&(s._deviceModelType="deviceModelType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.UserAgent"},i.AppVersion=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.primary=s.uint32();break}case 2:{p.secondary=s.uint32();break}case 3:{p.tertiary=s.uint32();break}case 4:{p.quaternary=s.uint32();break}case 5:{p.quinary=s.uint32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.ClientPayload.UserAgent.AppVersion)return s;var g=new E.proto.ClientPayload.UserAgent.AppVersion;return s.primary!=null&&(g.primary=s.primary>>>0),s.secondary!=null&&(g.secondary=s.secondary>>>0),s.tertiary!=null&&(g.tertiary=s.tertiary>>>0),s.quaternary!=null&&(g.quaternary=s.quaternary>>>0),s.quinary!=null&&(g.quinary=s.quinary>>>0),g},a.toObject=function(s,g){g||(g={});var c={};return s.primary!=null&&s.hasOwnProperty("primary")&&(c.primary=s.primary,g.oneofs&&(c._primary="primary")),s.secondary!=null&&s.hasOwnProperty("secondary")&&(c.secondary=s.secondary,g.oneofs&&(c._secondary="secondary")),s.tertiary!=null&&s.hasOwnProperty("tertiary")&&(c.tertiary=s.tertiary,g.oneofs&&(c._tertiary="tertiary")),s.quaternary!=null&&s.hasOwnProperty("quaternary")&&(c.quaternary=s.quaternary,g.oneofs&&(c._quaternary="quaternary")),s.quinary!=null&&s.hasOwnProperty("quinary")&&(c.quinary=s.quinary,g.oneofs&&(c._quinary="quinary")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ClientPayload.UserAgent.AppVersion"},a})(),i.DeviceType=(function(){let a={},A=Object.create(a);return A[a[0]="PHONE"]=0,A[a[1]="TABLET"]=1,A[a[2]="DESKTOP"]=2,A[a[3]="WEARABLE"]=3,A[a[4]="VR"]=4,A})(),i.Platform=(function(){let a={},A=Object.create(a);return A[a[0]="ANDROID"]=0,A[a[1]="IOS"]=1,A[a[2]="WINDOWS_PHONE"]=2,A[a[3]="BLACKBERRY"]=3,A[a[4]="BLACKBERRYX"]=4,A[a[5]="S40"]=5,A[a[6]="S60"]=6,A[a[7]="PYTHON_CLIENT"]=7,A[a[8]="TIZEN"]=8,A[a[9]="ENTERPRISE"]=9,A[a[10]="SMB_ANDROID"]=10,A[a[11]="KAIOS"]=11,A[a[12]="SMB_IOS"]=12,A[a[13]="WINDOWS"]=13,A[a[14]="WEB"]=14,A[a[15]="PORTAL"]=15,A[a[16]="GREEN_ANDROID"]=16,A[a[17]="GREEN_IPHONE"]=17,A[a[18]="BLUE_ANDROID"]=18,A[a[19]="BLUE_IPHONE"]=19,A[a[20]="FBLITE_ANDROID"]=20,A[a[21]="MLITE_ANDROID"]=21,A[a[22]="IGLITE_ANDROID"]=22,A[a[23]="PAGE"]=23,A[a[24]="MACOS"]=24,A[a[25]="OCULUS_MSG"]=25,A[a[26]="OCULUS_CALL"]=26,A[a[27]="MILAN"]=27,A[a[28]="CAPI"]=28,A[a[29]="WEAROS"]=29,A[a[30]="ARDEVICE"]=30,A[a[31]="VRDEVICE"]=31,A[a[32]="BLUE_WEB"]=32,A[a[33]="IPAD"]=33,A[a[34]="TEST"]=34,A[a[35]="SMART_GLASSES"]=35,A[a[36]="BLUE_VR"]=36,A[a[37]="AR_WRIST"]=37,A})(),i.ReleaseChannel=(function(){let a={},A=Object.create(a);return A[a[0]="RELEASE"]=0,A[a[1]="BETA"]=1,A[a[2]="ALPHA"]=2,A[a[3]="DEBUG"]=3,A})(),i})(),r.WebInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.refToken=A.string();break}case 2:{c.version=A.string();break}case 3:{c.webdPayload=E.proto.ClientPayload.WebInfo.WebdPayload.decode(A,A.uint32());break}case 4:{c.webSubPlatform=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ClientPayload.WebInfo)return A;var t=new E.proto.ClientPayload.WebInfo;if(A.refToken!=null&&(t.refToken=String(A.refToken)),A.version!=null&&(t.version=String(A.version)),A.webdPayload!=null){if(typeof A.webdPayload!="object")throw TypeError(".proto.ClientPayload.WebInfo.webdPayload: object expected");t.webdPayload=E.proto.ClientPayload.WebInfo.WebdPayload.fromObject(A.webdPayload)}switch(A.webSubPlatform){default:if(typeof A.webSubPlatform=="number"){t.webSubPlatform=A.webSubPlatform;break}break;case"WEB_BROWSER":case 0:t.webSubPlatform=0;break;case"APP_STORE":case 1:t.webSubPlatform=1;break;case"WIN_STORE":case 2:t.webSubPlatform=2;break;case"DARWIN":case 3:t.webSubPlatform=3;break;case"WIN32":case 4:t.webSubPlatform=4;break;case"WIN_HYBRID":case 5:t.webSubPlatform=5;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.refToken!=null&&A.hasOwnProperty("refToken")&&(s.refToken=A.refToken,t.oneofs&&(s._refToken="refToken")),A.version!=null&&A.hasOwnProperty("version")&&(s.version=A.version,t.oneofs&&(s._version="version")),A.webdPayload!=null&&A.hasOwnProperty("webdPayload")&&(s.webdPayload=E.proto.ClientPayload.WebInfo.WebdPayload.toObject(A.webdPayload,t),t.oneofs&&(s._webdPayload="webdPayload")),A.webSubPlatform!=null&&A.hasOwnProperty("webSubPlatform")&&(s.webSubPlatform=t.enums===String?E.proto.ClientPayload.WebInfo.WebSubPlatform[A.webSubPlatform]===void 0?A.webSubPlatform:E.proto.ClientPayload.WebInfo.WebSubPlatform[A.webSubPlatform]:A.webSubPlatform,t.oneofs&&(s._webSubPlatform="webSubPlatform")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.WebInfo"},i.WebSubPlatform=(function(){let a={},A=Object.create(a);return A[a[0]="WEB_BROWSER"]=0,A[a[1]="APP_STORE"]=1,A[a[2]="WIN_STORE"]=2,A[a[3]="DARWIN"]=3,A[a[4]="WIN32"]=4,A[a[5]="WIN_HYBRID"]=5,A})(),i.WebdPayload=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.usesParticipantInKey=s.bool();break}case 2:{p.supportsStarredMessages=s.bool();break}case 3:{p.supportsDocumentMessages=s.bool();break}case 4:{p.supportsUrlMessages=s.bool();break}case 5:{p.supportsMediaRetry=s.bool();break}case 6:{p.supportsE2EImage=s.bool();break}case 7:{p.supportsE2EVideo=s.bool();break}case 8:{p.supportsE2EAudio=s.bool();break}case 9:{p.supportsE2EDocument=s.bool();break}case 10:{p.documentTypes=s.string();break}case 11:{p.features=s.bytes();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.ClientPayload.WebInfo.WebdPayload)return s;var g=new E.proto.ClientPayload.WebInfo.WebdPayload;return s.usesParticipantInKey!=null&&(g.usesParticipantInKey=!!s.usesParticipantInKey),s.supportsStarredMessages!=null&&(g.supportsStarredMessages=!!s.supportsStarredMessages),s.supportsDocumentMessages!=null&&(g.supportsDocumentMessages=!!s.supportsDocumentMessages),s.supportsUrlMessages!=null&&(g.supportsUrlMessages=!!s.supportsUrlMessages),s.supportsMediaRetry!=null&&(g.supportsMediaRetry=!!s.supportsMediaRetry),s.supportsE2EImage!=null&&(g.supportsE2EImage=!!s.supportsE2EImage),s.supportsE2EVideo!=null&&(g.supportsE2EVideo=!!s.supportsE2EVideo),s.supportsE2EAudio!=null&&(g.supportsE2EAudio=!!s.supportsE2EAudio),s.supportsE2EDocument!=null&&(g.supportsE2EDocument=!!s.supportsE2EDocument),s.documentTypes!=null&&(g.documentTypes=String(s.documentTypes)),s.features!=null&&(typeof s.features=="string"?I.base64.decode(s.features,g.features=I.newBuffer(I.base64.length(s.features)),0):s.features.length>=0&&(g.features=s.features)),g},a.toObject=function(s,g){g||(g={});var c={};return s.usesParticipantInKey!=null&&s.hasOwnProperty("usesParticipantInKey")&&(c.usesParticipantInKey=s.usesParticipantInKey,g.oneofs&&(c._usesParticipantInKey="usesParticipantInKey")),s.supportsStarredMessages!=null&&s.hasOwnProperty("supportsStarredMessages")&&(c.supportsStarredMessages=s.supportsStarredMessages,g.oneofs&&(c._supportsStarredMessages="supportsStarredMessages")),s.supportsDocumentMessages!=null&&s.hasOwnProperty("supportsDocumentMessages")&&(c.supportsDocumentMessages=s.supportsDocumentMessages,g.oneofs&&(c._supportsDocumentMessages="supportsDocumentMessages")),s.supportsUrlMessages!=null&&s.hasOwnProperty("supportsUrlMessages")&&(c.supportsUrlMessages=s.supportsUrlMessages,g.oneofs&&(c._supportsUrlMessages="supportsUrlMessages")),s.supportsMediaRetry!=null&&s.hasOwnProperty("supportsMediaRetry")&&(c.supportsMediaRetry=s.supportsMediaRetry,g.oneofs&&(c._supportsMediaRetry="supportsMediaRetry")),s.supportsE2EImage!=null&&s.hasOwnProperty("supportsE2EImage")&&(c.supportsE2EImage=s.supportsE2EImage,g.oneofs&&(c._supportsE2EImage="supportsE2EImage")),s.supportsE2EVideo!=null&&s.hasOwnProperty("supportsE2EVideo")&&(c.supportsE2EVideo=s.supportsE2EVideo,g.oneofs&&(c._supportsE2EVideo="supportsE2EVideo")),s.supportsE2EAudio!=null&&s.hasOwnProperty("supportsE2EAudio")&&(c.supportsE2EAudio=s.supportsE2EAudio,g.oneofs&&(c._supportsE2EAudio="supportsE2EAudio")),s.supportsE2EDocument!=null&&s.hasOwnProperty("supportsE2EDocument")&&(c.supportsE2EDocument=s.supportsE2EDocument,g.oneofs&&(c._supportsE2EDocument="supportsE2EDocument")),s.documentTypes!=null&&s.hasOwnProperty("documentTypes")&&(c.documentTypes=s.documentTypes,g.oneofs&&(c._documentTypes="documentTypes")),s.features!=null&&s.hasOwnProperty("features")&&(c.features=g.bytes===String?I.base64.encode(s.features,0,s.features.length):g.bytes===Array?Array.prototype.slice.call(s.features):s.features,g.oneofs&&(c._features="features")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ClientPayload.WebInfo.WebdPayload"},a})(),i})(),r})(),n.CollectionName=(function(){let r={},o=Object.create(r);return o[r[0]="COLLECTION_NAME_UNKNOWN"]=0,o[r[1]="REGULAR"]=1,o[r[2]="REGULAR_LOW"]=2,o[r[3]="REGULAR_HIGH"]=3,o[r[4]="CRITICAL_BLOCK"]=4,o[r[5]="CRITICAL_UNBLOCK_LOW"]=5,o})(),n.CommentMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.commentParentKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.replyCount=e.uint32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.CommentMetadata)return e;var a=new E.proto.CommentMetadata;if(e.commentParentKey!=null){if(typeof e.commentParentKey!="object")throw TypeError(".proto.CommentMetadata.commentParentKey: object expected");a.commentParentKey=E.proto.MessageKey.fromObject(e.commentParentKey)}return e.replyCount!=null&&(a.replyCount=e.replyCount>>>0),a},r.toObject=function(e,a){a||(a={});var A={};return e.commentParentKey!=null&&e.hasOwnProperty("commentParentKey")&&(A.commentParentKey=E.proto.MessageKey.toObject(e.commentParentKey,a),a.oneofs&&(A._commentParentKey="commentParentKey")),e.replyCount!=null&&e.hasOwnProperty("replyCount")&&(A.replyCount=e.replyCount,a.oneofs&&(A._replyCount="replyCount")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CommentMetadata"},r})(),n.CompanionCommitment=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.hash=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.CompanionCommitment)return e;var a=new E.proto.CompanionCommitment;return e.hash!=null&&(typeof e.hash=="string"?I.base64.decode(e.hash,a.hash=I.newBuffer(I.base64.length(e.hash)),0):e.hash.length>=0&&(a.hash=e.hash)),a},r.toObject=function(e,a){a||(a={});var A={};return e.hash!=null&&e.hasOwnProperty("hash")&&(A.hash=a.bytes===String?I.base64.encode(e.hash,0,e.hash.length):a.bytes===Array?Array.prototype.slice.call(e.hash):e.hash,a.oneofs&&(A._hash="hash")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CompanionCommitment"},r})(),n.CompanionEphemeralIdentity=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.deviceType=e.int32();break}case 3:{s.ref=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.CompanionEphemeralIdentity)return e;var a=new E.proto.CompanionEphemeralIdentity;switch(e.publicKey!=null&&(typeof e.publicKey=="string"?I.base64.decode(e.publicKey,a.publicKey=I.newBuffer(I.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.deviceType){default:if(typeof e.deviceType=="number"){a.deviceType=e.deviceType;break}break;case"UNKNOWN":case 0:a.deviceType=0;break;case"CHROME":case 1:a.deviceType=1;break;case"FIREFOX":case 2:a.deviceType=2;break;case"IE":case 3:a.deviceType=3;break;case"OPERA":case 4:a.deviceType=4;break;case"SAFARI":case 5:a.deviceType=5;break;case"EDGE":case 6:a.deviceType=6;break;case"DESKTOP":case 7:a.deviceType=7;break;case"IPAD":case 8:a.deviceType=8;break;case"ANDROID_TABLET":case 9:a.deviceType=9;break;case"OHANA":case 10:a.deviceType=10;break;case"ALOHA":case 11:a.deviceType=11;break;case"CATALINA":case 12:a.deviceType=12;break;case"TCL_TV":case 13:a.deviceType=13;break;case"IOS_PHONE":case 14:a.deviceType=14;break;case"IOS_CATALYST":case 15:a.deviceType=15;break;case"ANDROID_PHONE":case 16:a.deviceType=16;break;case"ANDROID_AMBIGUOUS":case 17:a.deviceType=17;break;case"WEAR_OS":case 18:a.deviceType=18;break;case"AR_WRIST":case 19:a.deviceType=19;break;case"AR_DEVICE":case 20:a.deviceType=20;break;case"UWP":case 21:a.deviceType=21;break;case"VR":case 22:a.deviceType=22;break;case"CLOUD_API":case 23:a.deviceType=23;break;case"SMARTGLASSES":case 24:a.deviceType=24;break}return e.ref!=null&&(a.ref=String(e.ref)),a},r.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?I.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.deviceType!=null&&e.hasOwnProperty("deviceType")&&(A.deviceType=a.enums===String?E.proto.DeviceProps.PlatformType[e.deviceType]===void 0?e.deviceType:E.proto.DeviceProps.PlatformType[e.deviceType]:e.deviceType,a.oneofs&&(A._deviceType="deviceType")),e.ref!=null&&e.hasOwnProperty("ref")&&(A.ref=e.ref,a.oneofs&&(A._ref="ref")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CompanionEphemeralIdentity"},r})(),n.Config=(function(){function r(i){if(this.field={},i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.field===I.emptyObject&&(s.field={});var p=e.uint32()+e.pos;for(g=0,c=null;e.pos>>3){case 1:g=e.uint32();break;case 2:c=E.proto.Field.decode(e,e.uint32());break;default:e.skipType(B&7);break}}s.field[g]=c;break}case 2:{s.version=e.uint32();break}default:e.skipType(l&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Config)return e;var a=new E.proto.Config;if(e.field){if(typeof e.field!="object")throw TypeError(".proto.Config.field: object expected");a.field={};for(var A=Object.keys(e.field),t=0;t>>0),a},r.toObject=function(e,a){a||(a={});var A={};(a.objects||a.defaults)&&(A.field={});var t;if(e.field&&(t=Object.keys(e.field)).length){A.field={};for(var s=0;s>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.participant=e.string();break}case 3:{s.quotedMessage=E.proto.Message.decode(e,e.uint32());break}case 4:{s.remoteJid=e.string();break}case 15:{s.mentionedJid&&s.mentionedJid.length||(s.mentionedJid=[]),s.mentionedJid.push(e.string());break}case 18:{s.conversionSource=e.string();break}case 19:{s.conversionData=e.bytes();break}case 20:{s.conversionDelaySeconds=e.uint32();break}case 21:{s.forwardingScore=e.uint32();break}case 22:{s.isForwarded=e.bool();break}case 23:{s.quotedAd=E.proto.ContextInfo.AdReplyInfo.decode(e,e.uint32());break}case 24:{s.placeholderKey=E.proto.MessageKey.decode(e,e.uint32());break}case 25:{s.expiration=e.uint32();break}case 26:{s.ephemeralSettingTimestamp=e.int64();break}case 27:{s.ephemeralSharedSecret=e.bytes();break}case 28:{s.externalAdReply=E.proto.ContextInfo.ExternalAdReplyInfo.decode(e,e.uint32());break}case 29:{s.entryPointConversionSource=e.string();break}case 30:{s.entryPointConversionApp=e.string();break}case 31:{s.entryPointConversionDelaySeconds=e.uint32();break}case 32:{s.disappearingMode=E.proto.DisappearingMode.decode(e,e.uint32());break}case 33:{s.actionLink=E.proto.ActionLink.decode(e,e.uint32());break}case 34:{s.groupSubject=e.string();break}case 35:{s.parentGroupJid=e.string();break}case 37:{s.trustBannerType=e.string();break}case 38:{s.trustBannerAction=e.uint32();break}case 39:{s.isSampled=e.bool();break}case 40:{s.groupMentions&&s.groupMentions.length||(s.groupMentions=[]),s.groupMentions.push(E.proto.GroupMention.decode(e,e.uint32()));break}case 41:{s.utm=E.proto.ContextInfo.UTMInfo.decode(e,e.uint32());break}case 43:{s.forwardedNewsletterMessageInfo=E.proto.ContextInfo.ForwardedNewsletterMessageInfo.decode(e,e.uint32());break}case 44:{s.businessMessageForwardInfo=E.proto.ContextInfo.BusinessMessageForwardInfo.decode(e,e.uint32());break}case 45:{s.smbClientCampaignId=e.string();break}case 46:{s.smbServerCampaignId=e.string();break}case 47:{s.dataSharingContext=E.proto.ContextInfo.DataSharingContext.decode(e,e.uint32());break}case 48:{s.alwaysShowAdAttribution=e.bool();break}case 49:{s.featureEligibilities=E.proto.ContextInfo.FeatureEligibilities.decode(e,e.uint32());break}case 50:{s.entryPointConversionExternalSource=e.string();break}case 51:{s.entryPointConversionExternalMedium=e.string();break}case 54:{s.ctwaSignals=e.string();break}case 55:{s.ctwaPayload=e.bytes();break}case 56:{s.forwardedAiBotMessageInfo=E.proto.ForwardedAIBotMessageInfo.decode(e,e.uint32());break}case 57:{s.statusAttributionType=e.int32();break}case 58:{s.urlTrackingMap=E.proto.UrlTrackingMap.decode(e,e.uint32());break}case 59:{s.pairedMediaType=e.int32();break}case 60:{s.rankingVersion=e.uint32();break}case 62:{s.memberLabel=E.proto.MemberLabel.decode(e,e.uint32());break}case 63:{s.isQuestion=e.bool();break}case 64:{s.statusSourceType=e.int32();break}case 65:{s.statusAttributions&&s.statusAttributions.length||(s.statusAttributions=[]),s.statusAttributions.push(E.proto.StatusAttribution.decode(e,e.uint32()));break}case 66:{s.isGroupStatus=e.bool();break}case 67:{s.forwardOrigin=e.int32();break}case 68:{s.questionReplyQuotedMessage=E.proto.ContextInfo.QuestionReplyQuotedMessage.decode(e,e.uint32());break}case 69:{s.statusAudienceMetadata=E.proto.ContextInfo.StatusAudienceMetadata.decode(e,e.uint32());break}case 70:{s.nonJidMentions=e.uint32();break}case 71:{s.quotedType=e.int32();break}case 72:{s.botMessageSharingInfo=E.proto.BotMessageSharingInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ContextInfo)return e;var a=new E.proto.ContextInfo;if(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.participant!=null&&(a.participant=String(e.participant)),e.quotedMessage!=null){if(typeof e.quotedMessage!="object")throw TypeError(".proto.ContextInfo.quotedMessage: object expected");a.quotedMessage=E.proto.Message.fromObject(e.quotedMessage)}if(e.remoteJid!=null&&(a.remoteJid=String(e.remoteJid)),e.mentionedJid){if(!Array.isArray(e.mentionedJid))throw TypeError(".proto.ContextInfo.mentionedJid: array expected");a.mentionedJid=[];for(var A=0;A=0&&(a.conversionData=e.conversionData)),e.conversionDelaySeconds!=null&&(a.conversionDelaySeconds=e.conversionDelaySeconds>>>0),e.forwardingScore!=null&&(a.forwardingScore=e.forwardingScore>>>0),e.isForwarded!=null&&(a.isForwarded=!!e.isForwarded),e.quotedAd!=null){if(typeof e.quotedAd!="object")throw TypeError(".proto.ContextInfo.quotedAd: object expected");a.quotedAd=E.proto.ContextInfo.AdReplyInfo.fromObject(e.quotedAd)}if(e.placeholderKey!=null){if(typeof e.placeholderKey!="object")throw TypeError(".proto.ContextInfo.placeholderKey: object expected");a.placeholderKey=E.proto.MessageKey.fromObject(e.placeholderKey)}if(e.expiration!=null&&(a.expiration=e.expiration>>>0),e.ephemeralSettingTimestamp!=null&&(I.Long?(a.ephemeralSettingTimestamp=I.Long.fromValue(e.ephemeralSettingTimestamp)).unsigned=!1:typeof e.ephemeralSettingTimestamp=="string"?a.ephemeralSettingTimestamp=parseInt(e.ephemeralSettingTimestamp,10):typeof e.ephemeralSettingTimestamp=="number"?a.ephemeralSettingTimestamp=e.ephemeralSettingTimestamp:typeof e.ephemeralSettingTimestamp=="object"&&(a.ephemeralSettingTimestamp=new I.LongBits(e.ephemeralSettingTimestamp.low>>>0,e.ephemeralSettingTimestamp.high>>>0).toNumber())),e.ephemeralSharedSecret!=null&&(typeof e.ephemeralSharedSecret=="string"?I.base64.decode(e.ephemeralSharedSecret,a.ephemeralSharedSecret=I.newBuffer(I.base64.length(e.ephemeralSharedSecret)),0):e.ephemeralSharedSecret.length>=0&&(a.ephemeralSharedSecret=e.ephemeralSharedSecret)),e.externalAdReply!=null){if(typeof e.externalAdReply!="object")throw TypeError(".proto.ContextInfo.externalAdReply: object expected");a.externalAdReply=E.proto.ContextInfo.ExternalAdReplyInfo.fromObject(e.externalAdReply)}if(e.entryPointConversionSource!=null&&(a.entryPointConversionSource=String(e.entryPointConversionSource)),e.entryPointConversionApp!=null&&(a.entryPointConversionApp=String(e.entryPointConversionApp)),e.entryPointConversionDelaySeconds!=null&&(a.entryPointConversionDelaySeconds=e.entryPointConversionDelaySeconds>>>0),e.disappearingMode!=null){if(typeof e.disappearingMode!="object")throw TypeError(".proto.ContextInfo.disappearingMode: object expected");a.disappearingMode=E.proto.DisappearingMode.fromObject(e.disappearingMode)}if(e.actionLink!=null){if(typeof e.actionLink!="object")throw TypeError(".proto.ContextInfo.actionLink: object expected");a.actionLink=E.proto.ActionLink.fromObject(e.actionLink)}if(e.groupSubject!=null&&(a.groupSubject=String(e.groupSubject)),e.parentGroupJid!=null&&(a.parentGroupJid=String(e.parentGroupJid)),e.trustBannerType!=null&&(a.trustBannerType=String(e.trustBannerType)),e.trustBannerAction!=null&&(a.trustBannerAction=e.trustBannerAction>>>0),e.isSampled!=null&&(a.isSampled=!!e.isSampled),e.groupMentions){if(!Array.isArray(e.groupMentions))throw TypeError(".proto.ContextInfo.groupMentions: array expected");a.groupMentions=[];for(var A=0;A=0&&(a.ctwaPayload=e.ctwaPayload)),e.forwardedAiBotMessageInfo!=null){if(typeof e.forwardedAiBotMessageInfo!="object")throw TypeError(".proto.ContextInfo.forwardedAiBotMessageInfo: object expected");a.forwardedAiBotMessageInfo=E.proto.ForwardedAIBotMessageInfo.fromObject(e.forwardedAiBotMessageInfo)}switch(e.statusAttributionType){default:if(typeof e.statusAttributionType=="number"){a.statusAttributionType=e.statusAttributionType;break}break;case"NONE":case 0:a.statusAttributionType=0;break;case"RESHARED_FROM_MENTION":case 1:a.statusAttributionType=1;break;case"RESHARED_FROM_POST":case 2:a.statusAttributionType=2;break;case"RESHARED_FROM_POST_MANY_TIMES":case 3:a.statusAttributionType=3;break;case"FORWARDED_FROM_STATUS":case 4:a.statusAttributionType=4;break}if(e.urlTrackingMap!=null){if(typeof e.urlTrackingMap!="object")throw TypeError(".proto.ContextInfo.urlTrackingMap: object expected");a.urlTrackingMap=E.proto.UrlTrackingMap.fromObject(e.urlTrackingMap)}switch(e.pairedMediaType){default:if(typeof e.pairedMediaType=="number"){a.pairedMediaType=e.pairedMediaType;break}break;case"NOT_PAIRED_MEDIA":case 0:a.pairedMediaType=0;break;case"SD_VIDEO_PARENT":case 1:a.pairedMediaType=1;break;case"HD_VIDEO_CHILD":case 2:a.pairedMediaType=2;break;case"SD_IMAGE_PARENT":case 3:a.pairedMediaType=3;break;case"HD_IMAGE_CHILD":case 4:a.pairedMediaType=4;break;case"MOTION_PHOTO_PARENT":case 5:a.pairedMediaType=5;break;case"MOTION_PHOTO_CHILD":case 6:a.pairedMediaType=6;break;case"HEVC_VIDEO_PARENT":case 7:a.pairedMediaType=7;break;case"HEVC_VIDEO_CHILD":case 8:a.pairedMediaType=8;break}if(e.rankingVersion!=null&&(a.rankingVersion=e.rankingVersion>>>0),e.memberLabel!=null){if(typeof e.memberLabel!="object")throw TypeError(".proto.ContextInfo.memberLabel: object expected");a.memberLabel=E.proto.MemberLabel.fromObject(e.memberLabel)}switch(e.isQuestion!=null&&(a.isQuestion=!!e.isQuestion),e.statusSourceType){default:if(typeof e.statusSourceType=="number"){a.statusSourceType=e.statusSourceType;break}break;case"IMAGE":case 0:a.statusSourceType=0;break;case"VIDEO":case 1:a.statusSourceType=1;break;case"GIF":case 2:a.statusSourceType=2;break;case"AUDIO":case 3:a.statusSourceType=3;break;case"TEXT":case 4:a.statusSourceType=4;break;case"MUSIC_STANDALONE":case 5:a.statusSourceType=5;break}if(e.statusAttributions){if(!Array.isArray(e.statusAttributions))throw TypeError(".proto.ContextInfo.statusAttributions: array expected");a.statusAttributions=[];for(var A=0;A>>0),e.quotedType){default:if(typeof e.quotedType=="number"){a.quotedType=e.quotedType;break}break;case"EXPLICIT":case 0:a.quotedType=0;break;case"AUTO":case 1:a.quotedType=1;break}if(e.botMessageSharingInfo!=null){if(typeof e.botMessageSharingInfo!="object")throw TypeError(".proto.ContextInfo.botMessageSharingInfo: object expected");a.botMessageSharingInfo=E.proto.BotMessageSharingInfo.fromObject(e.botMessageSharingInfo)}return a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.mentionedJid=[],A.groupMentions=[],A.statusAttributions=[]),e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),e.quotedMessage!=null&&e.hasOwnProperty("quotedMessage")&&(A.quotedMessage=E.proto.Message.toObject(e.quotedMessage,a),a.oneofs&&(A._quotedMessage="quotedMessage")),e.remoteJid!=null&&e.hasOwnProperty("remoteJid")&&(A.remoteJid=e.remoteJid,a.oneofs&&(A._remoteJid="remoteJid")),e.mentionedJid&&e.mentionedJid.length){A.mentionedJid=[];for(var t=0;t>>3){case 1:{c.advertiserName=A.string();break}case 2:{c.mediaType=A.int32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.caption=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.AdReplyInfo)return A;var t=new E.proto.ContextInfo.AdReplyInfo;switch(A.advertiserName!=null&&(t.advertiserName=String(A.advertiserName)),A.mediaType){default:if(typeof A.mediaType=="number"){t.mediaType=A.mediaType;break}break;case"NONE":case 0:t.mediaType=0;break;case"IMAGE":case 1:t.mediaType=1;break;case"VIDEO":case 2:t.mediaType=2;break}return A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(t.caption=String(A.caption)),t},i.toObject=function(A,t){t||(t={});var s={};return A.advertiserName!=null&&A.hasOwnProperty("advertiserName")&&(s.advertiserName=A.advertiserName,t.oneofs&&(s._advertiserName="advertiserName")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=t.enums===String?E.proto.ContextInfo.AdReplyInfo.MediaType[A.mediaType]===void 0?A.mediaType:E.proto.ContextInfo.AdReplyInfo.MediaType[A.mediaType]:A.mediaType,t.oneofs&&(s._mediaType="mediaType")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.AdReplyInfo"},i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="IMAGE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),r.BusinessMessageForwardInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.businessOwnerJid=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.BusinessMessageForwardInfo)return A;var t=new E.proto.ContextInfo.BusinessMessageForwardInfo;return A.businessOwnerJid!=null&&(t.businessOwnerJid=String(A.businessOwnerJid)),t},i.toObject=function(A,t){t||(t={});var s={};return A.businessOwnerJid!=null&&A.hasOwnProperty("businessOwnerJid")&&(s.businessOwnerJid=A.businessOwnerJid,t.oneofs&&(s._businessOwnerJid="businessOwnerJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.BusinessMessageForwardInfo"},i})(),r.DataSharingContext=(function(){function i(a){if(this.parameters=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.showMmDisclosure=A.bool();break}case 2:{c.encryptedSignalTokenConsented=A.string();break}case 3:{c.parameters&&c.parameters.length||(c.parameters=[]),c.parameters.push(E.proto.ContextInfo.DataSharingContext.Parameters.decode(A,A.uint32()));break}case 4:{c.dataSharingFlags=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.DataSharingContext)return A;var t=new E.proto.ContextInfo.DataSharingContext;if(A.showMmDisclosure!=null&&(t.showMmDisclosure=!!A.showMmDisclosure),A.encryptedSignalTokenConsented!=null&&(t.encryptedSignalTokenConsented=String(A.encryptedSignalTokenConsented)),A.parameters){if(!Array.isArray(A.parameters))throw TypeError(".proto.ContextInfo.DataSharingContext.parameters: array expected");t.parameters=[];for(var s=0;s>>3){case 1:{p.key=s.string();break}case 2:{p.stringData=s.string();break}case 3:{p.intData=s.int64();break}case 4:{p.floatData=s.float();break}case 5:{p.contents=E.proto.ContextInfo.DataSharingContext.Parameters.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.ContextInfo.DataSharingContext.Parameters)return s;var g=new E.proto.ContextInfo.DataSharingContext.Parameters;if(s.key!=null&&(g.key=String(s.key)),s.stringData!=null&&(g.stringData=String(s.stringData)),s.intData!=null&&(I.Long?(g.intData=I.Long.fromValue(s.intData)).unsigned=!1:typeof s.intData=="string"?g.intData=parseInt(s.intData,10):typeof s.intData=="number"?g.intData=s.intData:typeof s.intData=="object"&&(g.intData=new I.LongBits(s.intData.low>>>0,s.intData.high>>>0).toNumber())),s.floatData!=null&&(g.floatData=Number(s.floatData)),s.contents!=null){if(typeof s.contents!="object")throw TypeError(".proto.ContextInfo.DataSharingContext.Parameters.contents: object expected");g.contents=E.proto.ContextInfo.DataSharingContext.Parameters.fromObject(s.contents)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.key!=null&&s.hasOwnProperty("key")&&(c.key=s.key,g.oneofs&&(c._key="key")),s.stringData!=null&&s.hasOwnProperty("stringData")&&(c.stringData=s.stringData,g.oneofs&&(c._stringData="stringData")),s.intData!=null&&s.hasOwnProperty("intData")&&(typeof s.intData=="number"?c.intData=g.longs===String?String(s.intData):s.intData:c.intData=g.longs===String?re(s.intData):g.longs===Number?ae(s.intData):s.intData,g.oneofs&&(c._intData="intData")),s.floatData!=null&&s.hasOwnProperty("floatData")&&(c.floatData=g.json&&!isFinite(s.floatData)?String(s.floatData):s.floatData,g.oneofs&&(c._floatData="floatData")),s.contents!=null&&s.hasOwnProperty("contents")&&(c.contents=E.proto.ContextInfo.DataSharingContext.Parameters.toObject(s.contents,g),g.oneofs&&(c._contents="contents")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ContextInfo.DataSharingContext.Parameters"},a})(),i})(),r.ExternalAdReplyInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.title=A.string();break}case 2:{c.body=A.string();break}case 3:{c.mediaType=A.int32();break}case 4:{c.thumbnailUrl=A.string();break}case 5:{c.mediaUrl=A.string();break}case 6:{c.thumbnail=A.bytes();break}case 7:{c.sourceType=A.string();break}case 8:{c.sourceId=A.string();break}case 9:{c.sourceUrl=A.string();break}case 10:{c.containsAutoReply=A.bool();break}case 11:{c.renderLargerThumbnail=A.bool();break}case 12:{c.showAdAttribution=A.bool();break}case 13:{c.ctwaClid=A.string();break}case 14:{c.ref=A.string();break}case 15:{c.clickToWhatsappCall=A.bool();break}case 16:{c.adContextPreviewDismissed=A.bool();break}case 17:{c.sourceApp=A.string();break}case 18:{c.automatedGreetingMessageShown=A.bool();break}case 19:{c.greetingMessageBody=A.string();break}case 20:{c.ctaPayload=A.string();break}case 21:{c.disableNudge=A.bool();break}case 22:{c.originalImageUrl=A.string();break}case 23:{c.automatedGreetingMessageCtaType=A.string();break}case 24:{c.wtwaAdFormat=A.bool();break}case 25:{c.adType=A.int32();break}case 26:{c.wtwaWebsiteUrl=A.string();break}case 27:{c.adPreviewUrl=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.ExternalAdReplyInfo)return A;var t=new E.proto.ContextInfo.ExternalAdReplyInfo;switch(A.title!=null&&(t.title=String(A.title)),A.body!=null&&(t.body=String(A.body)),A.mediaType){default:if(typeof A.mediaType=="number"){t.mediaType=A.mediaType;break}break;case"NONE":case 0:t.mediaType=0;break;case"IMAGE":case 1:t.mediaType=1;break;case"VIDEO":case 2:t.mediaType=2;break}switch(A.thumbnailUrl!=null&&(t.thumbnailUrl=String(A.thumbnailUrl)),A.mediaUrl!=null&&(t.mediaUrl=String(A.mediaUrl)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?I.base64.decode(A.thumbnail,t.thumbnail=I.newBuffer(I.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(t.thumbnail=A.thumbnail)),A.sourceType!=null&&(t.sourceType=String(A.sourceType)),A.sourceId!=null&&(t.sourceId=String(A.sourceId)),A.sourceUrl!=null&&(t.sourceUrl=String(A.sourceUrl)),A.containsAutoReply!=null&&(t.containsAutoReply=!!A.containsAutoReply),A.renderLargerThumbnail!=null&&(t.renderLargerThumbnail=!!A.renderLargerThumbnail),A.showAdAttribution!=null&&(t.showAdAttribution=!!A.showAdAttribution),A.ctwaClid!=null&&(t.ctwaClid=String(A.ctwaClid)),A.ref!=null&&(t.ref=String(A.ref)),A.clickToWhatsappCall!=null&&(t.clickToWhatsappCall=!!A.clickToWhatsappCall),A.adContextPreviewDismissed!=null&&(t.adContextPreviewDismissed=!!A.adContextPreviewDismissed),A.sourceApp!=null&&(t.sourceApp=String(A.sourceApp)),A.automatedGreetingMessageShown!=null&&(t.automatedGreetingMessageShown=!!A.automatedGreetingMessageShown),A.greetingMessageBody!=null&&(t.greetingMessageBody=String(A.greetingMessageBody)),A.ctaPayload!=null&&(t.ctaPayload=String(A.ctaPayload)),A.disableNudge!=null&&(t.disableNudge=!!A.disableNudge),A.originalImageUrl!=null&&(t.originalImageUrl=String(A.originalImageUrl)),A.automatedGreetingMessageCtaType!=null&&(t.automatedGreetingMessageCtaType=String(A.automatedGreetingMessageCtaType)),A.wtwaAdFormat!=null&&(t.wtwaAdFormat=!!A.wtwaAdFormat),A.adType){default:if(typeof A.adType=="number"){t.adType=A.adType;break}break;case"CTWA":case 0:t.adType=0;break;case"CAWC":case 1:t.adType=1;break}return A.wtwaWebsiteUrl!=null&&(t.wtwaWebsiteUrl=String(A.wtwaWebsiteUrl)),A.adPreviewUrl!=null&&(t.adPreviewUrl=String(A.adPreviewUrl)),t},i.toObject=function(A,t){t||(t={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,t.oneofs&&(s._body="body")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=t.enums===String?E.proto.ContextInfo.ExternalAdReplyInfo.MediaType[A.mediaType]===void 0?A.mediaType:E.proto.ContextInfo.ExternalAdReplyInfo.MediaType[A.mediaType]:A.mediaType,t.oneofs&&(s._mediaType="mediaType")),A.thumbnailUrl!=null&&A.hasOwnProperty("thumbnailUrl")&&(s.thumbnailUrl=A.thumbnailUrl,t.oneofs&&(s._thumbnailUrl="thumbnailUrl")),A.mediaUrl!=null&&A.hasOwnProperty("mediaUrl")&&(s.mediaUrl=A.mediaUrl,t.oneofs&&(s._mediaUrl="mediaUrl")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=t.bytes===String?I.base64.encode(A.thumbnail,0,A.thumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,t.oneofs&&(s._thumbnail="thumbnail")),A.sourceType!=null&&A.hasOwnProperty("sourceType")&&(s.sourceType=A.sourceType,t.oneofs&&(s._sourceType="sourceType")),A.sourceId!=null&&A.hasOwnProperty("sourceId")&&(s.sourceId=A.sourceId,t.oneofs&&(s._sourceId="sourceId")),A.sourceUrl!=null&&A.hasOwnProperty("sourceUrl")&&(s.sourceUrl=A.sourceUrl,t.oneofs&&(s._sourceUrl="sourceUrl")),A.containsAutoReply!=null&&A.hasOwnProperty("containsAutoReply")&&(s.containsAutoReply=A.containsAutoReply,t.oneofs&&(s._containsAutoReply="containsAutoReply")),A.renderLargerThumbnail!=null&&A.hasOwnProperty("renderLargerThumbnail")&&(s.renderLargerThumbnail=A.renderLargerThumbnail,t.oneofs&&(s._renderLargerThumbnail="renderLargerThumbnail")),A.showAdAttribution!=null&&A.hasOwnProperty("showAdAttribution")&&(s.showAdAttribution=A.showAdAttribution,t.oneofs&&(s._showAdAttribution="showAdAttribution")),A.ctwaClid!=null&&A.hasOwnProperty("ctwaClid")&&(s.ctwaClid=A.ctwaClid,t.oneofs&&(s._ctwaClid="ctwaClid")),A.ref!=null&&A.hasOwnProperty("ref")&&(s.ref=A.ref,t.oneofs&&(s._ref="ref")),A.clickToWhatsappCall!=null&&A.hasOwnProperty("clickToWhatsappCall")&&(s.clickToWhatsappCall=A.clickToWhatsappCall,t.oneofs&&(s._clickToWhatsappCall="clickToWhatsappCall")),A.adContextPreviewDismissed!=null&&A.hasOwnProperty("adContextPreviewDismissed")&&(s.adContextPreviewDismissed=A.adContextPreviewDismissed,t.oneofs&&(s._adContextPreviewDismissed="adContextPreviewDismissed")),A.sourceApp!=null&&A.hasOwnProperty("sourceApp")&&(s.sourceApp=A.sourceApp,t.oneofs&&(s._sourceApp="sourceApp")),A.automatedGreetingMessageShown!=null&&A.hasOwnProperty("automatedGreetingMessageShown")&&(s.automatedGreetingMessageShown=A.automatedGreetingMessageShown,t.oneofs&&(s._automatedGreetingMessageShown="automatedGreetingMessageShown")),A.greetingMessageBody!=null&&A.hasOwnProperty("greetingMessageBody")&&(s.greetingMessageBody=A.greetingMessageBody,t.oneofs&&(s._greetingMessageBody="greetingMessageBody")),A.ctaPayload!=null&&A.hasOwnProperty("ctaPayload")&&(s.ctaPayload=A.ctaPayload,t.oneofs&&(s._ctaPayload="ctaPayload")),A.disableNudge!=null&&A.hasOwnProperty("disableNudge")&&(s.disableNudge=A.disableNudge,t.oneofs&&(s._disableNudge="disableNudge")),A.originalImageUrl!=null&&A.hasOwnProperty("originalImageUrl")&&(s.originalImageUrl=A.originalImageUrl,t.oneofs&&(s._originalImageUrl="originalImageUrl")),A.automatedGreetingMessageCtaType!=null&&A.hasOwnProperty("automatedGreetingMessageCtaType")&&(s.automatedGreetingMessageCtaType=A.automatedGreetingMessageCtaType,t.oneofs&&(s._automatedGreetingMessageCtaType="automatedGreetingMessageCtaType")),A.wtwaAdFormat!=null&&A.hasOwnProperty("wtwaAdFormat")&&(s.wtwaAdFormat=A.wtwaAdFormat,t.oneofs&&(s._wtwaAdFormat="wtwaAdFormat")),A.adType!=null&&A.hasOwnProperty("adType")&&(s.adType=t.enums===String?E.proto.ContextInfo.ExternalAdReplyInfo.AdType[A.adType]===void 0?A.adType:E.proto.ContextInfo.ExternalAdReplyInfo.AdType[A.adType]:A.adType,t.oneofs&&(s._adType="adType")),A.wtwaWebsiteUrl!=null&&A.hasOwnProperty("wtwaWebsiteUrl")&&(s.wtwaWebsiteUrl=A.wtwaWebsiteUrl,t.oneofs&&(s._wtwaWebsiteUrl="wtwaWebsiteUrl")),A.adPreviewUrl!=null&&A.hasOwnProperty("adPreviewUrl")&&(s.adPreviewUrl=A.adPreviewUrl,t.oneofs&&(s._adPreviewUrl="adPreviewUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.ExternalAdReplyInfo"},i.AdType=(function(){let a={},A=Object.create(a);return A[a[0]="CTWA"]=0,A[a[1]="CAWC"]=1,A})(),i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="IMAGE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),r.FeatureEligibilities=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.cannotBeReactedTo=A.bool();break}case 2:{c.cannotBeRanked=A.bool();break}case 3:{c.canRequestFeedback=A.bool();break}case 4:{c.canBeReshared=A.bool();break}case 5:{c.canReceiveMultiReact=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.FeatureEligibilities)return A;var t=new E.proto.ContextInfo.FeatureEligibilities;return A.cannotBeReactedTo!=null&&(t.cannotBeReactedTo=!!A.cannotBeReactedTo),A.cannotBeRanked!=null&&(t.cannotBeRanked=!!A.cannotBeRanked),A.canRequestFeedback!=null&&(t.canRequestFeedback=!!A.canRequestFeedback),A.canBeReshared!=null&&(t.canBeReshared=!!A.canBeReshared),A.canReceiveMultiReact!=null&&(t.canReceiveMultiReact=!!A.canReceiveMultiReact),t},i.toObject=function(A,t){t||(t={});var s={};return A.cannotBeReactedTo!=null&&A.hasOwnProperty("cannotBeReactedTo")&&(s.cannotBeReactedTo=A.cannotBeReactedTo,t.oneofs&&(s._cannotBeReactedTo="cannotBeReactedTo")),A.cannotBeRanked!=null&&A.hasOwnProperty("cannotBeRanked")&&(s.cannotBeRanked=A.cannotBeRanked,t.oneofs&&(s._cannotBeRanked="cannotBeRanked")),A.canRequestFeedback!=null&&A.hasOwnProperty("canRequestFeedback")&&(s.canRequestFeedback=A.canRequestFeedback,t.oneofs&&(s._canRequestFeedback="canRequestFeedback")),A.canBeReshared!=null&&A.hasOwnProperty("canBeReshared")&&(s.canBeReshared=A.canBeReshared,t.oneofs&&(s._canBeReshared="canBeReshared")),A.canReceiveMultiReact!=null&&A.hasOwnProperty("canReceiveMultiReact")&&(s.canReceiveMultiReact=A.canReceiveMultiReact,t.oneofs&&(s._canReceiveMultiReact="canReceiveMultiReact")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.FeatureEligibilities"},i})(),r.ForwardOrigin=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT"]=1,e[i[2]="STATUS"]=2,e[i[3]="CHANNELS"]=3,e[i[4]="META_AI"]=4,e[i[5]="UGC"]=5,e})(),r.ForwardedNewsletterMessageInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.serverMessageId=A.int32();break}case 3:{c.newsletterName=A.string();break}case 4:{c.contentType=A.int32();break}case 5:{c.accessibilityText=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.ForwardedNewsletterMessageInfo)return A;var t=new E.proto.ContextInfo.ForwardedNewsletterMessageInfo;switch(A.newsletterJid!=null&&(t.newsletterJid=String(A.newsletterJid)),A.serverMessageId!=null&&(t.serverMessageId=A.serverMessageId|0),A.newsletterName!=null&&(t.newsletterName=String(A.newsletterName)),A.contentType){default:if(typeof A.contentType=="number"){t.contentType=A.contentType;break}break;case"UPDATE":case 1:t.contentType=1;break;case"UPDATE_CARD":case 2:t.contentType=2;break;case"LINK_CARD":case 3:t.contentType=3;break}return A.accessibilityText!=null&&(t.accessibilityText=String(A.accessibilityText)),t},i.toObject=function(A,t){t||(t={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,t.oneofs&&(s._newsletterJid="newsletterJid")),A.serverMessageId!=null&&A.hasOwnProperty("serverMessageId")&&(s.serverMessageId=A.serverMessageId,t.oneofs&&(s._serverMessageId="serverMessageId")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,t.oneofs&&(s._newsletterName="newsletterName")),A.contentType!=null&&A.hasOwnProperty("contentType")&&(s.contentType=t.enums===String?E.proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType[A.contentType]===void 0?A.contentType:E.proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType[A.contentType]:A.contentType,t.oneofs&&(s._contentType="contentType")),A.accessibilityText!=null&&A.hasOwnProperty("accessibilityText")&&(s.accessibilityText=A.accessibilityText,t.oneofs&&(s._accessibilityText="accessibilityText")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.ForwardedNewsletterMessageInfo"},i.ContentType=(function(){let a={},A=Object.create(a);return A[a[1]="UPDATE"]=1,A[a[2]="UPDATE_CARD"]=2,A[a[3]="LINK_CARD"]=3,A})(),i})(),r.PairedMediaType=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_PAIRED_MEDIA"]=0,e[i[1]="SD_VIDEO_PARENT"]=1,e[i[2]="HD_VIDEO_CHILD"]=2,e[i[3]="SD_IMAGE_PARENT"]=3,e[i[4]="HD_IMAGE_CHILD"]=4,e[i[5]="MOTION_PHOTO_PARENT"]=5,e[i[6]="MOTION_PHOTO_CHILD"]=6,e[i[7]="HEVC_VIDEO_PARENT"]=7,e[i[8]="HEVC_VIDEO_CHILD"]=8,e})(),r.QuestionReplyQuotedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.serverQuestionId=A.int32();break}case 2:{c.quotedQuestion=E.proto.Message.decode(A,A.uint32());break}case 3:{c.quotedResponse=E.proto.Message.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.QuestionReplyQuotedMessage)return A;var t=new E.proto.ContextInfo.QuestionReplyQuotedMessage;if(A.serverQuestionId!=null&&(t.serverQuestionId=A.serverQuestionId|0),A.quotedQuestion!=null){if(typeof A.quotedQuestion!="object")throw TypeError(".proto.ContextInfo.QuestionReplyQuotedMessage.quotedQuestion: object expected");t.quotedQuestion=E.proto.Message.fromObject(A.quotedQuestion)}if(A.quotedResponse!=null){if(typeof A.quotedResponse!="object")throw TypeError(".proto.ContextInfo.QuestionReplyQuotedMessage.quotedResponse: object expected");t.quotedResponse=E.proto.Message.fromObject(A.quotedResponse)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.serverQuestionId!=null&&A.hasOwnProperty("serverQuestionId")&&(s.serverQuestionId=A.serverQuestionId,t.oneofs&&(s._serverQuestionId="serverQuestionId")),A.quotedQuestion!=null&&A.hasOwnProperty("quotedQuestion")&&(s.quotedQuestion=E.proto.Message.toObject(A.quotedQuestion,t),t.oneofs&&(s._quotedQuestion="quotedQuestion")),A.quotedResponse!=null&&A.hasOwnProperty("quotedResponse")&&(s.quotedResponse=E.proto.Message.toObject(A.quotedResponse,t),t.oneofs&&(s._quotedResponse="quotedResponse")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.QuestionReplyQuotedMessage"},i})(),r.QuotedType=(function(){let i={},e=Object.create(i);return e[i[0]="EXPLICIT"]=0,e[i[1]="AUTO"]=1,e})(),r.StatusAttributionType=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="RESHARED_FROM_MENTION"]=1,e[i[2]="RESHARED_FROM_POST"]=2,e[i[3]="RESHARED_FROM_POST_MANY_TIMES"]=3,e[i[4]="FORWARDED_FROM_STATUS"]=4,e})(),r.StatusAudienceMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.audienceType=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.StatusAudienceMetadata)return A;var t=new E.proto.ContextInfo.StatusAudienceMetadata;switch(A.audienceType){default:if(typeof A.audienceType=="number"){t.audienceType=A.audienceType;break}break;case"UNKNOWN":case 0:t.audienceType=0;break;case"CLOSE_FRIENDS":case 1:t.audienceType=1;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.audienceType!=null&&A.hasOwnProperty("audienceType")&&(s.audienceType=t.enums===String?E.proto.ContextInfo.StatusAudienceMetadata.AudienceType[A.audienceType]===void 0?A.audienceType:E.proto.ContextInfo.StatusAudienceMetadata.AudienceType[A.audienceType]:A.audienceType,t.oneofs&&(s._audienceType="audienceType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.StatusAudienceMetadata"},i.AudienceType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CLOSE_FRIENDS"]=1,A})(),i})(),r.StatusSourceType=(function(){let i={},e=Object.create(i);return e[i[0]="IMAGE"]=0,e[i[1]="VIDEO"]=1,e[i[2]="GIF"]=2,e[i[3]="AUDIO"]=3,e[i[4]="TEXT"]=4,e[i[5]="MUSIC_STANDALONE"]=5,e})(),r.UTMInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.utmSource=A.string();break}case 2:{c.utmCampaign=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.ContextInfo.UTMInfo)return A;var t=new E.proto.ContextInfo.UTMInfo;return A.utmSource!=null&&(t.utmSource=String(A.utmSource)),A.utmCampaign!=null&&(t.utmCampaign=String(A.utmCampaign)),t},i.toObject=function(A,t){t||(t={});var s={};return A.utmSource!=null&&A.hasOwnProperty("utmSource")&&(s.utmSource=A.utmSource,t.oneofs&&(s._utmSource="utmSource")),A.utmCampaign!=null&&A.hasOwnProperty("utmCampaign")&&(s.utmCampaign=A.utmCampaign,t.oneofs&&(s._utmCampaign="utmCampaign")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.UTMInfo"},i})(),r})(),n.Conversation=(function(){function r(i){if(this.messages=[],this.participant=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.messages&&s.messages.length||(s.messages=[]),s.messages.push(E.proto.HistorySyncMsg.decode(e,e.uint32()));break}case 3:{s.newJid=e.string();break}case 4:{s.oldJid=e.string();break}case 5:{s.lastMsgTimestamp=e.uint64();break}case 6:{s.unreadCount=e.uint32();break}case 7:{s.readOnly=e.bool();break}case 8:{s.endOfHistoryTransfer=e.bool();break}case 9:{s.ephemeralExpiration=e.uint32();break}case 10:{s.ephemeralSettingTimestamp=e.int64();break}case 11:{s.endOfHistoryTransferType=e.int32();break}case 12:{s.conversationTimestamp=e.uint64();break}case 13:{s.name=e.string();break}case 14:{s.pHash=e.string();break}case 15:{s.notSpam=e.bool();break}case 16:{s.archived=e.bool();break}case 17:{s.disappearingMode=E.proto.DisappearingMode.decode(e,e.uint32());break}case 18:{s.unreadMentionCount=e.uint32();break}case 19:{s.markedAsUnread=e.bool();break}case 20:{s.participant&&s.participant.length||(s.participant=[]),s.participant.push(E.proto.GroupParticipant.decode(e,e.uint32()));break}case 21:{s.tcToken=e.bytes();break}case 22:{s.tcTokenTimestamp=e.uint64();break}case 23:{s.contactPrimaryIdentityKey=e.bytes();break}case 24:{s.pinned=e.uint32();break}case 25:{s.muteEndTime=e.uint64();break}case 26:{s.wallpaper=E.proto.WallpaperSettings.decode(e,e.uint32());break}case 27:{s.mediaVisibility=e.int32();break}case 28:{s.tcTokenSenderTimestamp=e.uint64();break}case 29:{s.suspended=e.bool();break}case 30:{s.terminated=e.bool();break}case 31:{s.createdAt=e.uint64();break}case 32:{s.createdBy=e.string();break}case 33:{s.description=e.string();break}case 34:{s.support=e.bool();break}case 35:{s.isParentGroup=e.bool();break}case 37:{s.parentGroupId=e.string();break}case 36:{s.isDefaultSubgroup=e.bool();break}case 38:{s.displayName=e.string();break}case 39:{s.pnJid=e.string();break}case 40:{s.shareOwnPn=e.bool();break}case 41:{s.pnhDuplicateLidThread=e.bool();break}case 42:{s.lidJid=e.string();break}case 43:{s.username=e.string();break}case 44:{s.lidOriginType=e.string();break}case 45:{s.commentsCount=e.uint32();break}case 46:{s.locked=e.bool();break}case 47:{s.systemMessageToInsert=e.int32();break}case 48:{s.capiCreatedGroup=e.bool();break}case 49:{s.accountLid=e.string();break}case 50:{s.limitSharing=e.bool();break}case 51:{s.limitSharingSettingTimestamp=e.int64();break}case 52:{s.limitSharingTrigger=e.int32();break}case 53:{s.limitSharingInitiatedByMe=e.bool();break}case 54:{s.maibaAiThreadEnabled=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Conversation)return e;var a=new E.proto.Conversation;if(e.id!=null&&(a.id=String(e.id)),e.messages){if(!Array.isArray(e.messages))throw TypeError(".proto.Conversation.messages: array expected");a.messages=[];for(var A=0;A>>0,e.lastMsgTimestamp.high>>>0).toNumber(!0))),e.unreadCount!=null&&(a.unreadCount=e.unreadCount>>>0),e.readOnly!=null&&(a.readOnly=!!e.readOnly),e.endOfHistoryTransfer!=null&&(a.endOfHistoryTransfer=!!e.endOfHistoryTransfer),e.ephemeralExpiration!=null&&(a.ephemeralExpiration=e.ephemeralExpiration>>>0),e.ephemeralSettingTimestamp!=null&&(I.Long?(a.ephemeralSettingTimestamp=I.Long.fromValue(e.ephemeralSettingTimestamp)).unsigned=!1:typeof e.ephemeralSettingTimestamp=="string"?a.ephemeralSettingTimestamp=parseInt(e.ephemeralSettingTimestamp,10):typeof e.ephemeralSettingTimestamp=="number"?a.ephemeralSettingTimestamp=e.ephemeralSettingTimestamp:typeof e.ephemeralSettingTimestamp=="object"&&(a.ephemeralSettingTimestamp=new I.LongBits(e.ephemeralSettingTimestamp.low>>>0,e.ephemeralSettingTimestamp.high>>>0).toNumber())),e.endOfHistoryTransferType){default:if(typeof e.endOfHistoryTransferType=="number"){a.endOfHistoryTransferType=e.endOfHistoryTransferType;break}break;case"COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY":case 0:a.endOfHistoryTransferType=0;break;case"COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY":case 1:a.endOfHistoryTransferType=1;break;case"COMPLETE_ON_DEMAND_SYNC_BUT_MORE_MSG_REMAIN_ON_PRIMARY":case 2:a.endOfHistoryTransferType=2;break}if(e.conversationTimestamp!=null&&(I.Long?(a.conversationTimestamp=I.Long.fromValue(e.conversationTimestamp)).unsigned=!0:typeof e.conversationTimestamp=="string"?a.conversationTimestamp=parseInt(e.conversationTimestamp,10):typeof e.conversationTimestamp=="number"?a.conversationTimestamp=e.conversationTimestamp:typeof e.conversationTimestamp=="object"&&(a.conversationTimestamp=new I.LongBits(e.conversationTimestamp.low>>>0,e.conversationTimestamp.high>>>0).toNumber(!0))),e.name!=null&&(a.name=String(e.name)),e.pHash!=null&&(a.pHash=String(e.pHash)),e.notSpam!=null&&(a.notSpam=!!e.notSpam),e.archived!=null&&(a.archived=!!e.archived),e.disappearingMode!=null){if(typeof e.disappearingMode!="object")throw TypeError(".proto.Conversation.disappearingMode: object expected");a.disappearingMode=E.proto.DisappearingMode.fromObject(e.disappearingMode)}if(e.unreadMentionCount!=null&&(a.unreadMentionCount=e.unreadMentionCount>>>0),e.markedAsUnread!=null&&(a.markedAsUnread=!!e.markedAsUnread),e.participant){if(!Array.isArray(e.participant))throw TypeError(".proto.Conversation.participant: array expected");a.participant=[];for(var A=0;A=0&&(a.tcToken=e.tcToken)),e.tcTokenTimestamp!=null&&(I.Long?(a.tcTokenTimestamp=I.Long.fromValue(e.tcTokenTimestamp)).unsigned=!0:typeof e.tcTokenTimestamp=="string"?a.tcTokenTimestamp=parseInt(e.tcTokenTimestamp,10):typeof e.tcTokenTimestamp=="number"?a.tcTokenTimestamp=e.tcTokenTimestamp:typeof e.tcTokenTimestamp=="object"&&(a.tcTokenTimestamp=new I.LongBits(e.tcTokenTimestamp.low>>>0,e.tcTokenTimestamp.high>>>0).toNumber(!0))),e.contactPrimaryIdentityKey!=null&&(typeof e.contactPrimaryIdentityKey=="string"?I.base64.decode(e.contactPrimaryIdentityKey,a.contactPrimaryIdentityKey=I.newBuffer(I.base64.length(e.contactPrimaryIdentityKey)),0):e.contactPrimaryIdentityKey.length>=0&&(a.contactPrimaryIdentityKey=e.contactPrimaryIdentityKey)),e.pinned!=null&&(a.pinned=e.pinned>>>0),e.muteEndTime!=null&&(I.Long?(a.muteEndTime=I.Long.fromValue(e.muteEndTime)).unsigned=!0:typeof e.muteEndTime=="string"?a.muteEndTime=parseInt(e.muteEndTime,10):typeof e.muteEndTime=="number"?a.muteEndTime=e.muteEndTime:typeof e.muteEndTime=="object"&&(a.muteEndTime=new I.LongBits(e.muteEndTime.low>>>0,e.muteEndTime.high>>>0).toNumber(!0))),e.wallpaper!=null){if(typeof e.wallpaper!="object")throw TypeError(".proto.Conversation.wallpaper: object expected");a.wallpaper=E.proto.WallpaperSettings.fromObject(e.wallpaper)}switch(e.mediaVisibility){default:if(typeof e.mediaVisibility=="number"){a.mediaVisibility=e.mediaVisibility;break}break;case"DEFAULT":case 0:a.mediaVisibility=0;break;case"OFF":case 1:a.mediaVisibility=1;break;case"ON":case 2:a.mediaVisibility=2;break}switch(e.tcTokenSenderTimestamp!=null&&(I.Long?(a.tcTokenSenderTimestamp=I.Long.fromValue(e.tcTokenSenderTimestamp)).unsigned=!0:typeof e.tcTokenSenderTimestamp=="string"?a.tcTokenSenderTimestamp=parseInt(e.tcTokenSenderTimestamp,10):typeof e.tcTokenSenderTimestamp=="number"?a.tcTokenSenderTimestamp=e.tcTokenSenderTimestamp:typeof e.tcTokenSenderTimestamp=="object"&&(a.tcTokenSenderTimestamp=new I.LongBits(e.tcTokenSenderTimestamp.low>>>0,e.tcTokenSenderTimestamp.high>>>0).toNumber(!0))),e.suspended!=null&&(a.suspended=!!e.suspended),e.terminated!=null&&(a.terminated=!!e.terminated),e.createdAt!=null&&(I.Long?(a.createdAt=I.Long.fromValue(e.createdAt)).unsigned=!0:typeof e.createdAt=="string"?a.createdAt=parseInt(e.createdAt,10):typeof e.createdAt=="number"?a.createdAt=e.createdAt:typeof e.createdAt=="object"&&(a.createdAt=new I.LongBits(e.createdAt.low>>>0,e.createdAt.high>>>0).toNumber(!0))),e.createdBy!=null&&(a.createdBy=String(e.createdBy)),e.description!=null&&(a.description=String(e.description)),e.support!=null&&(a.support=!!e.support),e.isParentGroup!=null&&(a.isParentGroup=!!e.isParentGroup),e.parentGroupId!=null&&(a.parentGroupId=String(e.parentGroupId)),e.isDefaultSubgroup!=null&&(a.isDefaultSubgroup=!!e.isDefaultSubgroup),e.displayName!=null&&(a.displayName=String(e.displayName)),e.pnJid!=null&&(a.pnJid=String(e.pnJid)),e.shareOwnPn!=null&&(a.shareOwnPn=!!e.shareOwnPn),e.pnhDuplicateLidThread!=null&&(a.pnhDuplicateLidThread=!!e.pnhDuplicateLidThread),e.lidJid!=null&&(a.lidJid=String(e.lidJid)),e.username!=null&&(a.username=String(e.username)),e.lidOriginType!=null&&(a.lidOriginType=String(e.lidOriginType)),e.commentsCount!=null&&(a.commentsCount=e.commentsCount>>>0),e.locked!=null&&(a.locked=!!e.locked),e.systemMessageToInsert){default:if(typeof e.systemMessageToInsert=="number"){a.systemMessageToInsert=e.systemMessageToInsert;break}break;case"E2EE_MSG":case 1:a.systemMessageToInsert=1;break;case"NE2EE_SELF":case 2:a.systemMessageToInsert=2;break;case"NE2EE_OTHER":case 3:a.systemMessageToInsert=3;break}switch(e.capiCreatedGroup!=null&&(a.capiCreatedGroup=!!e.capiCreatedGroup),e.accountLid!=null&&(a.accountLid=String(e.accountLid)),e.limitSharing!=null&&(a.limitSharing=!!e.limitSharing),e.limitSharingSettingTimestamp!=null&&(I.Long?(a.limitSharingSettingTimestamp=I.Long.fromValue(e.limitSharingSettingTimestamp)).unsigned=!1:typeof e.limitSharingSettingTimestamp=="string"?a.limitSharingSettingTimestamp=parseInt(e.limitSharingSettingTimestamp,10):typeof e.limitSharingSettingTimestamp=="number"?a.limitSharingSettingTimestamp=e.limitSharingSettingTimestamp:typeof e.limitSharingSettingTimestamp=="object"&&(a.limitSharingSettingTimestamp=new I.LongBits(e.limitSharingSettingTimestamp.low>>>0,e.limitSharingSettingTimestamp.high>>>0).toNumber())),e.limitSharingTrigger){default:if(typeof e.limitSharingTrigger=="number"){a.limitSharingTrigger=e.limitSharingTrigger;break}break;case"UNKNOWN":case 0:a.limitSharingTrigger=0;break;case"CHAT_SETTING":case 1:a.limitSharingTrigger=1;break;case"BIZ_SUPPORTS_FB_HOSTING":case 2:a.limitSharingTrigger=2;break;case"UNKNOWN_GROUP":case 3:a.limitSharingTrigger=3;break}return e.limitSharingInitiatedByMe!=null&&(a.limitSharingInitiatedByMe=!!e.limitSharingInitiatedByMe),e.maibaAiThreadEnabled!=null&&(a.maibaAiThreadEnabled=!!e.maibaAiThreadEnabled),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.messages=[],A.participant=[]),a.defaults&&(A.id=""),e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id),e.messages&&e.messages.length){A.messages=[];for(var t=0;t>>3){case 1:{s.chatLockSupportLevel=e.int32();break}case 2:{s.lidMigration=E.proto.DeviceCapabilities.LIDMigration.decode(e,e.uint32());break}case 3:{s.businessBroadcast=E.proto.DeviceCapabilities.BusinessBroadcast.decode(e,e.uint32());break}case 4:{s.userHasAvatar=E.proto.DeviceCapabilities.UserHasAvatar.decode(e,e.uint32());break}case 5:{s.memberNameTagPrimarySupport=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.DeviceCapabilities)return e;var a=new E.proto.DeviceCapabilities;switch(e.chatLockSupportLevel){default:if(typeof e.chatLockSupportLevel=="number"){a.chatLockSupportLevel=e.chatLockSupportLevel;break}break;case"NONE":case 0:a.chatLockSupportLevel=0;break;case"MINIMAL":case 1:a.chatLockSupportLevel=1;break;case"FULL":case 2:a.chatLockSupportLevel=2;break}if(e.lidMigration!=null){if(typeof e.lidMigration!="object")throw TypeError(".proto.DeviceCapabilities.lidMigration: object expected");a.lidMigration=E.proto.DeviceCapabilities.LIDMigration.fromObject(e.lidMigration)}if(e.businessBroadcast!=null){if(typeof e.businessBroadcast!="object")throw TypeError(".proto.DeviceCapabilities.businessBroadcast: object expected");a.businessBroadcast=E.proto.DeviceCapabilities.BusinessBroadcast.fromObject(e.businessBroadcast)}if(e.userHasAvatar!=null){if(typeof e.userHasAvatar!="object")throw TypeError(".proto.DeviceCapabilities.userHasAvatar: object expected");a.userHasAvatar=E.proto.DeviceCapabilities.UserHasAvatar.fromObject(e.userHasAvatar)}switch(e.memberNameTagPrimarySupport){default:if(typeof e.memberNameTagPrimarySupport=="number"){a.memberNameTagPrimarySupport=e.memberNameTagPrimarySupport;break}break;case"DISABLED":case 0:a.memberNameTagPrimarySupport=0;break;case"RECEIVER_ENABLED":case 1:a.memberNameTagPrimarySupport=1;break;case"SENDER_ENABLED":case 2:a.memberNameTagPrimarySupport=2;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.chatLockSupportLevel!=null&&e.hasOwnProperty("chatLockSupportLevel")&&(A.chatLockSupportLevel=a.enums===String?E.proto.DeviceCapabilities.ChatLockSupportLevel[e.chatLockSupportLevel]===void 0?e.chatLockSupportLevel:E.proto.DeviceCapabilities.ChatLockSupportLevel[e.chatLockSupportLevel]:e.chatLockSupportLevel,a.oneofs&&(A._chatLockSupportLevel="chatLockSupportLevel")),e.lidMigration!=null&&e.hasOwnProperty("lidMigration")&&(A.lidMigration=E.proto.DeviceCapabilities.LIDMigration.toObject(e.lidMigration,a),a.oneofs&&(A._lidMigration="lidMigration")),e.businessBroadcast!=null&&e.hasOwnProperty("businessBroadcast")&&(A.businessBroadcast=E.proto.DeviceCapabilities.BusinessBroadcast.toObject(e.businessBroadcast,a),a.oneofs&&(A._businessBroadcast="businessBroadcast")),e.userHasAvatar!=null&&e.hasOwnProperty("userHasAvatar")&&(A.userHasAvatar=E.proto.DeviceCapabilities.UserHasAvatar.toObject(e.userHasAvatar,a),a.oneofs&&(A._userHasAvatar="userHasAvatar")),e.memberNameTagPrimarySupport!=null&&e.hasOwnProperty("memberNameTagPrimarySupport")&&(A.memberNameTagPrimarySupport=a.enums===String?E.proto.DeviceCapabilities.MemberNameTagPrimarySupport[e.memberNameTagPrimarySupport]===void 0?e.memberNameTagPrimarySupport:E.proto.DeviceCapabilities.MemberNameTagPrimarySupport[e.memberNameTagPrimarySupport]:e.memberNameTagPrimarySupport,a.oneofs&&(A._memberNameTagPrimarySupport="memberNameTagPrimarySupport")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceCapabilities"},r.BusinessBroadcast=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.importListEnabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.DeviceCapabilities.BusinessBroadcast)return A;var t=new E.proto.DeviceCapabilities.BusinessBroadcast;return A.importListEnabled!=null&&(t.importListEnabled=!!A.importListEnabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.importListEnabled!=null&&A.hasOwnProperty("importListEnabled")&&(s.importListEnabled=A.importListEnabled,t.oneofs&&(s._importListEnabled="importListEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.BusinessBroadcast"},i})(),r.ChatLockSupportLevel=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="MINIMAL"]=1,e[i[2]="FULL"]=2,e})(),r.LIDMigration=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.chatDbMigrationTimestamp=A.uint64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.DeviceCapabilities.LIDMigration)return A;var t=new E.proto.DeviceCapabilities.LIDMigration;return A.chatDbMigrationTimestamp!=null&&(I.Long?(t.chatDbMigrationTimestamp=I.Long.fromValue(A.chatDbMigrationTimestamp)).unsigned=!0:typeof A.chatDbMigrationTimestamp=="string"?t.chatDbMigrationTimestamp=parseInt(A.chatDbMigrationTimestamp,10):typeof A.chatDbMigrationTimestamp=="number"?t.chatDbMigrationTimestamp=A.chatDbMigrationTimestamp:typeof A.chatDbMigrationTimestamp=="object"&&(t.chatDbMigrationTimestamp=new I.LongBits(A.chatDbMigrationTimestamp.low>>>0,A.chatDbMigrationTimestamp.high>>>0).toNumber(!0))),t},i.toObject=function(A,t){t||(t={});var s={};return A.chatDbMigrationTimestamp!=null&&A.hasOwnProperty("chatDbMigrationTimestamp")&&(typeof A.chatDbMigrationTimestamp=="number"?s.chatDbMigrationTimestamp=t.longs===String?String(A.chatDbMigrationTimestamp):A.chatDbMigrationTimestamp:s.chatDbMigrationTimestamp=t.longs===String?re(A.chatDbMigrationTimestamp,!0):t.longs===Number?ae(A.chatDbMigrationTimestamp,!0):A.chatDbMigrationTimestamp,t.oneofs&&(s._chatDbMigrationTimestamp="chatDbMigrationTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.LIDMigration"},i})(),r.MemberNameTagPrimarySupport=(function(){let i={},e=Object.create(i);return e[i[0]="DISABLED"]=0,e[i[1]="RECEIVER_ENABLED"]=1,e[i[2]="SENDER_ENABLED"]=2,e})(),r.UserHasAvatar=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.userHasAvatar=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.DeviceCapabilities.UserHasAvatar)return A;var t=new E.proto.DeviceCapabilities.UserHasAvatar;return A.userHasAvatar!=null&&(t.userHasAvatar=!!A.userHasAvatar),t},i.toObject=function(A,t){t||(t={});var s={};return A.userHasAvatar!=null&&A.hasOwnProperty("userHasAvatar")&&(s.userHasAvatar=A.userHasAvatar,t.oneofs&&(s._userHasAvatar="userHasAvatar")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.UserHasAvatar"},i})(),r})(),n.DeviceConsistencyCodeMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.generation=e.uint32();break}case 2:{s.signature=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.DeviceConsistencyCodeMessage)return e;var a=new E.proto.DeviceConsistencyCodeMessage;return e.generation!=null&&(a.generation=e.generation>>>0),e.signature!=null&&(typeof e.signature=="string"?I.base64.decode(e.signature,a.signature=I.newBuffer(I.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),a},r.toObject=function(e,a){a||(a={});var A={};return e.generation!=null&&e.hasOwnProperty("generation")&&(A.generation=e.generation,a.oneofs&&(A._generation="generation")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?I.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceConsistencyCodeMessage"},r})(),n.DeviceListMetadata=(function(){function r(i){if(this.senderKeyIndexes=[],this.recipientKeyIndexes=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.senderKeyHash=e.bytes();break}case 2:{s.senderTimestamp=e.uint64();break}case 3:{if(s.senderKeyIndexes&&s.senderKeyIndexes.length||(s.senderKeyIndexes=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos=0&&(a.senderKeyHash=e.senderKeyHash)),e.senderTimestamp!=null&&(I.Long?(a.senderTimestamp=I.Long.fromValue(e.senderTimestamp)).unsigned=!0:typeof e.senderTimestamp=="string"?a.senderTimestamp=parseInt(e.senderTimestamp,10):typeof e.senderTimestamp=="number"?a.senderTimestamp=e.senderTimestamp:typeof e.senderTimestamp=="object"&&(a.senderTimestamp=new I.LongBits(e.senderTimestamp.low>>>0,e.senderTimestamp.high>>>0).toNumber(!0))),e.senderKeyIndexes){if(!Array.isArray(e.senderKeyIndexes))throw TypeError(".proto.DeviceListMetadata.senderKeyIndexes: array expected");a.senderKeyIndexes=[];for(var A=0;A>>0}switch(e.senderAccountType){default:if(typeof e.senderAccountType=="number"){a.senderAccountType=e.senderAccountType;break}break;case"E2EE":case 0:a.senderAccountType=0;break;case"HOSTED":case 1:a.senderAccountType=1;break}switch(e.receiverAccountType){default:if(typeof e.receiverAccountType=="number"){a.receiverAccountType=e.receiverAccountType;break}break;case"E2EE":case 0:a.receiverAccountType=0;break;case"HOSTED":case 1:a.receiverAccountType=1;break}if(e.recipientKeyHash!=null&&(typeof e.recipientKeyHash=="string"?I.base64.decode(e.recipientKeyHash,a.recipientKeyHash=I.newBuffer(I.base64.length(e.recipientKeyHash)),0):e.recipientKeyHash.length>=0&&(a.recipientKeyHash=e.recipientKeyHash)),e.recipientTimestamp!=null&&(I.Long?(a.recipientTimestamp=I.Long.fromValue(e.recipientTimestamp)).unsigned=!0:typeof e.recipientTimestamp=="string"?a.recipientTimestamp=parseInt(e.recipientTimestamp,10):typeof e.recipientTimestamp=="number"?a.recipientTimestamp=e.recipientTimestamp:typeof e.recipientTimestamp=="object"&&(a.recipientTimestamp=new I.LongBits(e.recipientTimestamp.low>>>0,e.recipientTimestamp.high>>>0).toNumber(!0))),e.recipientKeyIndexes){if(!Array.isArray(e.recipientKeyIndexes))throw TypeError(".proto.DeviceListMetadata.recipientKeyIndexes: array expected");a.recipientKeyIndexes=[];for(var A=0;A>>0}return a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.senderKeyIndexes=[],A.recipientKeyIndexes=[]),e.senderKeyHash!=null&&e.hasOwnProperty("senderKeyHash")&&(A.senderKeyHash=a.bytes===String?I.base64.encode(e.senderKeyHash,0,e.senderKeyHash.length):a.bytes===Array?Array.prototype.slice.call(e.senderKeyHash):e.senderKeyHash,a.oneofs&&(A._senderKeyHash="senderKeyHash")),e.senderTimestamp!=null&&e.hasOwnProperty("senderTimestamp")&&(typeof e.senderTimestamp=="number"?A.senderTimestamp=a.longs===String?String(e.senderTimestamp):e.senderTimestamp:A.senderTimestamp=a.longs===String?re(e.senderTimestamp,!0):a.longs===Number?ae(e.senderTimestamp,!0):e.senderTimestamp,a.oneofs&&(A._senderTimestamp="senderTimestamp")),e.senderKeyIndexes&&e.senderKeyIndexes.length){A.senderKeyIndexes=[];for(var t=0;t>>3){case 1:{s.os=e.string();break}case 2:{s.version=E.proto.DeviceProps.AppVersion.decode(e,e.uint32());break}case 3:{s.platformType=e.int32();break}case 4:{s.requireFullSync=e.bool();break}case 5:{s.historySyncConfig=E.proto.DeviceProps.HistorySyncConfig.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.DeviceProps)return e;var a=new E.proto.DeviceProps;if(e.os!=null&&(a.os=String(e.os)),e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.DeviceProps.version: object expected");a.version=E.proto.DeviceProps.AppVersion.fromObject(e.version)}switch(e.platformType){default:if(typeof e.platformType=="number"){a.platformType=e.platformType;break}break;case"UNKNOWN":case 0:a.platformType=0;break;case"CHROME":case 1:a.platformType=1;break;case"FIREFOX":case 2:a.platformType=2;break;case"IE":case 3:a.platformType=3;break;case"OPERA":case 4:a.platformType=4;break;case"SAFARI":case 5:a.platformType=5;break;case"EDGE":case 6:a.platformType=6;break;case"DESKTOP":case 7:a.platformType=7;break;case"IPAD":case 8:a.platformType=8;break;case"ANDROID_TABLET":case 9:a.platformType=9;break;case"OHANA":case 10:a.platformType=10;break;case"ALOHA":case 11:a.platformType=11;break;case"CATALINA":case 12:a.platformType=12;break;case"TCL_TV":case 13:a.platformType=13;break;case"IOS_PHONE":case 14:a.platformType=14;break;case"IOS_CATALYST":case 15:a.platformType=15;break;case"ANDROID_PHONE":case 16:a.platformType=16;break;case"ANDROID_AMBIGUOUS":case 17:a.platformType=17;break;case"WEAR_OS":case 18:a.platformType=18;break;case"AR_WRIST":case 19:a.platformType=19;break;case"AR_DEVICE":case 20:a.platformType=20;break;case"UWP":case 21:a.platformType=21;break;case"VR":case 22:a.platformType=22;break;case"CLOUD_API":case 23:a.platformType=23;break;case"SMARTGLASSES":case 24:a.platformType=24;break}if(e.requireFullSync!=null&&(a.requireFullSync=!!e.requireFullSync),e.historySyncConfig!=null){if(typeof e.historySyncConfig!="object")throw TypeError(".proto.DeviceProps.historySyncConfig: object expected");a.historySyncConfig=E.proto.DeviceProps.HistorySyncConfig.fromObject(e.historySyncConfig)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.os!=null&&e.hasOwnProperty("os")&&(A.os=e.os,a.oneofs&&(A._os="os")),e.version!=null&&e.hasOwnProperty("version")&&(A.version=E.proto.DeviceProps.AppVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.platformType!=null&&e.hasOwnProperty("platformType")&&(A.platformType=a.enums===String?E.proto.DeviceProps.PlatformType[e.platformType]===void 0?e.platformType:E.proto.DeviceProps.PlatformType[e.platformType]:e.platformType,a.oneofs&&(A._platformType="platformType")),e.requireFullSync!=null&&e.hasOwnProperty("requireFullSync")&&(A.requireFullSync=e.requireFullSync,a.oneofs&&(A._requireFullSync="requireFullSync")),e.historySyncConfig!=null&&e.hasOwnProperty("historySyncConfig")&&(A.historySyncConfig=E.proto.DeviceProps.HistorySyncConfig.toObject(e.historySyncConfig,a),a.oneofs&&(A._historySyncConfig="historySyncConfig")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceProps"},r.AppVersion=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.primary=A.uint32();break}case 2:{c.secondary=A.uint32();break}case 3:{c.tertiary=A.uint32();break}case 4:{c.quaternary=A.uint32();break}case 5:{c.quinary=A.uint32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.DeviceProps.AppVersion)return A;var t=new E.proto.DeviceProps.AppVersion;return A.primary!=null&&(t.primary=A.primary>>>0),A.secondary!=null&&(t.secondary=A.secondary>>>0),A.tertiary!=null&&(t.tertiary=A.tertiary>>>0),A.quaternary!=null&&(t.quaternary=A.quaternary>>>0),A.quinary!=null&&(t.quinary=A.quinary>>>0),t},i.toObject=function(A,t){t||(t={});var s={};return A.primary!=null&&A.hasOwnProperty("primary")&&(s.primary=A.primary,t.oneofs&&(s._primary="primary")),A.secondary!=null&&A.hasOwnProperty("secondary")&&(s.secondary=A.secondary,t.oneofs&&(s._secondary="secondary")),A.tertiary!=null&&A.hasOwnProperty("tertiary")&&(s.tertiary=A.tertiary,t.oneofs&&(s._tertiary="tertiary")),A.quaternary!=null&&A.hasOwnProperty("quaternary")&&(s.quaternary=A.quaternary,t.oneofs&&(s._quaternary="quaternary")),A.quinary!=null&&A.hasOwnProperty("quinary")&&(s.quinary=A.quinary,t.oneofs&&(s._quinary="quinary")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceProps.AppVersion"},i})(),r.HistorySyncConfig=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.fullSyncDaysLimit=A.uint32();break}case 2:{c.fullSyncSizeMbLimit=A.uint32();break}case 3:{c.storageQuotaMb=A.uint32();break}case 4:{c.inlineInitialPayloadInE2EeMsg=A.bool();break}case 5:{c.recentSyncDaysLimit=A.uint32();break}case 6:{c.supportCallLogHistory=A.bool();break}case 7:{c.supportBotUserAgentChatHistory=A.bool();break}case 8:{c.supportCagReactionsAndPolls=A.bool();break}case 9:{c.supportBizHostedMsg=A.bool();break}case 10:{c.supportRecentSyncChunkMessageCountTuning=A.bool();break}case 11:{c.supportHostedGroupMsg=A.bool();break}case 12:{c.supportFbidBotChatHistory=A.bool();break}case 13:{c.supportAddOnHistorySyncMigration=A.bool();break}case 14:{c.supportMessageAssociation=A.bool();break}case 15:{c.supportGroupHistory=A.bool();break}case 16:{c.onDemandReady=A.bool();break}case 17:{c.supportGuestChat=A.bool();break}case 18:{c.completeOnDemandReady=A.bool();break}case 19:{c.thumbnailSyncDaysLimit=A.uint32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.DeviceProps.HistorySyncConfig)return A;var t=new E.proto.DeviceProps.HistorySyncConfig;return A.fullSyncDaysLimit!=null&&(t.fullSyncDaysLimit=A.fullSyncDaysLimit>>>0),A.fullSyncSizeMbLimit!=null&&(t.fullSyncSizeMbLimit=A.fullSyncSizeMbLimit>>>0),A.storageQuotaMb!=null&&(t.storageQuotaMb=A.storageQuotaMb>>>0),A.inlineInitialPayloadInE2EeMsg!=null&&(t.inlineInitialPayloadInE2EeMsg=!!A.inlineInitialPayloadInE2EeMsg),A.recentSyncDaysLimit!=null&&(t.recentSyncDaysLimit=A.recentSyncDaysLimit>>>0),A.supportCallLogHistory!=null&&(t.supportCallLogHistory=!!A.supportCallLogHistory),A.supportBotUserAgentChatHistory!=null&&(t.supportBotUserAgentChatHistory=!!A.supportBotUserAgentChatHistory),A.supportCagReactionsAndPolls!=null&&(t.supportCagReactionsAndPolls=!!A.supportCagReactionsAndPolls),A.supportBizHostedMsg!=null&&(t.supportBizHostedMsg=!!A.supportBizHostedMsg),A.supportRecentSyncChunkMessageCountTuning!=null&&(t.supportRecentSyncChunkMessageCountTuning=!!A.supportRecentSyncChunkMessageCountTuning),A.supportHostedGroupMsg!=null&&(t.supportHostedGroupMsg=!!A.supportHostedGroupMsg),A.supportFbidBotChatHistory!=null&&(t.supportFbidBotChatHistory=!!A.supportFbidBotChatHistory),A.supportAddOnHistorySyncMigration!=null&&(t.supportAddOnHistorySyncMigration=!!A.supportAddOnHistorySyncMigration),A.supportMessageAssociation!=null&&(t.supportMessageAssociation=!!A.supportMessageAssociation),A.supportGroupHistory!=null&&(t.supportGroupHistory=!!A.supportGroupHistory),A.onDemandReady!=null&&(t.onDemandReady=!!A.onDemandReady),A.supportGuestChat!=null&&(t.supportGuestChat=!!A.supportGuestChat),A.completeOnDemandReady!=null&&(t.completeOnDemandReady=!!A.completeOnDemandReady),A.thumbnailSyncDaysLimit!=null&&(t.thumbnailSyncDaysLimit=A.thumbnailSyncDaysLimit>>>0),t},i.toObject=function(A,t){t||(t={});var s={};return A.fullSyncDaysLimit!=null&&A.hasOwnProperty("fullSyncDaysLimit")&&(s.fullSyncDaysLimit=A.fullSyncDaysLimit,t.oneofs&&(s._fullSyncDaysLimit="fullSyncDaysLimit")),A.fullSyncSizeMbLimit!=null&&A.hasOwnProperty("fullSyncSizeMbLimit")&&(s.fullSyncSizeMbLimit=A.fullSyncSizeMbLimit,t.oneofs&&(s._fullSyncSizeMbLimit="fullSyncSizeMbLimit")),A.storageQuotaMb!=null&&A.hasOwnProperty("storageQuotaMb")&&(s.storageQuotaMb=A.storageQuotaMb,t.oneofs&&(s._storageQuotaMb="storageQuotaMb")),A.inlineInitialPayloadInE2EeMsg!=null&&A.hasOwnProperty("inlineInitialPayloadInE2EeMsg")&&(s.inlineInitialPayloadInE2EeMsg=A.inlineInitialPayloadInE2EeMsg,t.oneofs&&(s._inlineInitialPayloadInE2EeMsg="inlineInitialPayloadInE2EeMsg")),A.recentSyncDaysLimit!=null&&A.hasOwnProperty("recentSyncDaysLimit")&&(s.recentSyncDaysLimit=A.recentSyncDaysLimit,t.oneofs&&(s._recentSyncDaysLimit="recentSyncDaysLimit")),A.supportCallLogHistory!=null&&A.hasOwnProperty("supportCallLogHistory")&&(s.supportCallLogHistory=A.supportCallLogHistory,t.oneofs&&(s._supportCallLogHistory="supportCallLogHistory")),A.supportBotUserAgentChatHistory!=null&&A.hasOwnProperty("supportBotUserAgentChatHistory")&&(s.supportBotUserAgentChatHistory=A.supportBotUserAgentChatHistory,t.oneofs&&(s._supportBotUserAgentChatHistory="supportBotUserAgentChatHistory")),A.supportCagReactionsAndPolls!=null&&A.hasOwnProperty("supportCagReactionsAndPolls")&&(s.supportCagReactionsAndPolls=A.supportCagReactionsAndPolls,t.oneofs&&(s._supportCagReactionsAndPolls="supportCagReactionsAndPolls")),A.supportBizHostedMsg!=null&&A.hasOwnProperty("supportBizHostedMsg")&&(s.supportBizHostedMsg=A.supportBizHostedMsg,t.oneofs&&(s._supportBizHostedMsg="supportBizHostedMsg")),A.supportRecentSyncChunkMessageCountTuning!=null&&A.hasOwnProperty("supportRecentSyncChunkMessageCountTuning")&&(s.supportRecentSyncChunkMessageCountTuning=A.supportRecentSyncChunkMessageCountTuning,t.oneofs&&(s._supportRecentSyncChunkMessageCountTuning="supportRecentSyncChunkMessageCountTuning")),A.supportHostedGroupMsg!=null&&A.hasOwnProperty("supportHostedGroupMsg")&&(s.supportHostedGroupMsg=A.supportHostedGroupMsg,t.oneofs&&(s._supportHostedGroupMsg="supportHostedGroupMsg")),A.supportFbidBotChatHistory!=null&&A.hasOwnProperty("supportFbidBotChatHistory")&&(s.supportFbidBotChatHistory=A.supportFbidBotChatHistory,t.oneofs&&(s._supportFbidBotChatHistory="supportFbidBotChatHistory")),A.supportAddOnHistorySyncMigration!=null&&A.hasOwnProperty("supportAddOnHistorySyncMigration")&&(s.supportAddOnHistorySyncMigration=A.supportAddOnHistorySyncMigration,t.oneofs&&(s._supportAddOnHistorySyncMigration="supportAddOnHistorySyncMigration")),A.supportMessageAssociation!=null&&A.hasOwnProperty("supportMessageAssociation")&&(s.supportMessageAssociation=A.supportMessageAssociation,t.oneofs&&(s._supportMessageAssociation="supportMessageAssociation")),A.supportGroupHistory!=null&&A.hasOwnProperty("supportGroupHistory")&&(s.supportGroupHistory=A.supportGroupHistory,t.oneofs&&(s._supportGroupHistory="supportGroupHistory")),A.onDemandReady!=null&&A.hasOwnProperty("onDemandReady")&&(s.onDemandReady=A.onDemandReady,t.oneofs&&(s._onDemandReady="onDemandReady")),A.supportGuestChat!=null&&A.hasOwnProperty("supportGuestChat")&&(s.supportGuestChat=A.supportGuestChat,t.oneofs&&(s._supportGuestChat="supportGuestChat")),A.completeOnDemandReady!=null&&A.hasOwnProperty("completeOnDemandReady")&&(s.completeOnDemandReady=A.completeOnDemandReady,t.oneofs&&(s._completeOnDemandReady="completeOnDemandReady")),A.thumbnailSyncDaysLimit!=null&&A.hasOwnProperty("thumbnailSyncDaysLimit")&&(s.thumbnailSyncDaysLimit=A.thumbnailSyncDaysLimit,t.oneofs&&(s._thumbnailSyncDaysLimit="thumbnailSyncDaysLimit")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceProps.HistorySyncConfig"},i})(),r.PlatformType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHROME"]=1,e[i[2]="FIREFOX"]=2,e[i[3]="IE"]=3,e[i[4]="OPERA"]=4,e[i[5]="SAFARI"]=5,e[i[6]="EDGE"]=6,e[i[7]="DESKTOP"]=7,e[i[8]="IPAD"]=8,e[i[9]="ANDROID_TABLET"]=9,e[i[10]="OHANA"]=10,e[i[11]="ALOHA"]=11,e[i[12]="CATALINA"]=12,e[i[13]="TCL_TV"]=13,e[i[14]="IOS_PHONE"]=14,e[i[15]="IOS_CATALYST"]=15,e[i[16]="ANDROID_PHONE"]=16,e[i[17]="ANDROID_AMBIGUOUS"]=17,e[i[18]="WEAR_OS"]=18,e[i[19]="AR_WRIST"]=19,e[i[20]="AR_DEVICE"]=20,e[i[21]="UWP"]=21,e[i[22]="VR"]=22,e[i[23]="CLOUD_API"]=23,e[i[24]="SMARTGLASSES"]=24,e})(),r})(),n.DisappearingMode=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.initiator=e.int32();break}case 2:{s.trigger=e.int32();break}case 3:{s.initiatorDeviceJid=e.string();break}case 4:{s.initiatedByMe=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.DisappearingMode)return e;var a=new E.proto.DisappearingMode;switch(e.initiator){default:if(typeof e.initiator=="number"){a.initiator=e.initiator;break}break;case"CHANGED_IN_CHAT":case 0:a.initiator=0;break;case"INITIATED_BY_ME":case 1:a.initiator=1;break;case"INITIATED_BY_OTHER":case 2:a.initiator=2;break;case"BIZ_UPGRADE_FB_HOSTING":case 3:a.initiator=3;break}switch(e.trigger){default:if(typeof e.trigger=="number"){a.trigger=e.trigger;break}break;case"UNKNOWN":case 0:a.trigger=0;break;case"CHAT_SETTING":case 1:a.trigger=1;break;case"ACCOUNT_SETTING":case 2:a.trigger=2;break;case"BULK_CHANGE":case 3:a.trigger=3;break;case"BIZ_SUPPORTS_FB_HOSTING":case 4:a.trigger=4;break;case"UNKNOWN_GROUPS":case 5:a.trigger=5;break}return e.initiatorDeviceJid!=null&&(a.initiatorDeviceJid=String(e.initiatorDeviceJid)),e.initiatedByMe!=null&&(a.initiatedByMe=!!e.initiatedByMe),a},r.toObject=function(e,a){a||(a={});var A={};return e.initiator!=null&&e.hasOwnProperty("initiator")&&(A.initiator=a.enums===String?E.proto.DisappearingMode.Initiator[e.initiator]===void 0?e.initiator:E.proto.DisappearingMode.Initiator[e.initiator]:e.initiator,a.oneofs&&(A._initiator="initiator")),e.trigger!=null&&e.hasOwnProperty("trigger")&&(A.trigger=a.enums===String?E.proto.DisappearingMode.Trigger[e.trigger]===void 0?e.trigger:E.proto.DisappearingMode.Trigger[e.trigger]:e.trigger,a.oneofs&&(A._trigger="trigger")),e.initiatorDeviceJid!=null&&e.hasOwnProperty("initiatorDeviceJid")&&(A.initiatorDeviceJid=e.initiatorDeviceJid,a.oneofs&&(A._initiatorDeviceJid="initiatorDeviceJid")),e.initiatedByMe!=null&&e.hasOwnProperty("initiatedByMe")&&(A.initiatedByMe=e.initiatedByMe,a.oneofs&&(A._initiatedByMe="initiatedByMe")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DisappearingMode"},r.Initiator=(function(){let i={},e=Object.create(i);return e[i[0]="CHANGED_IN_CHAT"]=0,e[i[1]="INITIATED_BY_ME"]=1,e[i[2]="INITIATED_BY_OTHER"]=2,e[i[3]="BIZ_UPGRADE_FB_HOSTING"]=3,e})(),r.Trigger=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT_SETTING"]=1,e[i[2]="ACCOUNT_SETTING"]=2,e[i[3]="BULK_CHANGE"]=3,e[i[4]="BIZ_SUPPORTS_FB_HOSTING"]=4,e[i[5]="UNKNOWN_GROUPS"]=5,e})(),r})(),n.EmbeddedContent=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.embeddedMessage=E.proto.EmbeddedMessage.decode(e,e.uint32());break}case 2:{s.embeddedMusic=E.proto.EmbeddedMusic.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.EmbeddedContent)return e;var a=new E.proto.EmbeddedContent;if(e.embeddedMessage!=null){if(typeof e.embeddedMessage!="object")throw TypeError(".proto.EmbeddedContent.embeddedMessage: object expected");a.embeddedMessage=E.proto.EmbeddedMessage.fromObject(e.embeddedMessage)}if(e.embeddedMusic!=null){if(typeof e.embeddedMusic!="object")throw TypeError(".proto.EmbeddedContent.embeddedMusic: object expected");a.embeddedMusic=E.proto.EmbeddedMusic.fromObject(e.embeddedMusic)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.embeddedMessage!=null&&e.hasOwnProperty("embeddedMessage")&&(A.embeddedMessage=E.proto.EmbeddedMessage.toObject(e.embeddedMessage,a),a.oneofs&&(A.content="embeddedMessage")),e.embeddedMusic!=null&&e.hasOwnProperty("embeddedMusic")&&(A.embeddedMusic=E.proto.EmbeddedMusic.toObject(e.embeddedMusic,a),a.oneofs&&(A.content="embeddedMusic")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedContent"},r})(),n.EmbeddedMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.message=E.proto.Message.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.EmbeddedMessage)return e;var a=new E.proto.EmbeddedMessage;if(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.EmbeddedMessage.message: object expected");a.message=E.proto.Message.fromObject(e.message)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=E.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedMessage"},r})(),n.EmbeddedMusic=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.musicContentMediaId=e.string();break}case 2:{s.songId=e.string();break}case 3:{s.author=e.string();break}case 4:{s.title=e.string();break}case 5:{s.artworkDirectPath=e.string();break}case 6:{s.artworkSha256=e.bytes();break}case 7:{s.artworkEncSha256=e.bytes();break}case 8:{s.artistAttribution=e.string();break}case 9:{s.countryBlocklist=e.bytes();break}case 10:{s.isExplicit=e.bool();break}case 11:{s.artworkMediaKey=e.bytes();break}case 12:{s.musicSongStartTimeInMs=e.int64();break}case 13:{s.derivedContentStartTimeInMs=e.int64();break}case 14:{s.overlapDurationInMs=e.int64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.EmbeddedMusic)return e;var a=new E.proto.EmbeddedMusic;return e.musicContentMediaId!=null&&(a.musicContentMediaId=String(e.musicContentMediaId)),e.songId!=null&&(a.songId=String(e.songId)),e.author!=null&&(a.author=String(e.author)),e.title!=null&&(a.title=String(e.title)),e.artworkDirectPath!=null&&(a.artworkDirectPath=String(e.artworkDirectPath)),e.artworkSha256!=null&&(typeof e.artworkSha256=="string"?I.base64.decode(e.artworkSha256,a.artworkSha256=I.newBuffer(I.base64.length(e.artworkSha256)),0):e.artworkSha256.length>=0&&(a.artworkSha256=e.artworkSha256)),e.artworkEncSha256!=null&&(typeof e.artworkEncSha256=="string"?I.base64.decode(e.artworkEncSha256,a.artworkEncSha256=I.newBuffer(I.base64.length(e.artworkEncSha256)),0):e.artworkEncSha256.length>=0&&(a.artworkEncSha256=e.artworkEncSha256)),e.artistAttribution!=null&&(a.artistAttribution=String(e.artistAttribution)),e.countryBlocklist!=null&&(typeof e.countryBlocklist=="string"?I.base64.decode(e.countryBlocklist,a.countryBlocklist=I.newBuffer(I.base64.length(e.countryBlocklist)),0):e.countryBlocklist.length>=0&&(a.countryBlocklist=e.countryBlocklist)),e.isExplicit!=null&&(a.isExplicit=!!e.isExplicit),e.artworkMediaKey!=null&&(typeof e.artworkMediaKey=="string"?I.base64.decode(e.artworkMediaKey,a.artworkMediaKey=I.newBuffer(I.base64.length(e.artworkMediaKey)),0):e.artworkMediaKey.length>=0&&(a.artworkMediaKey=e.artworkMediaKey)),e.musicSongStartTimeInMs!=null&&(I.Long?(a.musicSongStartTimeInMs=I.Long.fromValue(e.musicSongStartTimeInMs)).unsigned=!1:typeof e.musicSongStartTimeInMs=="string"?a.musicSongStartTimeInMs=parseInt(e.musicSongStartTimeInMs,10):typeof e.musicSongStartTimeInMs=="number"?a.musicSongStartTimeInMs=e.musicSongStartTimeInMs:typeof e.musicSongStartTimeInMs=="object"&&(a.musicSongStartTimeInMs=new I.LongBits(e.musicSongStartTimeInMs.low>>>0,e.musicSongStartTimeInMs.high>>>0).toNumber())),e.derivedContentStartTimeInMs!=null&&(I.Long?(a.derivedContentStartTimeInMs=I.Long.fromValue(e.derivedContentStartTimeInMs)).unsigned=!1:typeof e.derivedContentStartTimeInMs=="string"?a.derivedContentStartTimeInMs=parseInt(e.derivedContentStartTimeInMs,10):typeof e.derivedContentStartTimeInMs=="number"?a.derivedContentStartTimeInMs=e.derivedContentStartTimeInMs:typeof e.derivedContentStartTimeInMs=="object"&&(a.derivedContentStartTimeInMs=new I.LongBits(e.derivedContentStartTimeInMs.low>>>0,e.derivedContentStartTimeInMs.high>>>0).toNumber())),e.overlapDurationInMs!=null&&(I.Long?(a.overlapDurationInMs=I.Long.fromValue(e.overlapDurationInMs)).unsigned=!1:typeof e.overlapDurationInMs=="string"?a.overlapDurationInMs=parseInt(e.overlapDurationInMs,10):typeof e.overlapDurationInMs=="number"?a.overlapDurationInMs=e.overlapDurationInMs:typeof e.overlapDurationInMs=="object"&&(a.overlapDurationInMs=new I.LongBits(e.overlapDurationInMs.low>>>0,e.overlapDurationInMs.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.musicContentMediaId!=null&&e.hasOwnProperty("musicContentMediaId")&&(A.musicContentMediaId=e.musicContentMediaId,a.oneofs&&(A._musicContentMediaId="musicContentMediaId")),e.songId!=null&&e.hasOwnProperty("songId")&&(A.songId=e.songId,a.oneofs&&(A._songId="songId")),e.author!=null&&e.hasOwnProperty("author")&&(A.author=e.author,a.oneofs&&(A._author="author")),e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.artworkDirectPath!=null&&e.hasOwnProperty("artworkDirectPath")&&(A.artworkDirectPath=e.artworkDirectPath,a.oneofs&&(A._artworkDirectPath="artworkDirectPath")),e.artworkSha256!=null&&e.hasOwnProperty("artworkSha256")&&(A.artworkSha256=a.bytes===String?I.base64.encode(e.artworkSha256,0,e.artworkSha256.length):a.bytes===Array?Array.prototype.slice.call(e.artworkSha256):e.artworkSha256,a.oneofs&&(A._artworkSha256="artworkSha256")),e.artworkEncSha256!=null&&e.hasOwnProperty("artworkEncSha256")&&(A.artworkEncSha256=a.bytes===String?I.base64.encode(e.artworkEncSha256,0,e.artworkEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.artworkEncSha256):e.artworkEncSha256,a.oneofs&&(A._artworkEncSha256="artworkEncSha256")),e.artistAttribution!=null&&e.hasOwnProperty("artistAttribution")&&(A.artistAttribution=e.artistAttribution,a.oneofs&&(A._artistAttribution="artistAttribution")),e.countryBlocklist!=null&&e.hasOwnProperty("countryBlocklist")&&(A.countryBlocklist=a.bytes===String?I.base64.encode(e.countryBlocklist,0,e.countryBlocklist.length):a.bytes===Array?Array.prototype.slice.call(e.countryBlocklist):e.countryBlocklist,a.oneofs&&(A._countryBlocklist="countryBlocklist")),e.isExplicit!=null&&e.hasOwnProperty("isExplicit")&&(A.isExplicit=e.isExplicit,a.oneofs&&(A._isExplicit="isExplicit")),e.artworkMediaKey!=null&&e.hasOwnProperty("artworkMediaKey")&&(A.artworkMediaKey=a.bytes===String?I.base64.encode(e.artworkMediaKey,0,e.artworkMediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.artworkMediaKey):e.artworkMediaKey,a.oneofs&&(A._artworkMediaKey="artworkMediaKey")),e.musicSongStartTimeInMs!=null&&e.hasOwnProperty("musicSongStartTimeInMs")&&(typeof e.musicSongStartTimeInMs=="number"?A.musicSongStartTimeInMs=a.longs===String?String(e.musicSongStartTimeInMs):e.musicSongStartTimeInMs:A.musicSongStartTimeInMs=a.longs===String?re(e.musicSongStartTimeInMs):a.longs===Number?ae(e.musicSongStartTimeInMs):e.musicSongStartTimeInMs,a.oneofs&&(A._musicSongStartTimeInMs="musicSongStartTimeInMs")),e.derivedContentStartTimeInMs!=null&&e.hasOwnProperty("derivedContentStartTimeInMs")&&(typeof e.derivedContentStartTimeInMs=="number"?A.derivedContentStartTimeInMs=a.longs===String?String(e.derivedContentStartTimeInMs):e.derivedContentStartTimeInMs:A.derivedContentStartTimeInMs=a.longs===String?re(e.derivedContentStartTimeInMs):a.longs===Number?ae(e.derivedContentStartTimeInMs):e.derivedContentStartTimeInMs,a.oneofs&&(A._derivedContentStartTimeInMs="derivedContentStartTimeInMs")),e.overlapDurationInMs!=null&&e.hasOwnProperty("overlapDurationInMs")&&(typeof e.overlapDurationInMs=="number"?A.overlapDurationInMs=a.longs===String?String(e.overlapDurationInMs):e.overlapDurationInMs:A.overlapDurationInMs=a.longs===String?re(e.overlapDurationInMs):a.longs===Number?ae(e.overlapDurationInMs):e.overlapDurationInMs,a.oneofs&&(A._overlapDurationInMs="overlapDurationInMs")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedMusic"},r})(),n.EncryptedPairingRequest=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encryptedPayload=e.bytes();break}case 2:{s.iv=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.EncryptedPairingRequest)return e;var a=new E.proto.EncryptedPairingRequest;return e.encryptedPayload!=null&&(typeof e.encryptedPayload=="string"?I.base64.decode(e.encryptedPayload,a.encryptedPayload=I.newBuffer(I.base64.length(e.encryptedPayload)),0):e.encryptedPayload.length>=0&&(a.encryptedPayload=e.encryptedPayload)),e.iv!=null&&(typeof e.iv=="string"?I.base64.decode(e.iv,a.iv=I.newBuffer(I.base64.length(e.iv)),0):e.iv.length>=0&&(a.iv=e.iv)),a},r.toObject=function(e,a){a||(a={});var A={};return e.encryptedPayload!=null&&e.hasOwnProperty("encryptedPayload")&&(A.encryptedPayload=a.bytes===String?I.base64.encode(e.encryptedPayload,0,e.encryptedPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encryptedPayload):e.encryptedPayload,a.oneofs&&(A._encryptedPayload="encryptedPayload")),e.iv!=null&&e.hasOwnProperty("iv")&&(A.iv=a.bytes===String?I.base64.encode(e.iv,0,e.iv.length):a.bytes===Array?Array.prototype.slice.call(e.iv):e.iv,a.oneofs&&(A._iv="iv")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EncryptedPairingRequest"},r})(),n.EphemeralSetting=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.duration=e.sfixed32();break}case 2:{s.timestamp=e.sfixed64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.EphemeralSetting)return e;var a=new E.proto.EphemeralSetting;return e.duration!=null&&(a.duration=e.duration|0),e.timestamp!=null&&(I.Long?(a.timestamp=I.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new I.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.duration!=null&&e.hasOwnProperty("duration")&&(A.duration=e.duration,a.oneofs&&(A._duration="duration")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?re(e.timestamp):a.longs===Number?ae(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EphemeralSetting"},r})(),n.EventAdditionalMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.isStale=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.EventAdditionalMetadata)return e;var a=new E.proto.EventAdditionalMetadata;return e.isStale!=null&&(a.isStale=!!e.isStale),a},r.toObject=function(e,a){a||(a={});var A={};return e.isStale!=null&&e.hasOwnProperty("isStale")&&(A.isStale=e.isStale,a.oneofs&&(A._isStale="isStale")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EventAdditionalMetadata"},r})(),n.EventResponse=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.eventResponseMessageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.timestampMs=e.int64();break}case 3:{s.eventResponseMessage=E.proto.Message.EventResponseMessage.decode(e,e.uint32());break}case 4:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.EventResponse)return e;var a=new E.proto.EventResponse;if(e.eventResponseMessageKey!=null){if(typeof e.eventResponseMessageKey!="object")throw TypeError(".proto.EventResponse.eventResponseMessageKey: object expected");a.eventResponseMessageKey=E.proto.MessageKey.fromObject(e.eventResponseMessageKey)}if(e.timestampMs!=null&&(I.Long?(a.timestampMs=I.Long.fromValue(e.timestampMs)).unsigned=!1:typeof e.timestampMs=="string"?a.timestampMs=parseInt(e.timestampMs,10):typeof e.timestampMs=="number"?a.timestampMs=e.timestampMs:typeof e.timestampMs=="object"&&(a.timestampMs=new I.LongBits(e.timestampMs.low>>>0,e.timestampMs.high>>>0).toNumber())),e.eventResponseMessage!=null){if(typeof e.eventResponseMessage!="object")throw TypeError(".proto.EventResponse.eventResponseMessage: object expected");a.eventResponseMessage=E.proto.Message.EventResponseMessage.fromObject(e.eventResponseMessage)}return e.unread!=null&&(a.unread=!!e.unread),a},r.toObject=function(e,a){a||(a={});var A={};return e.eventResponseMessageKey!=null&&e.hasOwnProperty("eventResponseMessageKey")&&(A.eventResponseMessageKey=E.proto.MessageKey.toObject(e.eventResponseMessageKey,a),a.oneofs&&(A._eventResponseMessageKey="eventResponseMessageKey")),e.timestampMs!=null&&e.hasOwnProperty("timestampMs")&&(typeof e.timestampMs=="number"?A.timestampMs=a.longs===String?String(e.timestampMs):e.timestampMs:A.timestampMs=a.longs===String?re(e.timestampMs):a.longs===Number?ae(e.timestampMs):e.timestampMs,a.oneofs&&(A._timestampMs="timestampMs")),e.eventResponseMessage!=null&&e.hasOwnProperty("eventResponseMessage")&&(A.eventResponseMessage=E.proto.Message.EventResponseMessage.toObject(e.eventResponseMessage,a),a.oneofs&&(A._eventResponseMessage="eventResponseMessage")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EventResponse"},r})(),n.ExitCode=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.code=e.uint64();break}case 2:{s.text=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ExitCode)return e;var a=new E.proto.ExitCode;return e.code!=null&&(I.Long?(a.code=I.Long.fromValue(e.code)).unsigned=!0:typeof e.code=="string"?a.code=parseInt(e.code,10):typeof e.code=="number"?a.code=e.code:typeof e.code=="object"&&(a.code=new I.LongBits(e.code.low>>>0,e.code.high>>>0).toNumber(!0))),e.text!=null&&(a.text=String(e.text)),a},r.toObject=function(e,a){a||(a={});var A={};return e.code!=null&&e.hasOwnProperty("code")&&(typeof e.code=="number"?A.code=a.longs===String?String(e.code):e.code:A.code=a.longs===String?re(e.code,!0):a.longs===Number?ae(e.code,!0):e.code,a.oneofs&&(A._code="code")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ExitCode"},r})(),n.ExternalBlobReference=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.mediaKey=e.bytes();break}case 2:{s.directPath=e.string();break}case 3:{s.handle=e.string();break}case 4:{s.fileSizeBytes=e.uint64();break}case 5:{s.fileSha256=e.bytes();break}case 6:{s.fileEncSha256=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ExternalBlobReference)return e;var a=new E.proto.ExternalBlobReference;return e.mediaKey!=null&&(typeof e.mediaKey=="string"?I.base64.decode(e.mediaKey,a.mediaKey=I.newBuffer(I.base64.length(e.mediaKey)),0):e.mediaKey.length>=0&&(a.mediaKey=e.mediaKey)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.handle!=null&&(a.handle=String(e.handle)),e.fileSizeBytes!=null&&(I.Long?(a.fileSizeBytes=I.Long.fromValue(e.fileSizeBytes)).unsigned=!0:typeof e.fileSizeBytes=="string"?a.fileSizeBytes=parseInt(e.fileSizeBytes,10):typeof e.fileSizeBytes=="number"?a.fileSizeBytes=e.fileSizeBytes:typeof e.fileSizeBytes=="object"&&(a.fileSizeBytes=new I.LongBits(e.fileSizeBytes.low>>>0,e.fileSizeBytes.high>>>0).toNumber(!0))),e.fileSha256!=null&&(typeof e.fileSha256=="string"?I.base64.decode(e.fileSha256,a.fileSha256=I.newBuffer(I.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?I.base64.decode(e.fileEncSha256,a.fileEncSha256=I.newBuffer(I.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),a},r.toObject=function(e,a){a||(a={});var A={};return e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=a.bytes===String?I.base64.encode(e.mediaKey,0,e.mediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.mediaKey):e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.handle!=null&&e.hasOwnProperty("handle")&&(A.handle=e.handle,a.oneofs&&(A._handle="handle")),e.fileSizeBytes!=null&&e.hasOwnProperty("fileSizeBytes")&&(typeof e.fileSizeBytes=="number"?A.fileSizeBytes=a.longs===String?String(e.fileSizeBytes):e.fileSizeBytes:A.fileSizeBytes=a.longs===String?re(e.fileSizeBytes,!0):a.longs===Number?ae(e.fileSizeBytes,!0):e.fileSizeBytes,a.oneofs&&(A._fileSizeBytes="fileSizeBytes")),e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=a.bytes===String?I.base64.encode(e.fileSha256,0,e.fileSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileSha256):e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?I.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ExternalBlobReference"},r})(),n.Field=(function(){function r(i){if(this.subfield={},i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.minVersion=e.uint32();break}case 2:{s.maxVersion=e.uint32();break}case 3:{s.notReportableMinVersion=e.uint32();break}case 4:{s.isMessage=e.bool();break}case 5:{s.subfield===I.emptyObject&&(s.subfield={});var p=e.uint32()+e.pos;for(g=0,c=null;e.pos>>3){case 1:g=e.uint32();break;case 2:c=E.proto.Field.decode(e,e.uint32());break;default:e.skipType(B&7);break}}s.subfield[g]=c;break}default:e.skipType(l&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Field)return e;var a=new E.proto.Field;if(e.minVersion!=null&&(a.minVersion=e.minVersion>>>0),e.maxVersion!=null&&(a.maxVersion=e.maxVersion>>>0),e.notReportableMinVersion!=null&&(a.notReportableMinVersion=e.notReportableMinVersion>>>0),e.isMessage!=null&&(a.isMessage=!!e.isMessage),e.subfield){if(typeof e.subfield!="object")throw TypeError(".proto.Field.subfield: object expected");a.subfield={};for(var A=Object.keys(e.subfield),t=0;t>>3){case 1:{s.botName=e.string();break}case 2:{s.botJid=e.string();break}case 3:{s.creatorName=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ForwardedAIBotMessageInfo)return e;var a=new E.proto.ForwardedAIBotMessageInfo;return e.botName!=null&&(a.botName=String(e.botName)),e.botJid!=null&&(a.botJid=String(e.botJid)),e.creatorName!=null&&(a.creatorName=String(e.creatorName)),a},r.toObject=function(e,a){a||(a={});var A={};return e.botName!=null&&e.hasOwnProperty("botName")&&(A.botName=e.botName,a.oneofs&&(A._botName="botName")),e.botJid!=null&&e.hasOwnProperty("botJid")&&(A.botJid=e.botJid,a.oneofs&&(A._botJid="botJid")),e.creatorName!=null&&e.hasOwnProperty("creatorName")&&(A.creatorName=e.creatorName,a.oneofs&&(A._creatorName="creatorName")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ForwardedAIBotMessageInfo"},r})(),n.GlobalSettings=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lightThemeWallpaper=E.proto.WallpaperSettings.decode(e,e.uint32());break}case 2:{s.mediaVisibility=e.int32();break}case 3:{s.darkThemeWallpaper=E.proto.WallpaperSettings.decode(e,e.uint32());break}case 4:{s.autoDownloadWiFi=E.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 5:{s.autoDownloadCellular=E.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 6:{s.autoDownloadRoaming=E.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 7:{s.showIndividualNotificationsPreview=e.bool();break}case 8:{s.showGroupNotificationsPreview=e.bool();break}case 9:{s.disappearingModeDuration=e.int32();break}case 10:{s.disappearingModeTimestamp=e.int64();break}case 11:{s.avatarUserSettings=E.proto.AvatarUserSettings.decode(e,e.uint32());break}case 12:{s.fontSize=e.int32();break}case 13:{s.securityNotifications=e.bool();break}case 14:{s.autoUnarchiveChats=e.bool();break}case 15:{s.videoQualityMode=e.int32();break}case 16:{s.photoQualityMode=e.int32();break}case 17:{s.individualNotificationSettings=E.proto.NotificationSettings.decode(e,e.uint32());break}case 18:{s.groupNotificationSettings=E.proto.NotificationSettings.decode(e,e.uint32());break}case 19:{s.chatLockSettings=E.proto.ChatLockSettings.decode(e,e.uint32());break}case 20:{s.chatDbLidMigrationTimestamp=e.int64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.GlobalSettings)return e;var a=new E.proto.GlobalSettings;if(e.lightThemeWallpaper!=null){if(typeof e.lightThemeWallpaper!="object")throw TypeError(".proto.GlobalSettings.lightThemeWallpaper: object expected");a.lightThemeWallpaper=E.proto.WallpaperSettings.fromObject(e.lightThemeWallpaper)}switch(e.mediaVisibility){default:if(typeof e.mediaVisibility=="number"){a.mediaVisibility=e.mediaVisibility;break}break;case"DEFAULT":case 0:a.mediaVisibility=0;break;case"OFF":case 1:a.mediaVisibility=1;break;case"ON":case 2:a.mediaVisibility=2;break}if(e.darkThemeWallpaper!=null){if(typeof e.darkThemeWallpaper!="object")throw TypeError(".proto.GlobalSettings.darkThemeWallpaper: object expected");a.darkThemeWallpaper=E.proto.WallpaperSettings.fromObject(e.darkThemeWallpaper)}if(e.autoDownloadWiFi!=null){if(typeof e.autoDownloadWiFi!="object")throw TypeError(".proto.GlobalSettings.autoDownloadWiFi: object expected");a.autoDownloadWiFi=E.proto.AutoDownloadSettings.fromObject(e.autoDownloadWiFi)}if(e.autoDownloadCellular!=null){if(typeof e.autoDownloadCellular!="object")throw TypeError(".proto.GlobalSettings.autoDownloadCellular: object expected");a.autoDownloadCellular=E.proto.AutoDownloadSettings.fromObject(e.autoDownloadCellular)}if(e.autoDownloadRoaming!=null){if(typeof e.autoDownloadRoaming!="object")throw TypeError(".proto.GlobalSettings.autoDownloadRoaming: object expected");a.autoDownloadRoaming=E.proto.AutoDownloadSettings.fromObject(e.autoDownloadRoaming)}if(e.showIndividualNotificationsPreview!=null&&(a.showIndividualNotificationsPreview=!!e.showIndividualNotificationsPreview),e.showGroupNotificationsPreview!=null&&(a.showGroupNotificationsPreview=!!e.showGroupNotificationsPreview),e.disappearingModeDuration!=null&&(a.disappearingModeDuration=e.disappearingModeDuration|0),e.disappearingModeTimestamp!=null&&(I.Long?(a.disappearingModeTimestamp=I.Long.fromValue(e.disappearingModeTimestamp)).unsigned=!1:typeof e.disappearingModeTimestamp=="string"?a.disappearingModeTimestamp=parseInt(e.disappearingModeTimestamp,10):typeof e.disappearingModeTimestamp=="number"?a.disappearingModeTimestamp=e.disappearingModeTimestamp:typeof e.disappearingModeTimestamp=="object"&&(a.disappearingModeTimestamp=new I.LongBits(e.disappearingModeTimestamp.low>>>0,e.disappearingModeTimestamp.high>>>0).toNumber())),e.avatarUserSettings!=null){if(typeof e.avatarUserSettings!="object")throw TypeError(".proto.GlobalSettings.avatarUserSettings: object expected");a.avatarUserSettings=E.proto.AvatarUserSettings.fromObject(e.avatarUserSettings)}if(e.fontSize!=null&&(a.fontSize=e.fontSize|0),e.securityNotifications!=null&&(a.securityNotifications=!!e.securityNotifications),e.autoUnarchiveChats!=null&&(a.autoUnarchiveChats=!!e.autoUnarchiveChats),e.videoQualityMode!=null&&(a.videoQualityMode=e.videoQualityMode|0),e.photoQualityMode!=null&&(a.photoQualityMode=e.photoQualityMode|0),e.individualNotificationSettings!=null){if(typeof e.individualNotificationSettings!="object")throw TypeError(".proto.GlobalSettings.individualNotificationSettings: object expected");a.individualNotificationSettings=E.proto.NotificationSettings.fromObject(e.individualNotificationSettings)}if(e.groupNotificationSettings!=null){if(typeof e.groupNotificationSettings!="object")throw TypeError(".proto.GlobalSettings.groupNotificationSettings: object expected");a.groupNotificationSettings=E.proto.NotificationSettings.fromObject(e.groupNotificationSettings)}if(e.chatLockSettings!=null){if(typeof e.chatLockSettings!="object")throw TypeError(".proto.GlobalSettings.chatLockSettings: object expected");a.chatLockSettings=E.proto.ChatLockSettings.fromObject(e.chatLockSettings)}return e.chatDbLidMigrationTimestamp!=null&&(I.Long?(a.chatDbLidMigrationTimestamp=I.Long.fromValue(e.chatDbLidMigrationTimestamp)).unsigned=!1:typeof e.chatDbLidMigrationTimestamp=="string"?a.chatDbLidMigrationTimestamp=parseInt(e.chatDbLidMigrationTimestamp,10):typeof e.chatDbLidMigrationTimestamp=="number"?a.chatDbLidMigrationTimestamp=e.chatDbLidMigrationTimestamp:typeof e.chatDbLidMigrationTimestamp=="object"&&(a.chatDbLidMigrationTimestamp=new I.LongBits(e.chatDbLidMigrationTimestamp.low>>>0,e.chatDbLidMigrationTimestamp.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.lightThemeWallpaper!=null&&e.hasOwnProperty("lightThemeWallpaper")&&(A.lightThemeWallpaper=E.proto.WallpaperSettings.toObject(e.lightThemeWallpaper,a),a.oneofs&&(A._lightThemeWallpaper="lightThemeWallpaper")),e.mediaVisibility!=null&&e.hasOwnProperty("mediaVisibility")&&(A.mediaVisibility=a.enums===String?E.proto.MediaVisibility[e.mediaVisibility]===void 0?e.mediaVisibility:E.proto.MediaVisibility[e.mediaVisibility]:e.mediaVisibility,a.oneofs&&(A._mediaVisibility="mediaVisibility")),e.darkThemeWallpaper!=null&&e.hasOwnProperty("darkThemeWallpaper")&&(A.darkThemeWallpaper=E.proto.WallpaperSettings.toObject(e.darkThemeWallpaper,a),a.oneofs&&(A._darkThemeWallpaper="darkThemeWallpaper")),e.autoDownloadWiFi!=null&&e.hasOwnProperty("autoDownloadWiFi")&&(A.autoDownloadWiFi=E.proto.AutoDownloadSettings.toObject(e.autoDownloadWiFi,a),a.oneofs&&(A._autoDownloadWiFi="autoDownloadWiFi")),e.autoDownloadCellular!=null&&e.hasOwnProperty("autoDownloadCellular")&&(A.autoDownloadCellular=E.proto.AutoDownloadSettings.toObject(e.autoDownloadCellular,a),a.oneofs&&(A._autoDownloadCellular="autoDownloadCellular")),e.autoDownloadRoaming!=null&&e.hasOwnProperty("autoDownloadRoaming")&&(A.autoDownloadRoaming=E.proto.AutoDownloadSettings.toObject(e.autoDownloadRoaming,a),a.oneofs&&(A._autoDownloadRoaming="autoDownloadRoaming")),e.showIndividualNotificationsPreview!=null&&e.hasOwnProperty("showIndividualNotificationsPreview")&&(A.showIndividualNotificationsPreview=e.showIndividualNotificationsPreview,a.oneofs&&(A._showIndividualNotificationsPreview="showIndividualNotificationsPreview")),e.showGroupNotificationsPreview!=null&&e.hasOwnProperty("showGroupNotificationsPreview")&&(A.showGroupNotificationsPreview=e.showGroupNotificationsPreview,a.oneofs&&(A._showGroupNotificationsPreview="showGroupNotificationsPreview")),e.disappearingModeDuration!=null&&e.hasOwnProperty("disappearingModeDuration")&&(A.disappearingModeDuration=e.disappearingModeDuration,a.oneofs&&(A._disappearingModeDuration="disappearingModeDuration")),e.disappearingModeTimestamp!=null&&e.hasOwnProperty("disappearingModeTimestamp")&&(typeof e.disappearingModeTimestamp=="number"?A.disappearingModeTimestamp=a.longs===String?String(e.disappearingModeTimestamp):e.disappearingModeTimestamp:A.disappearingModeTimestamp=a.longs===String?re(e.disappearingModeTimestamp):a.longs===Number?ae(e.disappearingModeTimestamp):e.disappearingModeTimestamp,a.oneofs&&(A._disappearingModeTimestamp="disappearingModeTimestamp")),e.avatarUserSettings!=null&&e.hasOwnProperty("avatarUserSettings")&&(A.avatarUserSettings=E.proto.AvatarUserSettings.toObject(e.avatarUserSettings,a),a.oneofs&&(A._avatarUserSettings="avatarUserSettings")),e.fontSize!=null&&e.hasOwnProperty("fontSize")&&(A.fontSize=e.fontSize,a.oneofs&&(A._fontSize="fontSize")),e.securityNotifications!=null&&e.hasOwnProperty("securityNotifications")&&(A.securityNotifications=e.securityNotifications,a.oneofs&&(A._securityNotifications="securityNotifications")),e.autoUnarchiveChats!=null&&e.hasOwnProperty("autoUnarchiveChats")&&(A.autoUnarchiveChats=e.autoUnarchiveChats,a.oneofs&&(A._autoUnarchiveChats="autoUnarchiveChats")),e.videoQualityMode!=null&&e.hasOwnProperty("videoQualityMode")&&(A.videoQualityMode=e.videoQualityMode,a.oneofs&&(A._videoQualityMode="videoQualityMode")),e.photoQualityMode!=null&&e.hasOwnProperty("photoQualityMode")&&(A.photoQualityMode=e.photoQualityMode,a.oneofs&&(A._photoQualityMode="photoQualityMode")),e.individualNotificationSettings!=null&&e.hasOwnProperty("individualNotificationSettings")&&(A.individualNotificationSettings=E.proto.NotificationSettings.toObject(e.individualNotificationSettings,a),a.oneofs&&(A._individualNotificationSettings="individualNotificationSettings")),e.groupNotificationSettings!=null&&e.hasOwnProperty("groupNotificationSettings")&&(A.groupNotificationSettings=E.proto.NotificationSettings.toObject(e.groupNotificationSettings,a),a.oneofs&&(A._groupNotificationSettings="groupNotificationSettings")),e.chatLockSettings!=null&&e.hasOwnProperty("chatLockSettings")&&(A.chatLockSettings=E.proto.ChatLockSettings.toObject(e.chatLockSettings,a),a.oneofs&&(A._chatLockSettings="chatLockSettings")),e.chatDbLidMigrationTimestamp!=null&&e.hasOwnProperty("chatDbLidMigrationTimestamp")&&(typeof e.chatDbLidMigrationTimestamp=="number"?A.chatDbLidMigrationTimestamp=a.longs===String?String(e.chatDbLidMigrationTimestamp):e.chatDbLidMigrationTimestamp:A.chatDbLidMigrationTimestamp=a.longs===String?re(e.chatDbLidMigrationTimestamp):a.longs===Number?ae(e.chatDbLidMigrationTimestamp):e.chatDbLidMigrationTimestamp,a.oneofs&&(A._chatDbLidMigrationTimestamp="chatDbLidMigrationTimestamp")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GlobalSettings"},r})(),n.GroupHistoryBundleInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.deprecatedMessageHistoryBundle=E.proto.Message.MessageHistoryBundle.decode(e,e.uint32());break}case 2:{s.processState=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.GroupHistoryBundleInfo)return e;var a=new E.proto.GroupHistoryBundleInfo;if(e.deprecatedMessageHistoryBundle!=null){if(typeof e.deprecatedMessageHistoryBundle!="object")throw TypeError(".proto.GroupHistoryBundleInfo.deprecatedMessageHistoryBundle: object expected");a.deprecatedMessageHistoryBundle=E.proto.Message.MessageHistoryBundle.fromObject(e.deprecatedMessageHistoryBundle)}switch(e.processState){default:if(typeof e.processState=="number"){a.processState=e.processState;break}break;case"NOT_INJECTED":case 0:a.processState=0;break;case"INJECTED":case 1:a.processState=1;break;case"INJECTED_PARTIAL":case 2:a.processState=2;break;case"INJECTION_FAILED":case 3:a.processState=3;break;case"INJECTION_FAILED_NO_RETRY":case 4:a.processState=4;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.deprecatedMessageHistoryBundle!=null&&e.hasOwnProperty("deprecatedMessageHistoryBundle")&&(A.deprecatedMessageHistoryBundle=E.proto.Message.MessageHistoryBundle.toObject(e.deprecatedMessageHistoryBundle,a),a.oneofs&&(A._deprecatedMessageHistoryBundle="deprecatedMessageHistoryBundle")),e.processState!=null&&e.hasOwnProperty("processState")&&(A.processState=a.enums===String?E.proto.GroupHistoryBundleInfo.ProcessState[e.processState]===void 0?e.processState:E.proto.GroupHistoryBundleInfo.ProcessState[e.processState]:e.processState,a.oneofs&&(A._processState="processState")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupHistoryBundleInfo"},r.ProcessState=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_INJECTED"]=0,e[i[1]="INJECTED"]=1,e[i[2]="INJECTED_PARTIAL"]=2,e[i[3]="INJECTION_FAILED"]=3,e[i[4]="INJECTION_FAILED_NO_RETRY"]=4,e})(),r})(),n.GroupHistoryIndividualMessageInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.bundleMessageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.editedAfterReceivedAsHistory=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.GroupHistoryIndividualMessageInfo)return e;var a=new E.proto.GroupHistoryIndividualMessageInfo;if(e.bundleMessageKey!=null){if(typeof e.bundleMessageKey!="object")throw TypeError(".proto.GroupHistoryIndividualMessageInfo.bundleMessageKey: object expected");a.bundleMessageKey=E.proto.MessageKey.fromObject(e.bundleMessageKey)}return e.editedAfterReceivedAsHistory!=null&&(a.editedAfterReceivedAsHistory=!!e.editedAfterReceivedAsHistory),a},r.toObject=function(e,a){a||(a={});var A={};return e.bundleMessageKey!=null&&e.hasOwnProperty("bundleMessageKey")&&(A.bundleMessageKey=E.proto.MessageKey.toObject(e.bundleMessageKey,a),a.oneofs&&(A._bundleMessageKey="bundleMessageKey")),e.editedAfterReceivedAsHistory!=null&&e.hasOwnProperty("editedAfterReceivedAsHistory")&&(A.editedAfterReceivedAsHistory=e.editedAfterReceivedAsHistory,a.oneofs&&(A._editedAfterReceivedAsHistory="editedAfterReceivedAsHistory")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupHistoryIndividualMessageInfo"},r})(),n.GroupMention=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.groupJid=e.string();break}case 2:{s.groupSubject=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.GroupMention)return e;var a=new E.proto.GroupMention;return e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.groupSubject!=null&&(a.groupSubject=String(e.groupSubject)),a},r.toObject=function(e,a){a||(a={});var A={};return e.groupJid!=null&&e.hasOwnProperty("groupJid")&&(A.groupJid=e.groupJid,a.oneofs&&(A._groupJid="groupJid")),e.groupSubject!=null&&e.hasOwnProperty("groupSubject")&&(A.groupSubject=e.groupSubject,a.oneofs&&(A._groupSubject="groupSubject")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupMention"},r})(),n.GroupParticipant=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.rank=e.int32();break}case 3:{s.memberLabel=E.proto.MemberLabel.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.GroupParticipant)return e;var a=new E.proto.GroupParticipant;switch(e.userJid!=null&&(a.userJid=String(e.userJid)),e.rank){default:if(typeof e.rank=="number"){a.rank=e.rank;break}break;case"REGULAR":case 0:a.rank=0;break;case"ADMIN":case 1:a.rank=1;break;case"SUPERADMIN":case 2:a.rank=2;break}if(e.memberLabel!=null){if(typeof e.memberLabel!="object")throw TypeError(".proto.GroupParticipant.memberLabel: object expected");a.memberLabel=E.proto.MemberLabel.fromObject(e.memberLabel)}return a},r.toObject=function(e,a){a||(a={});var A={};return a.defaults&&(A.userJid=""),e.userJid!=null&&e.hasOwnProperty("userJid")&&(A.userJid=e.userJid),e.rank!=null&&e.hasOwnProperty("rank")&&(A.rank=a.enums===String?E.proto.GroupParticipant.Rank[e.rank]===void 0?e.rank:E.proto.GroupParticipant.Rank[e.rank]:e.rank,a.oneofs&&(A._rank="rank")),e.memberLabel!=null&&e.hasOwnProperty("memberLabel")&&(A.memberLabel=E.proto.MemberLabel.toObject(e.memberLabel,a),a.oneofs&&(A._memberLabel="memberLabel")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupParticipant"},r.Rank=(function(){let i={},e=Object.create(i);return e[i[0]="REGULAR"]=0,e[i[1]="ADMIN"]=1,e[i[2]="SUPERADMIN"]=2,e})(),r})(),n.HandshakeMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 2:{s.clientHello=E.proto.HandshakeMessage.ClientHello.decode(e,e.uint32());break}case 3:{s.serverHello=E.proto.HandshakeMessage.ServerHello.decode(e,e.uint32());break}case 4:{s.clientFinish=E.proto.HandshakeMessage.ClientFinish.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.HandshakeMessage)return e;var a=new E.proto.HandshakeMessage;if(e.clientHello!=null){if(typeof e.clientHello!="object")throw TypeError(".proto.HandshakeMessage.clientHello: object expected");a.clientHello=E.proto.HandshakeMessage.ClientHello.fromObject(e.clientHello)}if(e.serverHello!=null){if(typeof e.serverHello!="object")throw TypeError(".proto.HandshakeMessage.serverHello: object expected");a.serverHello=E.proto.HandshakeMessage.ServerHello.fromObject(e.serverHello)}if(e.clientFinish!=null){if(typeof e.clientFinish!="object")throw TypeError(".proto.HandshakeMessage.clientFinish: object expected");a.clientFinish=E.proto.HandshakeMessage.ClientFinish.fromObject(e.clientFinish)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.clientHello!=null&&e.hasOwnProperty("clientHello")&&(A.clientHello=E.proto.HandshakeMessage.ClientHello.toObject(e.clientHello,a),a.oneofs&&(A._clientHello="clientHello")),e.serverHello!=null&&e.hasOwnProperty("serverHello")&&(A.serverHello=E.proto.HandshakeMessage.ServerHello.toObject(e.serverHello,a),a.oneofs&&(A._serverHello="serverHello")),e.clientFinish!=null&&e.hasOwnProperty("clientFinish")&&(A.clientFinish=E.proto.HandshakeMessage.ClientFinish.toObject(e.clientFinish,a),a.oneofs&&(A._clientFinish="clientFinish")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HandshakeMessage"},r.ClientFinish=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.static=A.bytes();break}case 2:{c.payload=A.bytes();break}case 3:{c.extendedCiphertext=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.HandshakeMessage.ClientFinish)return A;var t=new E.proto.HandshakeMessage.ClientFinish;return A.static!=null&&(typeof A.static=="string"?I.base64.decode(A.static,t.static=I.newBuffer(I.base64.length(A.static)),0):A.static.length>=0&&(t.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?I.base64.decode(A.payload,t.payload=I.newBuffer(I.base64.length(A.payload)),0):A.payload.length>=0&&(t.payload=A.payload)),A.extendedCiphertext!=null&&(typeof A.extendedCiphertext=="string"?I.base64.decode(A.extendedCiphertext,t.extendedCiphertext=I.newBuffer(I.base64.length(A.extendedCiphertext)),0):A.extendedCiphertext.length>=0&&(t.extendedCiphertext=A.extendedCiphertext)),t},i.toObject=function(A,t){t||(t={});var s={};return A.static!=null&&A.hasOwnProperty("static")&&(s.static=t.bytes===String?I.base64.encode(A.static,0,A.static.length):t.bytes===Array?Array.prototype.slice.call(A.static):A.static,t.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=t.bytes===String?I.base64.encode(A.payload,0,A.payload.length):t.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,t.oneofs&&(s._payload="payload")),A.extendedCiphertext!=null&&A.hasOwnProperty("extendedCiphertext")&&(s.extendedCiphertext=t.bytes===String?I.base64.encode(A.extendedCiphertext,0,A.extendedCiphertext.length):t.bytes===Array?Array.prototype.slice.call(A.extendedCiphertext):A.extendedCiphertext,t.oneofs&&(s._extendedCiphertext="extendedCiphertext")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ClientFinish"},i})(),r.ClientHello=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.ephemeral=A.bytes();break}case 2:{c.static=A.bytes();break}case 3:{c.payload=A.bytes();break}case 4:{c.useExtended=A.bool();break}case 5:{c.extendedCiphertext=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.HandshakeMessage.ClientHello)return A;var t=new E.proto.HandshakeMessage.ClientHello;return A.ephemeral!=null&&(typeof A.ephemeral=="string"?I.base64.decode(A.ephemeral,t.ephemeral=I.newBuffer(I.base64.length(A.ephemeral)),0):A.ephemeral.length>=0&&(t.ephemeral=A.ephemeral)),A.static!=null&&(typeof A.static=="string"?I.base64.decode(A.static,t.static=I.newBuffer(I.base64.length(A.static)),0):A.static.length>=0&&(t.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?I.base64.decode(A.payload,t.payload=I.newBuffer(I.base64.length(A.payload)),0):A.payload.length>=0&&(t.payload=A.payload)),A.useExtended!=null&&(t.useExtended=!!A.useExtended),A.extendedCiphertext!=null&&(typeof A.extendedCiphertext=="string"?I.base64.decode(A.extendedCiphertext,t.extendedCiphertext=I.newBuffer(I.base64.length(A.extendedCiphertext)),0):A.extendedCiphertext.length>=0&&(t.extendedCiphertext=A.extendedCiphertext)),t},i.toObject=function(A,t){t||(t={});var s={};return A.ephemeral!=null&&A.hasOwnProperty("ephemeral")&&(s.ephemeral=t.bytes===String?I.base64.encode(A.ephemeral,0,A.ephemeral.length):t.bytes===Array?Array.prototype.slice.call(A.ephemeral):A.ephemeral,t.oneofs&&(s._ephemeral="ephemeral")),A.static!=null&&A.hasOwnProperty("static")&&(s.static=t.bytes===String?I.base64.encode(A.static,0,A.static.length):t.bytes===Array?Array.prototype.slice.call(A.static):A.static,t.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=t.bytes===String?I.base64.encode(A.payload,0,A.payload.length):t.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,t.oneofs&&(s._payload="payload")),A.useExtended!=null&&A.hasOwnProperty("useExtended")&&(s.useExtended=A.useExtended,t.oneofs&&(s._useExtended="useExtended")),A.extendedCiphertext!=null&&A.hasOwnProperty("extendedCiphertext")&&(s.extendedCiphertext=t.bytes===String?I.base64.encode(A.extendedCiphertext,0,A.extendedCiphertext.length):t.bytes===Array?Array.prototype.slice.call(A.extendedCiphertext):A.extendedCiphertext,t.oneofs&&(s._extendedCiphertext="extendedCiphertext")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ClientHello"},i})(),r.ServerHello=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.ephemeral=A.bytes();break}case 2:{c.static=A.bytes();break}case 3:{c.payload=A.bytes();break}case 4:{c.extendedStatic=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.HandshakeMessage.ServerHello)return A;var t=new E.proto.HandshakeMessage.ServerHello;return A.ephemeral!=null&&(typeof A.ephemeral=="string"?I.base64.decode(A.ephemeral,t.ephemeral=I.newBuffer(I.base64.length(A.ephemeral)),0):A.ephemeral.length>=0&&(t.ephemeral=A.ephemeral)),A.static!=null&&(typeof A.static=="string"?I.base64.decode(A.static,t.static=I.newBuffer(I.base64.length(A.static)),0):A.static.length>=0&&(t.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?I.base64.decode(A.payload,t.payload=I.newBuffer(I.base64.length(A.payload)),0):A.payload.length>=0&&(t.payload=A.payload)),A.extendedStatic!=null&&(typeof A.extendedStatic=="string"?I.base64.decode(A.extendedStatic,t.extendedStatic=I.newBuffer(I.base64.length(A.extendedStatic)),0):A.extendedStatic.length>=0&&(t.extendedStatic=A.extendedStatic)),t},i.toObject=function(A,t){t||(t={});var s={};return A.ephemeral!=null&&A.hasOwnProperty("ephemeral")&&(s.ephemeral=t.bytes===String?I.base64.encode(A.ephemeral,0,A.ephemeral.length):t.bytes===Array?Array.prototype.slice.call(A.ephemeral):A.ephemeral,t.oneofs&&(s._ephemeral="ephemeral")),A.static!=null&&A.hasOwnProperty("static")&&(s.static=t.bytes===String?I.base64.encode(A.static,0,A.static.length):t.bytes===Array?Array.prototype.slice.call(A.static):A.static,t.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=t.bytes===String?I.base64.encode(A.payload,0,A.payload.length):t.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,t.oneofs&&(s._payload="payload")),A.extendedStatic!=null&&A.hasOwnProperty("extendedStatic")&&(s.extendedStatic=t.bytes===String?I.base64.encode(A.extendedStatic,0,A.extendedStatic.length):t.bytes===Array?Array.prototype.slice.call(A.extendedStatic):A.extendedStatic,t.oneofs&&(s._extendedStatic="extendedStatic")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ServerHello"},i})(),r})(),n.HistorySync=(function(){function r(i){if(this.conversations=[],this.statusV3Messages=[],this.pushnames=[],this.recentStickers=[],this.pastParticipants=[],this.callLogRecords=[],this.phoneNumberToLidMappings=[],this.accounts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.syncType=e.int32();break}case 2:{s.conversations&&s.conversations.length||(s.conversations=[]),s.conversations.push(E.proto.Conversation.decode(e,e.uint32()));break}case 3:{s.statusV3Messages&&s.statusV3Messages.length||(s.statusV3Messages=[]),s.statusV3Messages.push(E.proto.WebMessageInfo.decode(e,e.uint32()));break}case 5:{s.chunkOrder=e.uint32();break}case 6:{s.progress=e.uint32();break}case 7:{s.pushnames&&s.pushnames.length||(s.pushnames=[]),s.pushnames.push(E.proto.Pushname.decode(e,e.uint32()));break}case 8:{s.globalSettings=E.proto.GlobalSettings.decode(e,e.uint32());break}case 9:{s.threadIdUserSecret=e.bytes();break}case 10:{s.threadDsTimeframeOffset=e.uint32();break}case 11:{s.recentStickers&&s.recentStickers.length||(s.recentStickers=[]),s.recentStickers.push(E.proto.StickerMetadata.decode(e,e.uint32()));break}case 12:{s.pastParticipants&&s.pastParticipants.length||(s.pastParticipants=[]),s.pastParticipants.push(E.proto.PastParticipants.decode(e,e.uint32()));break}case 13:{s.callLogRecords&&s.callLogRecords.length||(s.callLogRecords=[]),s.callLogRecords.push(E.proto.CallLogRecord.decode(e,e.uint32()));break}case 14:{s.aiWaitListState=e.int32();break}case 15:{s.phoneNumberToLidMappings&&s.phoneNumberToLidMappings.length||(s.phoneNumberToLidMappings=[]),s.phoneNumberToLidMappings.push(E.proto.PhoneNumberToLIDMapping.decode(e,e.uint32()));break}case 16:{s.companionMetaNonce=e.string();break}case 17:{s.shareableChatIdentifierEncryptionKey=e.bytes();break}case 18:{s.accounts&&s.accounts.length||(s.accounts=[]),s.accounts.push(E.proto.Account.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.HistorySync)return e;var a=new E.proto.HistorySync;switch(e.syncType){default:if(typeof e.syncType=="number"){a.syncType=e.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:a.syncType=0;break;case"INITIAL_STATUS_V3":case 1:a.syncType=1;break;case"FULL":case 2:a.syncType=2;break;case"RECENT":case 3:a.syncType=3;break;case"PUSH_NAME":case 4:a.syncType=4;break;case"NON_BLOCKING_DATA":case 5:a.syncType=5;break;case"ON_DEMAND":case 6:a.syncType=6;break}if(e.conversations){if(!Array.isArray(e.conversations))throw TypeError(".proto.HistorySync.conversations: array expected");a.conversations=[];for(var A=0;A>>0),e.progress!=null&&(a.progress=e.progress>>>0),e.pushnames){if(!Array.isArray(e.pushnames))throw TypeError(".proto.HistorySync.pushnames: array expected");a.pushnames=[];for(var A=0;A=0&&(a.threadIdUserSecret=e.threadIdUserSecret)),e.threadDsTimeframeOffset!=null&&(a.threadDsTimeframeOffset=e.threadDsTimeframeOffset>>>0),e.recentStickers){if(!Array.isArray(e.recentStickers))throw TypeError(".proto.HistorySync.recentStickers: array expected");a.recentStickers=[];for(var A=0;A=0&&(a.shareableChatIdentifierEncryptionKey=e.shareableChatIdentifierEncryptionKey)),e.accounts){if(!Array.isArray(e.accounts))throw TypeError(".proto.HistorySync.accounts: array expected");a.accounts=[];for(var A=0;A>>3){case 1:{s.message=E.proto.WebMessageInfo.decode(e,e.uint32());break}case 2:{s.msgOrderId=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.HistorySyncMsg)return e;var a=new E.proto.HistorySyncMsg;if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.HistorySyncMsg.message: object expected");a.message=E.proto.WebMessageInfo.fromObject(e.message)}return e.msgOrderId!=null&&(I.Long?(a.msgOrderId=I.Long.fromValue(e.msgOrderId)).unsigned=!0:typeof e.msgOrderId=="string"?a.msgOrderId=parseInt(e.msgOrderId,10):typeof e.msgOrderId=="number"?a.msgOrderId=e.msgOrderId:typeof e.msgOrderId=="object"&&(a.msgOrderId=new I.LongBits(e.msgOrderId.low>>>0,e.msgOrderId.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};return e.message!=null&&e.hasOwnProperty("message")&&(A.message=E.proto.WebMessageInfo.toObject(e.message,a),a.oneofs&&(A._message="message")),e.msgOrderId!=null&&e.hasOwnProperty("msgOrderId")&&(typeof e.msgOrderId=="number"?A.msgOrderId=a.longs===String?String(e.msgOrderId):e.msgOrderId:A.msgOrderId=a.longs===String?re(e.msgOrderId,!0):a.longs===Number?ae(e.msgOrderId,!0):e.msgOrderId,a.oneofs&&(A._msgOrderId="msgOrderId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HistorySyncMsg"},r})(),n.HydratedTemplateButton=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 4:{s.index=e.uint32();break}case 1:{s.quickReplyButton=E.proto.HydratedTemplateButton.HydratedQuickReplyButton.decode(e,e.uint32());break}case 2:{s.urlButton=E.proto.HydratedTemplateButton.HydratedURLButton.decode(e,e.uint32());break}case 3:{s.callButton=E.proto.HydratedTemplateButton.HydratedCallButton.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.HydratedTemplateButton)return e;var a=new E.proto.HydratedTemplateButton;if(e.index!=null&&(a.index=e.index>>>0),e.quickReplyButton!=null){if(typeof e.quickReplyButton!="object")throw TypeError(".proto.HydratedTemplateButton.quickReplyButton: object expected");a.quickReplyButton=E.proto.HydratedTemplateButton.HydratedQuickReplyButton.fromObject(e.quickReplyButton)}if(e.urlButton!=null){if(typeof e.urlButton!="object")throw TypeError(".proto.HydratedTemplateButton.urlButton: object expected");a.urlButton=E.proto.HydratedTemplateButton.HydratedURLButton.fromObject(e.urlButton)}if(e.callButton!=null){if(typeof e.callButton!="object")throw TypeError(".proto.HydratedTemplateButton.callButton: object expected");a.callButton=E.proto.HydratedTemplateButton.HydratedCallButton.fromObject(e.callButton)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.quickReplyButton!=null&&e.hasOwnProperty("quickReplyButton")&&(A.quickReplyButton=E.proto.HydratedTemplateButton.HydratedQuickReplyButton.toObject(e.quickReplyButton,a),a.oneofs&&(A.hydratedButton="quickReplyButton")),e.urlButton!=null&&e.hasOwnProperty("urlButton")&&(A.urlButton=E.proto.HydratedTemplateButton.HydratedURLButton.toObject(e.urlButton,a),a.oneofs&&(A.hydratedButton="urlButton")),e.callButton!=null&&e.hasOwnProperty("callButton")&&(A.callButton=E.proto.HydratedTemplateButton.HydratedCallButton.toObject(e.callButton,a),a.oneofs&&(A.hydratedButton="callButton")),e.index!=null&&e.hasOwnProperty("index")&&(A.index=e.index,a.oneofs&&(A._index="index")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HydratedTemplateButton"},r.HydratedCallButton=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayText=A.string();break}case 2:{c.phoneNumber=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.HydratedTemplateButton.HydratedCallButton)return A;var t=new E.proto.HydratedTemplateButton.HydratedCallButton;return A.displayText!=null&&(t.displayText=String(A.displayText)),A.phoneNumber!=null&&(t.phoneNumber=String(A.phoneNumber)),t},i.toObject=function(A,t){t||(t={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,t.oneofs&&(s._displayText="displayText")),A.phoneNumber!=null&&A.hasOwnProperty("phoneNumber")&&(s.phoneNumber=A.phoneNumber,t.oneofs&&(s._phoneNumber="phoneNumber")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedCallButton"},i})(),r.HydratedQuickReplyButton=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayText=A.string();break}case 2:{c.id=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.HydratedTemplateButton.HydratedQuickReplyButton)return A;var t=new E.proto.HydratedTemplateButton.HydratedQuickReplyButton;return A.displayText!=null&&(t.displayText=String(A.displayText)),A.id!=null&&(t.id=String(A.id)),t},i.toObject=function(A,t){t||(t={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,t.oneofs&&(s._displayText="displayText")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,t.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedQuickReplyButton"},i})(),r.HydratedURLButton=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayText=A.string();break}case 2:{c.url=A.string();break}case 3:{c.consentedUsersUrl=A.string();break}case 4:{c.webviewPresentation=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.HydratedTemplateButton.HydratedURLButton)return A;var t=new E.proto.HydratedTemplateButton.HydratedURLButton;switch(A.displayText!=null&&(t.displayText=String(A.displayText)),A.url!=null&&(t.url=String(A.url)),A.consentedUsersUrl!=null&&(t.consentedUsersUrl=String(A.consentedUsersUrl)),A.webviewPresentation){default:if(typeof A.webviewPresentation=="number"){t.webviewPresentation=A.webviewPresentation;break}break;case"FULL":case 1:t.webviewPresentation=1;break;case"TALL":case 2:t.webviewPresentation=2;break;case"COMPACT":case 3:t.webviewPresentation=3;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,t.oneofs&&(s._displayText="displayText")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.consentedUsersUrl!=null&&A.hasOwnProperty("consentedUsersUrl")&&(s.consentedUsersUrl=A.consentedUsersUrl,t.oneofs&&(s._consentedUsersUrl="consentedUsersUrl")),A.webviewPresentation!=null&&A.hasOwnProperty("webviewPresentation")&&(s.webviewPresentation=t.enums===String?E.proto.HydratedTemplateButton.HydratedURLButton.WebviewPresentationType[A.webviewPresentation]===void 0?A.webviewPresentation:E.proto.HydratedTemplateButton.HydratedURLButton.WebviewPresentationType[A.webviewPresentation]:A.webviewPresentation,t.oneofs&&(s._webviewPresentation="webviewPresentation")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedURLButton"},i.WebviewPresentationType=(function(){let a={},A=Object.create(a);return A[a[1]="FULL"]=1,A[a[2]="TALL"]=2,A[a[3]="COMPACT"]=3,A})(),i})(),r})(),n.IdentityKeyPairStructure=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.privateKey=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.IdentityKeyPairStructure)return e;var a=new E.proto.IdentityKeyPairStructure;return e.publicKey!=null&&(typeof e.publicKey=="string"?I.base64.decode(e.publicKey,a.publicKey=I.newBuffer(I.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?I.base64.decode(e.privateKey,a.privateKey=I.newBuffer(I.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),a},r.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?I.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?I.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.IdentityKeyPairStructure"},r})(),n.InThreadSurveyMetadata=(function(){function r(i){if(this.questions=[],this.privacyStatementParts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.tessaSessionId=e.string();break}case 2:{s.simonSessionId=e.string();break}case 3:{s.simonSurveyId=e.string();break}case 4:{s.tessaRootId=e.string();break}case 5:{s.requestId=e.string();break}case 6:{s.tessaEvent=e.string();break}case 7:{s.invitationHeaderText=e.string();break}case 8:{s.invitationBodyText=e.string();break}case 9:{s.invitationCtaText=e.string();break}case 10:{s.invitationCtaUrl=e.string();break}case 11:{s.surveyTitle=e.string();break}case 12:{s.questions&&s.questions.length||(s.questions=[]),s.questions.push(E.proto.InThreadSurveyMetadata.InThreadSurveyQuestion.decode(e,e.uint32()));break}case 13:{s.surveyContinueButtonText=e.string();break}case 14:{s.surveySubmitButtonText=e.string();break}case 15:{s.privacyStatementFull=e.string();break}case 16:{s.privacyStatementParts&&s.privacyStatementParts.length||(s.privacyStatementParts=[]),s.privacyStatementParts.push(E.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart.decode(e,e.uint32()));break}case 17:{s.feedbackToastText=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.InThreadSurveyMetadata)return e;var a=new E.proto.InThreadSurveyMetadata;if(e.tessaSessionId!=null&&(a.tessaSessionId=String(e.tessaSessionId)),e.simonSessionId!=null&&(a.simonSessionId=String(e.simonSessionId)),e.simonSurveyId!=null&&(a.simonSurveyId=String(e.simonSurveyId)),e.tessaRootId!=null&&(a.tessaRootId=String(e.tessaRootId)),e.requestId!=null&&(a.requestId=String(e.requestId)),e.tessaEvent!=null&&(a.tessaEvent=String(e.tessaEvent)),e.invitationHeaderText!=null&&(a.invitationHeaderText=String(e.invitationHeaderText)),e.invitationBodyText!=null&&(a.invitationBodyText=String(e.invitationBodyText)),e.invitationCtaText!=null&&(a.invitationCtaText=String(e.invitationCtaText)),e.invitationCtaUrl!=null&&(a.invitationCtaUrl=String(e.invitationCtaUrl)),e.surveyTitle!=null&&(a.surveyTitle=String(e.surveyTitle)),e.questions){if(!Array.isArray(e.questions))throw TypeError(".proto.InThreadSurveyMetadata.questions: array expected");a.questions=[];for(var A=0;A>>3){case 1:{c.stringValue=A.string();break}case 2:{c.numericValue=A.uint32();break}case 3:{c.textTranslated=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.InThreadSurveyMetadata.InThreadSurveyOption)return A;var t=new E.proto.InThreadSurveyMetadata.InThreadSurveyOption;return A.stringValue!=null&&(t.stringValue=String(A.stringValue)),A.numericValue!=null&&(t.numericValue=A.numericValue>>>0),A.textTranslated!=null&&(t.textTranslated=String(A.textTranslated)),t},i.toObject=function(A,t){t||(t={});var s={};return A.stringValue!=null&&A.hasOwnProperty("stringValue")&&(s.stringValue=A.stringValue,t.oneofs&&(s._stringValue="stringValue")),A.numericValue!=null&&A.hasOwnProperty("numericValue")&&(s.numericValue=A.numericValue,t.oneofs&&(s._numericValue="numericValue")),A.textTranslated!=null&&A.hasOwnProperty("textTranslated")&&(s.textTranslated=A.textTranslated,t.oneofs&&(s._textTranslated="textTranslated")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.InThreadSurveyMetadata.InThreadSurveyOption"},i})(),r.InThreadSurveyPrivacyStatementPart=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.text=A.string();break}case 2:{c.url=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart)return A;var t=new E.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart;return A.text!=null&&(t.text=String(A.text)),A.url!=null&&(t.url=String(A.url)),t},i.toObject=function(A,t){t||(t={});var s={};return A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,t.oneofs&&(s._text="text")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart"},i})(),r.InThreadSurveyQuestion=(function(){function i(a){if(this.questionOptions=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.questionText=A.string();break}case 2:{c.questionId=A.string();break}case 3:{c.questionOptions&&c.questionOptions.length||(c.questionOptions=[]),c.questionOptions.push(E.proto.InThreadSurveyMetadata.InThreadSurveyOption.decode(A,A.uint32()));break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.InThreadSurveyMetadata.InThreadSurveyQuestion)return A;var t=new E.proto.InThreadSurveyMetadata.InThreadSurveyQuestion;if(A.questionText!=null&&(t.questionText=String(A.questionText)),A.questionId!=null&&(t.questionId=String(A.questionId)),A.questionOptions){if(!Array.isArray(A.questionOptions))throw TypeError(".proto.InThreadSurveyMetadata.InThreadSurveyQuestion.questionOptions: array expected");t.questionOptions=[];for(var s=0;s>>3){case 1:{s.polygonVertices&&s.polygonVertices.length||(s.polygonVertices=[]),s.polygonVertices.push(E.proto.Point.decode(e,e.uint32()));break}case 4:{s.shouldSkipConfirmation=e.bool();break}case 5:{s.embeddedContent=E.proto.EmbeddedContent.decode(e,e.uint32());break}case 8:{s.statusLinkType=e.int32();break}case 2:{s.location=E.proto.Location.decode(e,e.uint32());break}case 3:{s.newsletter=E.proto.ContextInfo.ForwardedNewsletterMessageInfo.decode(e,e.uint32());break}case 6:{s.embeddedAction=e.bool();break}case 7:{s.tapAction=E.proto.TapLinkAction.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.InteractiveAnnotation)return e;var a=new E.proto.InteractiveAnnotation;if(e.polygonVertices){if(!Array.isArray(e.polygonVertices))throw TypeError(".proto.InteractiveAnnotation.polygonVertices: array expected");a.polygonVertices=[];for(var A=0;A>>3){case 1:{s.isGalaxyFlowCompleted=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.InteractiveMessageAdditionalMetadata)return e;var a=new E.proto.InteractiveMessageAdditionalMetadata;return e.isGalaxyFlowCompleted!=null&&(a.isGalaxyFlowCompleted=!!e.isGalaxyFlowCompleted),a},r.toObject=function(e,a){a||(a={});var A={};return e.isGalaxyFlowCompleted!=null&&e.hasOwnProperty("isGalaxyFlowCompleted")&&(A.isGalaxyFlowCompleted=e.isGalaxyFlowCompleted,a.oneofs&&(A._isGalaxyFlowCompleted="isGalaxyFlowCompleted")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.InteractiveMessageAdditionalMetadata"},r})(),n.KeepInChat=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.keepType=e.int32();break}case 2:{s.serverTimestamp=e.int64();break}case 3:{s.key=E.proto.MessageKey.decode(e,e.uint32());break}case 4:{s.deviceJid=e.string();break}case 5:{s.clientTimestampMs=e.int64();break}case 6:{s.serverTimestampMs=e.int64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.KeepInChat)return e;var a=new E.proto.KeepInChat;switch(e.keepType){default:if(typeof e.keepType=="number"){a.keepType=e.keepType;break}break;case"UNKNOWN":case 0:a.keepType=0;break;case"KEEP_FOR_ALL":case 1:a.keepType=1;break;case"UNDO_KEEP_FOR_ALL":case 2:a.keepType=2;break}if(e.serverTimestamp!=null&&(I.Long?(a.serverTimestamp=I.Long.fromValue(e.serverTimestamp)).unsigned=!1:typeof e.serverTimestamp=="string"?a.serverTimestamp=parseInt(e.serverTimestamp,10):typeof e.serverTimestamp=="number"?a.serverTimestamp=e.serverTimestamp:typeof e.serverTimestamp=="object"&&(a.serverTimestamp=new I.LongBits(e.serverTimestamp.low>>>0,e.serverTimestamp.high>>>0).toNumber())),e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.KeepInChat.key: object expected");a.key=E.proto.MessageKey.fromObject(e.key)}return e.deviceJid!=null&&(a.deviceJid=String(e.deviceJid)),e.clientTimestampMs!=null&&(I.Long?(a.clientTimestampMs=I.Long.fromValue(e.clientTimestampMs)).unsigned=!1:typeof e.clientTimestampMs=="string"?a.clientTimestampMs=parseInt(e.clientTimestampMs,10):typeof e.clientTimestampMs=="number"?a.clientTimestampMs=e.clientTimestampMs:typeof e.clientTimestampMs=="object"&&(a.clientTimestampMs=new I.LongBits(e.clientTimestampMs.low>>>0,e.clientTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(I.Long?(a.serverTimestampMs=I.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new I.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.keepType!=null&&e.hasOwnProperty("keepType")&&(A.keepType=a.enums===String?E.proto.KeepType[e.keepType]===void 0?e.keepType:E.proto.KeepType[e.keepType]:e.keepType,a.oneofs&&(A._keepType="keepType")),e.serverTimestamp!=null&&e.hasOwnProperty("serverTimestamp")&&(typeof e.serverTimestamp=="number"?A.serverTimestamp=a.longs===String?String(e.serverTimestamp):e.serverTimestamp:A.serverTimestamp=a.longs===String?re(e.serverTimestamp):a.longs===Number?ae(e.serverTimestamp):e.serverTimestamp,a.oneofs&&(A._serverTimestamp="serverTimestamp")),e.key!=null&&e.hasOwnProperty("key")&&(A.key=E.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.deviceJid!=null&&e.hasOwnProperty("deviceJid")&&(A.deviceJid=e.deviceJid,a.oneofs&&(A._deviceJid="deviceJid")),e.clientTimestampMs!=null&&e.hasOwnProperty("clientTimestampMs")&&(typeof e.clientTimestampMs=="number"?A.clientTimestampMs=a.longs===String?String(e.clientTimestampMs):e.clientTimestampMs:A.clientTimestampMs=a.longs===String?re(e.clientTimestampMs):a.longs===Number?ae(e.clientTimestampMs):e.clientTimestampMs,a.oneofs&&(A._clientTimestampMs="clientTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?re(e.serverTimestampMs):a.longs===Number?ae(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeepInChat"},r})(),n.KeepType=(function(){let r={},o=Object.create(r);return o[r[0]="UNKNOWN"]=0,o[r[1]="KEEP_FOR_ALL"]=1,o[r[2]="UNDO_KEEP_FOR_ALL"]=2,o})(),n.KeyExchangeMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.baseKey=e.bytes();break}case 3:{s.ratchetKey=e.bytes();break}case 4:{s.identityKey=e.bytes();break}case 5:{s.baseKeySignature=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.KeyExchangeMessage)return e;var a=new E.proto.KeyExchangeMessage;return e.id!=null&&(a.id=e.id>>>0),e.baseKey!=null&&(typeof e.baseKey=="string"?I.base64.decode(e.baseKey,a.baseKey=I.newBuffer(I.base64.length(e.baseKey)),0):e.baseKey.length>=0&&(a.baseKey=e.baseKey)),e.ratchetKey!=null&&(typeof e.ratchetKey=="string"?I.base64.decode(e.ratchetKey,a.ratchetKey=I.newBuffer(I.base64.length(e.ratchetKey)),0):e.ratchetKey.length>=0&&(a.ratchetKey=e.ratchetKey)),e.identityKey!=null&&(typeof e.identityKey=="string"?I.base64.decode(e.identityKey,a.identityKey=I.newBuffer(I.base64.length(e.identityKey)),0):e.identityKey.length>=0&&(a.identityKey=e.identityKey)),e.baseKeySignature!=null&&(typeof e.baseKeySignature=="string"?I.base64.decode(e.baseKeySignature,a.baseKeySignature=I.newBuffer(I.base64.length(e.baseKeySignature)),0):e.baseKeySignature.length>=0&&(a.baseKeySignature=e.baseKeySignature)),a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.baseKey!=null&&e.hasOwnProperty("baseKey")&&(A.baseKey=a.bytes===String?I.base64.encode(e.baseKey,0,e.baseKey.length):a.bytes===Array?Array.prototype.slice.call(e.baseKey):e.baseKey,a.oneofs&&(A._baseKey="baseKey")),e.ratchetKey!=null&&e.hasOwnProperty("ratchetKey")&&(A.ratchetKey=a.bytes===String?I.base64.encode(e.ratchetKey,0,e.ratchetKey.length):a.bytes===Array?Array.prototype.slice.call(e.ratchetKey):e.ratchetKey,a.oneofs&&(A._ratchetKey="ratchetKey")),e.identityKey!=null&&e.hasOwnProperty("identityKey")&&(A.identityKey=a.bytes===String?I.base64.encode(e.identityKey,0,e.identityKey.length):a.bytes===Array?Array.prototype.slice.call(e.identityKey):e.identityKey,a.oneofs&&(A._identityKey="identityKey")),e.baseKeySignature!=null&&e.hasOwnProperty("baseKeySignature")&&(A.baseKeySignature=a.bytes===String?I.base64.encode(e.baseKeySignature,0,e.baseKeySignature.length):a.bytes===Array?Array.prototype.slice.call(e.baseKeySignature):e.baseKeySignature,a.oneofs&&(A._baseKeySignature="baseKeySignature")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeyExchangeMessage"},r})(),n.KeyId=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.KeyId)return e;var a=new E.proto.KeyId;return e.id!=null&&(typeof e.id=="string"?I.base64.decode(e.id,a.id=I.newBuffer(I.base64.length(e.id)),0):e.id.length>=0&&(a.id=e.id)),a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=a.bytes===String?I.base64.encode(e.id,0,e.id.length):a.bytes===Array?Array.prototype.slice.call(e.id):e.id,a.oneofs&&(A._id="id")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeyId"},r})(),n.LIDMigrationMapping=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pn=e.uint64();break}case 2:{s.assignedLid=e.uint64();break}case 3:{s.latestLid=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.LIDMigrationMapping)return e;var a=new E.proto.LIDMigrationMapping;return e.pn!=null&&(I.Long?(a.pn=I.Long.fromValue(e.pn)).unsigned=!0:typeof e.pn=="string"?a.pn=parseInt(e.pn,10):typeof e.pn=="number"?a.pn=e.pn:typeof e.pn=="object"&&(a.pn=new I.LongBits(e.pn.low>>>0,e.pn.high>>>0).toNumber(!0))),e.assignedLid!=null&&(I.Long?(a.assignedLid=I.Long.fromValue(e.assignedLid)).unsigned=!0:typeof e.assignedLid=="string"?a.assignedLid=parseInt(e.assignedLid,10):typeof e.assignedLid=="number"?a.assignedLid=e.assignedLid:typeof e.assignedLid=="object"&&(a.assignedLid=new I.LongBits(e.assignedLid.low>>>0,e.assignedLid.high>>>0).toNumber(!0))),e.latestLid!=null&&(I.Long?(a.latestLid=I.Long.fromValue(e.latestLid)).unsigned=!0:typeof e.latestLid=="string"?a.latestLid=parseInt(e.latestLid,10):typeof e.latestLid=="number"?a.latestLid=e.latestLid:typeof e.latestLid=="object"&&(a.latestLid=new I.LongBits(e.latestLid.low>>>0,e.latestLid.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};if(a.defaults){if(I.Long){var t=new I.Long(0,0,!0);A.pn=a.longs===String?t.toString():a.longs===Number?t.toNumber():t}else A.pn=a.longs===String?"0":0;if(I.Long){var t=new I.Long(0,0,!0);A.assignedLid=a.longs===String?t.toString():a.longs===Number?t.toNumber():t}else A.assignedLid=a.longs===String?"0":0}return e.pn!=null&&e.hasOwnProperty("pn")&&(typeof e.pn=="number"?A.pn=a.longs===String?String(e.pn):e.pn:A.pn=a.longs===String?re(e.pn,!0):a.longs===Number?ae(e.pn,!0):e.pn),e.assignedLid!=null&&e.hasOwnProperty("assignedLid")&&(typeof e.assignedLid=="number"?A.assignedLid=a.longs===String?String(e.assignedLid):e.assignedLid:A.assignedLid=a.longs===String?re(e.assignedLid,!0):a.longs===Number?ae(e.assignedLid,!0):e.assignedLid),e.latestLid!=null&&e.hasOwnProperty("latestLid")&&(typeof e.latestLid=="number"?A.latestLid=a.longs===String?String(e.latestLid):e.latestLid:A.latestLid=a.longs===String?re(e.latestLid,!0):a.longs===Number?ae(e.latestLid,!0):e.latestLid,a.oneofs&&(A._latestLid="latestLid")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LIDMigrationMapping"},r})(),n.LIDMigrationMappingSyncMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encodedMappingPayload=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.LIDMigrationMappingSyncMessage)return e;var a=new E.proto.LIDMigrationMappingSyncMessage;return e.encodedMappingPayload!=null&&(typeof e.encodedMappingPayload=="string"?I.base64.decode(e.encodedMappingPayload,a.encodedMappingPayload=I.newBuffer(I.base64.length(e.encodedMappingPayload)),0):e.encodedMappingPayload.length>=0&&(a.encodedMappingPayload=e.encodedMappingPayload)),a},r.toObject=function(e,a){a||(a={});var A={};return e.encodedMappingPayload!=null&&e.hasOwnProperty("encodedMappingPayload")&&(A.encodedMappingPayload=a.bytes===String?I.base64.encode(e.encodedMappingPayload,0,e.encodedMappingPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encodedMappingPayload):e.encodedMappingPayload,a.oneofs&&(A._encodedMappingPayload="encodedMappingPayload")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LIDMigrationMappingSyncMessage"},r})(),n.LIDMigrationMappingSyncPayload=(function(){function r(i){if(this.pnToLidMappings=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pnToLidMappings&&s.pnToLidMappings.length||(s.pnToLidMappings=[]),s.pnToLidMappings.push(E.proto.LIDMigrationMapping.decode(e,e.uint32()));break}case 2:{s.chatDbMigrationTimestamp=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.LIDMigrationMappingSyncPayload)return e;var a=new E.proto.LIDMigrationMappingSyncPayload;if(e.pnToLidMappings){if(!Array.isArray(e.pnToLidMappings))throw TypeError(".proto.LIDMigrationMappingSyncPayload.pnToLidMappings: array expected");a.pnToLidMappings=[];for(var A=0;A>>0,e.chatDbMigrationTimestamp.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.pnToLidMappings=[]),e.pnToLidMappings&&e.pnToLidMappings.length){A.pnToLidMappings=[];for(var t=0;t>>3){case 1:{s.eventResponseMessage=E.proto.Message.EventResponseMessage.decode(e,e.uint32());break}case 2:{s.pollVote=E.proto.Message.PollVoteMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.LegacyMessage)return e;var a=new E.proto.LegacyMessage;if(e.eventResponseMessage!=null){if(typeof e.eventResponseMessage!="object")throw TypeError(".proto.LegacyMessage.eventResponseMessage: object expected");a.eventResponseMessage=E.proto.Message.EventResponseMessage.fromObject(e.eventResponseMessage)}if(e.pollVote!=null){if(typeof e.pollVote!="object")throw TypeError(".proto.LegacyMessage.pollVote: object expected");a.pollVote=E.proto.Message.PollVoteMessage.fromObject(e.pollVote)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.eventResponseMessage!=null&&e.hasOwnProperty("eventResponseMessage")&&(A.eventResponseMessage=E.proto.Message.EventResponseMessage.toObject(e.eventResponseMessage,a),a.oneofs&&(A._eventResponseMessage="eventResponseMessage")),e.pollVote!=null&&e.hasOwnProperty("pollVote")&&(A.pollVote=E.proto.Message.PollVoteMessage.toObject(e.pollVote,a),a.oneofs&&(A._pollVote="pollVote")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LegacyMessage"},r})(),n.LimitSharing=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sharingLimited=e.bool();break}case 2:{s.trigger=e.int32();break}case 3:{s.limitSharingSettingTimestamp=e.int64();break}case 4:{s.initiatedByMe=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.LimitSharing)return e;var a=new E.proto.LimitSharing;switch(e.sharingLimited!=null&&(a.sharingLimited=!!e.sharingLimited),e.trigger){default:if(typeof e.trigger=="number"){a.trigger=e.trigger;break}break;case"UNKNOWN":case 0:a.trigger=0;break;case"CHAT_SETTING":case 1:a.trigger=1;break;case"BIZ_SUPPORTS_FB_HOSTING":case 2:a.trigger=2;break;case"UNKNOWN_GROUP":case 3:a.trigger=3;break}return e.limitSharingSettingTimestamp!=null&&(I.Long?(a.limitSharingSettingTimestamp=I.Long.fromValue(e.limitSharingSettingTimestamp)).unsigned=!1:typeof e.limitSharingSettingTimestamp=="string"?a.limitSharingSettingTimestamp=parseInt(e.limitSharingSettingTimestamp,10):typeof e.limitSharingSettingTimestamp=="number"?a.limitSharingSettingTimestamp=e.limitSharingSettingTimestamp:typeof e.limitSharingSettingTimestamp=="object"&&(a.limitSharingSettingTimestamp=new I.LongBits(e.limitSharingSettingTimestamp.low>>>0,e.limitSharingSettingTimestamp.high>>>0).toNumber())),e.initiatedByMe!=null&&(a.initiatedByMe=!!e.initiatedByMe),a},r.toObject=function(e,a){a||(a={});var A={};return e.sharingLimited!=null&&e.hasOwnProperty("sharingLimited")&&(A.sharingLimited=e.sharingLimited,a.oneofs&&(A._sharingLimited="sharingLimited")),e.trigger!=null&&e.hasOwnProperty("trigger")&&(A.trigger=a.enums===String?E.proto.LimitSharing.TriggerType[e.trigger]===void 0?e.trigger:E.proto.LimitSharing.TriggerType[e.trigger]:e.trigger,a.oneofs&&(A._trigger="trigger")),e.limitSharingSettingTimestamp!=null&&e.hasOwnProperty("limitSharingSettingTimestamp")&&(typeof e.limitSharingSettingTimestamp=="number"?A.limitSharingSettingTimestamp=a.longs===String?String(e.limitSharingSettingTimestamp):e.limitSharingSettingTimestamp:A.limitSharingSettingTimestamp=a.longs===String?re(e.limitSharingSettingTimestamp):a.longs===Number?ae(e.limitSharingSettingTimestamp):e.limitSharingSettingTimestamp,a.oneofs&&(A._limitSharingSettingTimestamp="limitSharingSettingTimestamp")),e.initiatedByMe!=null&&e.hasOwnProperty("initiatedByMe")&&(A.initiatedByMe=e.initiatedByMe,a.oneofs&&(A._initiatedByMe="initiatedByMe")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LimitSharing"},r.TriggerType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT_SETTING"]=1,e[i[2]="BIZ_SUPPORTS_FB_HOSTING"]=2,e[i[3]="UNKNOWN_GROUP"]=3,e})(),r})(),n.LocalizedName=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lg=e.string();break}case 2:{s.lc=e.string();break}case 3:{s.verifiedName=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.LocalizedName)return e;var a=new E.proto.LocalizedName;return e.lg!=null&&(a.lg=String(e.lg)),e.lc!=null&&(a.lc=String(e.lc)),e.verifiedName!=null&&(a.verifiedName=String(e.verifiedName)),a},r.toObject=function(e,a){a||(a={});var A={};return e.lg!=null&&e.hasOwnProperty("lg")&&(A.lg=e.lg,a.oneofs&&(A._lg="lg")),e.lc!=null&&e.hasOwnProperty("lc")&&(A.lc=e.lc,a.oneofs&&(A._lc="lc")),e.verifiedName!=null&&e.hasOwnProperty("verifiedName")&&(A.verifiedName=e.verifiedName,a.oneofs&&(A._verifiedName="verifiedName")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LocalizedName"},r})(),n.Location=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.degreesLatitude=e.double();break}case 2:{s.degreesLongitude=e.double();break}case 3:{s.name=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Location)return e;var a=new E.proto.Location;return e.degreesLatitude!=null&&(a.degreesLatitude=Number(e.degreesLatitude)),e.degreesLongitude!=null&&(a.degreesLongitude=Number(e.degreesLongitude)),e.name!=null&&(a.name=String(e.name)),a},r.toObject=function(e,a){a||(a={});var A={};return e.degreesLatitude!=null&&e.hasOwnProperty("degreesLatitude")&&(A.degreesLatitude=a.json&&!isFinite(e.degreesLatitude)?String(e.degreesLatitude):e.degreesLatitude,a.oneofs&&(A._degreesLatitude="degreesLatitude")),e.degreesLongitude!=null&&e.hasOwnProperty("degreesLongitude")&&(A.degreesLongitude=a.json&&!isFinite(e.degreesLongitude)?String(e.degreesLongitude):e.degreesLongitude,a.oneofs&&(A._degreesLongitude="degreesLongitude")),e.name!=null&&e.hasOwnProperty("name")&&(A.name=e.name,a.oneofs&&(A._name="name")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Location"},r})(),n.MediaData=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.localPath=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MediaData)return e;var a=new E.proto.MediaData;return e.localPath!=null&&(a.localPath=String(e.localPath)),a},r.toObject=function(e,a){a||(a={});var A={};return e.localPath!=null&&e.hasOwnProperty("localPath")&&(A.localPath=e.localPath,a.oneofs&&(A._localPath="localPath")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaData"},r})(),n.MediaNotifyMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.expressPathUrl=e.string();break}case 2:{s.fileEncSha256=e.bytes();break}case 3:{s.fileLength=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MediaNotifyMessage)return e;var a=new E.proto.MediaNotifyMessage;return e.expressPathUrl!=null&&(a.expressPathUrl=String(e.expressPathUrl)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?I.base64.decode(e.fileEncSha256,a.fileEncSha256=I.newBuffer(I.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),e.fileLength!=null&&(I.Long?(a.fileLength=I.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new I.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};return e.expressPathUrl!=null&&e.hasOwnProperty("expressPathUrl")&&(A.expressPathUrl=e.expressPathUrl,a.oneofs&&(A._expressPathUrl="expressPathUrl")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?I.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?re(e.fileLength,!0):a.longs===Number?ae(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaNotifyMessage"},r})(),n.MediaRetryNotification=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.directPath=e.string();break}case 3:{s.result=e.int32();break}case 4:{s.messageSecret=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MediaRetryNotification)return e;var a=new E.proto.MediaRetryNotification;switch(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.result){default:if(typeof e.result=="number"){a.result=e.result;break}break;case"GENERAL_ERROR":case 0:a.result=0;break;case"SUCCESS":case 1:a.result=1;break;case"NOT_FOUND":case 2:a.result=2;break;case"DECRYPTION_ERROR":case 3:a.result=3;break}return e.messageSecret!=null&&(typeof e.messageSecret=="string"?I.base64.decode(e.messageSecret,a.messageSecret=I.newBuffer(I.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),a},r.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.result!=null&&e.hasOwnProperty("result")&&(A.result=a.enums===String?E.proto.MediaRetryNotification.ResultType[e.result]===void 0?e.result:E.proto.MediaRetryNotification.ResultType[e.result]:e.result,a.oneofs&&(A._result="result")),e.messageSecret!=null&&e.hasOwnProperty("messageSecret")&&(A.messageSecret=a.bytes===String?I.base64.encode(e.messageSecret,0,e.messageSecret.length):a.bytes===Array?Array.prototype.slice.call(e.messageSecret):e.messageSecret,a.oneofs&&(A._messageSecret="messageSecret")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaRetryNotification"},r.ResultType=(function(){let i={},e=Object.create(i);return e[i[0]="GENERAL_ERROR"]=0,e[i[1]="SUCCESS"]=1,e[i[2]="NOT_FOUND"]=2,e[i[3]="DECRYPTION_ERROR"]=3,e})(),r})(),n.MediaVisibility=(function(){let r={},o=Object.create(r);return o[r[0]="DEFAULT"]=0,o[r[1]="OFF"]=1,o[r[2]="ON"]=2,o})(),n.MemberLabel=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.label=e.string();break}case 2:{s.labelTimestamp=e.int64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MemberLabel)return e;var a=new E.proto.MemberLabel;return e.label!=null&&(a.label=String(e.label)),e.labelTimestamp!=null&&(I.Long?(a.labelTimestamp=I.Long.fromValue(e.labelTimestamp)).unsigned=!1:typeof e.labelTimestamp=="string"?a.labelTimestamp=parseInt(e.labelTimestamp,10):typeof e.labelTimestamp=="number"?a.labelTimestamp=e.labelTimestamp:typeof e.labelTimestamp=="object"&&(a.labelTimestamp=new I.LongBits(e.labelTimestamp.low>>>0,e.labelTimestamp.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.label!=null&&e.hasOwnProperty("label")&&(A.label=e.label,a.oneofs&&(A._label="label")),e.labelTimestamp!=null&&e.hasOwnProperty("labelTimestamp")&&(typeof e.labelTimestamp=="number"?A.labelTimestamp=a.longs===String?String(e.labelTimestamp):e.labelTimestamp:A.labelTimestamp=a.longs===String?re(e.labelTimestamp):a.longs===Number?ae(e.labelTimestamp):e.labelTimestamp,a.oneofs&&(A._labelTimestamp="labelTimestamp")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MemberLabel"},r})(),n.Message=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.conversation=e.string();break}case 2:{s.senderKeyDistributionMessage=E.proto.Message.SenderKeyDistributionMessage.decode(e,e.uint32());break}case 3:{s.imageMessage=E.proto.Message.ImageMessage.decode(e,e.uint32());break}case 4:{s.contactMessage=E.proto.Message.ContactMessage.decode(e,e.uint32());break}case 5:{s.locationMessage=E.proto.Message.LocationMessage.decode(e,e.uint32());break}case 6:{s.extendedTextMessage=E.proto.Message.ExtendedTextMessage.decode(e,e.uint32());break}case 7:{s.documentMessage=E.proto.Message.DocumentMessage.decode(e,e.uint32());break}case 8:{s.audioMessage=E.proto.Message.AudioMessage.decode(e,e.uint32());break}case 9:{s.videoMessage=E.proto.Message.VideoMessage.decode(e,e.uint32());break}case 10:{s.call=E.proto.Message.Call.decode(e,e.uint32());break}case 11:{s.chat=E.proto.Message.Chat.decode(e,e.uint32());break}case 12:{s.protocolMessage=E.proto.Message.ProtocolMessage.decode(e,e.uint32());break}case 13:{s.contactsArrayMessage=E.proto.Message.ContactsArrayMessage.decode(e,e.uint32());break}case 14:{s.highlyStructuredMessage=E.proto.Message.HighlyStructuredMessage.decode(e,e.uint32());break}case 15:{s.fastRatchetKeySenderKeyDistributionMessage=E.proto.Message.SenderKeyDistributionMessage.decode(e,e.uint32());break}case 16:{s.sendPaymentMessage=E.proto.Message.SendPaymentMessage.decode(e,e.uint32());break}case 18:{s.liveLocationMessage=E.proto.Message.LiveLocationMessage.decode(e,e.uint32());break}case 22:{s.requestPaymentMessage=E.proto.Message.RequestPaymentMessage.decode(e,e.uint32());break}case 23:{s.declinePaymentRequestMessage=E.proto.Message.DeclinePaymentRequestMessage.decode(e,e.uint32());break}case 24:{s.cancelPaymentRequestMessage=E.proto.Message.CancelPaymentRequestMessage.decode(e,e.uint32());break}case 25:{s.templateMessage=E.proto.Message.TemplateMessage.decode(e,e.uint32());break}case 26:{s.stickerMessage=E.proto.Message.StickerMessage.decode(e,e.uint32());break}case 28:{s.groupInviteMessage=E.proto.Message.GroupInviteMessage.decode(e,e.uint32());break}case 29:{s.templateButtonReplyMessage=E.proto.Message.TemplateButtonReplyMessage.decode(e,e.uint32());break}case 30:{s.productMessage=E.proto.Message.ProductMessage.decode(e,e.uint32());break}case 31:{s.deviceSentMessage=E.proto.Message.DeviceSentMessage.decode(e,e.uint32());break}case 35:{s.messageContextInfo=E.proto.MessageContextInfo.decode(e,e.uint32());break}case 36:{s.listMessage=E.proto.Message.ListMessage.decode(e,e.uint32());break}case 37:{s.viewOnceMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 38:{s.orderMessage=E.proto.Message.OrderMessage.decode(e,e.uint32());break}case 39:{s.listResponseMessage=E.proto.Message.ListResponseMessage.decode(e,e.uint32());break}case 40:{s.ephemeralMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 41:{s.invoiceMessage=E.proto.Message.InvoiceMessage.decode(e,e.uint32());break}case 42:{s.buttonsMessage=E.proto.Message.ButtonsMessage.decode(e,e.uint32());break}case 43:{s.buttonsResponseMessage=E.proto.Message.ButtonsResponseMessage.decode(e,e.uint32());break}case 44:{s.paymentInviteMessage=E.proto.Message.PaymentInviteMessage.decode(e,e.uint32());break}case 45:{s.interactiveMessage=E.proto.Message.InteractiveMessage.decode(e,e.uint32());break}case 46:{s.reactionMessage=E.proto.Message.ReactionMessage.decode(e,e.uint32());break}case 47:{s.stickerSyncRmrMessage=E.proto.Message.StickerSyncRMRMessage.decode(e,e.uint32());break}case 48:{s.interactiveResponseMessage=E.proto.Message.InteractiveResponseMessage.decode(e,e.uint32());break}case 49:{s.pollCreationMessage=E.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 50:{s.pollUpdateMessage=E.proto.Message.PollUpdateMessage.decode(e,e.uint32());break}case 51:{s.keepInChatMessage=E.proto.Message.KeepInChatMessage.decode(e,e.uint32());break}case 53:{s.documentWithCaptionMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 54:{s.requestPhoneNumberMessage=E.proto.Message.RequestPhoneNumberMessage.decode(e,e.uint32());break}case 55:{s.viewOnceMessageV2=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 56:{s.encReactionMessage=E.proto.Message.EncReactionMessage.decode(e,e.uint32());break}case 58:{s.editedMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 59:{s.viewOnceMessageV2Extension=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 60:{s.pollCreationMessageV2=E.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 61:{s.scheduledCallCreationMessage=E.proto.Message.ScheduledCallCreationMessage.decode(e,e.uint32());break}case 62:{s.groupMentionedMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 63:{s.pinInChatMessage=E.proto.Message.PinInChatMessage.decode(e,e.uint32());break}case 64:{s.pollCreationMessageV3=E.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 65:{s.scheduledCallEditMessage=E.proto.Message.ScheduledCallEditMessage.decode(e,e.uint32());break}case 66:{s.ptvMessage=E.proto.Message.VideoMessage.decode(e,e.uint32());break}case 67:{s.botInvokeMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 69:{s.callLogMesssage=E.proto.Message.CallLogMessage.decode(e,e.uint32());break}case 70:{s.messageHistoryBundle=E.proto.Message.MessageHistoryBundle.decode(e,e.uint32());break}case 71:{s.encCommentMessage=E.proto.Message.EncCommentMessage.decode(e,e.uint32());break}case 72:{s.bcallMessage=E.proto.Message.BCallMessage.decode(e,e.uint32());break}case 74:{s.lottieStickerMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 75:{s.eventMessage=E.proto.Message.EventMessage.decode(e,e.uint32());break}case 76:{s.encEventResponseMessage=E.proto.Message.EncEventResponseMessage.decode(e,e.uint32());break}case 77:{s.commentMessage=E.proto.Message.CommentMessage.decode(e,e.uint32());break}case 78:{s.newsletterAdminInviteMessage=E.proto.Message.NewsletterAdminInviteMessage.decode(e,e.uint32());break}case 80:{s.placeholderMessage=E.proto.Message.PlaceholderMessage.decode(e,e.uint32());break}case 82:{s.secretEncryptedMessage=E.proto.Message.SecretEncryptedMessage.decode(e,e.uint32());break}case 83:{s.albumMessage=E.proto.Message.AlbumMessage.decode(e,e.uint32());break}case 85:{s.eventCoverImage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 86:{s.stickerPackMessage=E.proto.Message.StickerPackMessage.decode(e,e.uint32());break}case 87:{s.statusMentionMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 88:{s.pollResultSnapshotMessage=E.proto.Message.PollResultSnapshotMessage.decode(e,e.uint32());break}case 90:{s.pollCreationOptionImageMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 91:{s.associatedChildMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 92:{s.groupStatusMentionMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 93:{s.pollCreationMessageV4=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 95:{s.statusAddYours=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 96:{s.groupStatusMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 97:{s.richResponseMessage=E.proto.AIRichResponseMessage.decode(e,e.uint32());break}case 98:{s.statusNotificationMessage=E.proto.Message.StatusNotificationMessage.decode(e,e.uint32());break}case 99:{s.limitSharingMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 100:{s.botTaskMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 101:{s.questionMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 102:{s.messageHistoryNotice=E.proto.Message.MessageHistoryNotice.decode(e,e.uint32());break}case 103:{s.groupStatusMessageV2=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 104:{s.botForwardedMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 105:{s.statusQuestionAnswerMessage=E.proto.Message.StatusQuestionAnswerMessage.decode(e,e.uint32());break}case 106:{s.questionReplyMessage=E.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 107:{s.questionResponseMessage=E.proto.Message.QuestionResponseMessage.decode(e,e.uint32());break}case 109:{s.statusQuotedMessage=E.proto.Message.StatusQuotedMessage.decode(e,e.uint32());break}case 110:{s.statusStickerInteractionMessage=E.proto.Message.StatusStickerInteractionMessage.decode(e,e.uint32());break}case 111:{s.pollCreationMessageV5=E.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 113:{s.newsletterFollowerInviteMessageV2=E.proto.Message.NewsletterFollowerInviteMessage.decode(e,e.uint32());break}case 114:{s.pollResultSnapshotMessageV3=E.proto.Message.PollResultSnapshotMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Message)return e;var a=new E.proto.Message;if(e.conversation!=null&&(a.conversation=String(e.conversation)),e.senderKeyDistributionMessage!=null){if(typeof e.senderKeyDistributionMessage!="object")throw TypeError(".proto.Message.senderKeyDistributionMessage: object expected");a.senderKeyDistributionMessage=E.proto.Message.SenderKeyDistributionMessage.fromObject(e.senderKeyDistributionMessage)}if(e.imageMessage!=null){if(typeof e.imageMessage!="object")throw TypeError(".proto.Message.imageMessage: object expected");a.imageMessage=E.proto.Message.ImageMessage.fromObject(e.imageMessage)}if(e.contactMessage!=null){if(typeof e.contactMessage!="object")throw TypeError(".proto.Message.contactMessage: object expected");a.contactMessage=E.proto.Message.ContactMessage.fromObject(e.contactMessage)}if(e.locationMessage!=null){if(typeof e.locationMessage!="object")throw TypeError(".proto.Message.locationMessage: object expected");a.locationMessage=E.proto.Message.LocationMessage.fromObject(e.locationMessage)}if(e.extendedTextMessage!=null){if(typeof e.extendedTextMessage!="object")throw TypeError(".proto.Message.extendedTextMessage: object expected");a.extendedTextMessage=E.proto.Message.ExtendedTextMessage.fromObject(e.extendedTextMessage)}if(e.documentMessage!=null){if(typeof e.documentMessage!="object")throw TypeError(".proto.Message.documentMessage: object expected");a.documentMessage=E.proto.Message.DocumentMessage.fromObject(e.documentMessage)}if(e.audioMessage!=null){if(typeof e.audioMessage!="object")throw TypeError(".proto.Message.audioMessage: object expected");a.audioMessage=E.proto.Message.AudioMessage.fromObject(e.audioMessage)}if(e.videoMessage!=null){if(typeof e.videoMessage!="object")throw TypeError(".proto.Message.videoMessage: object expected");a.videoMessage=E.proto.Message.VideoMessage.fromObject(e.videoMessage)}if(e.call!=null){if(typeof e.call!="object")throw TypeError(".proto.Message.call: object expected");a.call=E.proto.Message.Call.fromObject(e.call)}if(e.chat!=null){if(typeof e.chat!="object")throw TypeError(".proto.Message.chat: object expected");a.chat=E.proto.Message.Chat.fromObject(e.chat)}if(e.protocolMessage!=null){if(typeof e.protocolMessage!="object")throw TypeError(".proto.Message.protocolMessage: object expected");a.protocolMessage=E.proto.Message.ProtocolMessage.fromObject(e.protocolMessage)}if(e.contactsArrayMessage!=null){if(typeof e.contactsArrayMessage!="object")throw TypeError(".proto.Message.contactsArrayMessage: object expected");a.contactsArrayMessage=E.proto.Message.ContactsArrayMessage.fromObject(e.contactsArrayMessage)}if(e.highlyStructuredMessage!=null){if(typeof e.highlyStructuredMessage!="object")throw TypeError(".proto.Message.highlyStructuredMessage: object expected");a.highlyStructuredMessage=E.proto.Message.HighlyStructuredMessage.fromObject(e.highlyStructuredMessage)}if(e.fastRatchetKeySenderKeyDistributionMessage!=null){if(typeof e.fastRatchetKeySenderKeyDistributionMessage!="object")throw TypeError(".proto.Message.fastRatchetKeySenderKeyDistributionMessage: object expected");a.fastRatchetKeySenderKeyDistributionMessage=E.proto.Message.SenderKeyDistributionMessage.fromObject(e.fastRatchetKeySenderKeyDistributionMessage)}if(e.sendPaymentMessage!=null){if(typeof e.sendPaymentMessage!="object")throw TypeError(".proto.Message.sendPaymentMessage: object expected");a.sendPaymentMessage=E.proto.Message.SendPaymentMessage.fromObject(e.sendPaymentMessage)}if(e.liveLocationMessage!=null){if(typeof e.liveLocationMessage!="object")throw TypeError(".proto.Message.liveLocationMessage: object expected");a.liveLocationMessage=E.proto.Message.LiveLocationMessage.fromObject(e.liveLocationMessage)}if(e.requestPaymentMessage!=null){if(typeof e.requestPaymentMessage!="object")throw TypeError(".proto.Message.requestPaymentMessage: object expected");a.requestPaymentMessage=E.proto.Message.RequestPaymentMessage.fromObject(e.requestPaymentMessage)}if(e.declinePaymentRequestMessage!=null){if(typeof e.declinePaymentRequestMessage!="object")throw TypeError(".proto.Message.declinePaymentRequestMessage: object expected");a.declinePaymentRequestMessage=E.proto.Message.DeclinePaymentRequestMessage.fromObject(e.declinePaymentRequestMessage)}if(e.cancelPaymentRequestMessage!=null){if(typeof e.cancelPaymentRequestMessage!="object")throw TypeError(".proto.Message.cancelPaymentRequestMessage: object expected");a.cancelPaymentRequestMessage=E.proto.Message.CancelPaymentRequestMessage.fromObject(e.cancelPaymentRequestMessage)}if(e.templateMessage!=null){if(typeof e.templateMessage!="object")throw TypeError(".proto.Message.templateMessage: object expected");a.templateMessage=E.proto.Message.TemplateMessage.fromObject(e.templateMessage)}if(e.stickerMessage!=null){if(typeof e.stickerMessage!="object")throw TypeError(".proto.Message.stickerMessage: object expected");a.stickerMessage=E.proto.Message.StickerMessage.fromObject(e.stickerMessage)}if(e.groupInviteMessage!=null){if(typeof e.groupInviteMessage!="object")throw TypeError(".proto.Message.groupInviteMessage: object expected");a.groupInviteMessage=E.proto.Message.GroupInviteMessage.fromObject(e.groupInviteMessage)}if(e.templateButtonReplyMessage!=null){if(typeof e.templateButtonReplyMessage!="object")throw TypeError(".proto.Message.templateButtonReplyMessage: object expected");a.templateButtonReplyMessage=E.proto.Message.TemplateButtonReplyMessage.fromObject(e.templateButtonReplyMessage)}if(e.productMessage!=null){if(typeof e.productMessage!="object")throw TypeError(".proto.Message.productMessage: object expected");a.productMessage=E.proto.Message.ProductMessage.fromObject(e.productMessage)}if(e.deviceSentMessage!=null){if(typeof e.deviceSentMessage!="object")throw TypeError(".proto.Message.deviceSentMessage: object expected");a.deviceSentMessage=E.proto.Message.DeviceSentMessage.fromObject(e.deviceSentMessage)}if(e.messageContextInfo!=null){if(typeof e.messageContextInfo!="object")throw TypeError(".proto.Message.messageContextInfo: object expected");a.messageContextInfo=E.proto.MessageContextInfo.fromObject(e.messageContextInfo)}if(e.listMessage!=null){if(typeof e.listMessage!="object")throw TypeError(".proto.Message.listMessage: object expected");a.listMessage=E.proto.Message.ListMessage.fromObject(e.listMessage)}if(e.viewOnceMessage!=null){if(typeof e.viewOnceMessage!="object")throw TypeError(".proto.Message.viewOnceMessage: object expected");a.viewOnceMessage=E.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessage)}if(e.orderMessage!=null){if(typeof e.orderMessage!="object")throw TypeError(".proto.Message.orderMessage: object expected");a.orderMessage=E.proto.Message.OrderMessage.fromObject(e.orderMessage)}if(e.listResponseMessage!=null){if(typeof e.listResponseMessage!="object")throw TypeError(".proto.Message.listResponseMessage: object expected");a.listResponseMessage=E.proto.Message.ListResponseMessage.fromObject(e.listResponseMessage)}if(e.ephemeralMessage!=null){if(typeof e.ephemeralMessage!="object")throw TypeError(".proto.Message.ephemeralMessage: object expected");a.ephemeralMessage=E.proto.Message.FutureProofMessage.fromObject(e.ephemeralMessage)}if(e.invoiceMessage!=null){if(typeof e.invoiceMessage!="object")throw TypeError(".proto.Message.invoiceMessage: object expected");a.invoiceMessage=E.proto.Message.InvoiceMessage.fromObject(e.invoiceMessage)}if(e.buttonsMessage!=null){if(typeof e.buttonsMessage!="object")throw TypeError(".proto.Message.buttonsMessage: object expected");a.buttonsMessage=E.proto.Message.ButtonsMessage.fromObject(e.buttonsMessage)}if(e.buttonsResponseMessage!=null){if(typeof e.buttonsResponseMessage!="object")throw TypeError(".proto.Message.buttonsResponseMessage: object expected");a.buttonsResponseMessage=E.proto.Message.ButtonsResponseMessage.fromObject(e.buttonsResponseMessage)}if(e.paymentInviteMessage!=null){if(typeof e.paymentInviteMessage!="object")throw TypeError(".proto.Message.paymentInviteMessage: object expected");a.paymentInviteMessage=E.proto.Message.PaymentInviteMessage.fromObject(e.paymentInviteMessage)}if(e.interactiveMessage!=null){if(typeof e.interactiveMessage!="object")throw TypeError(".proto.Message.interactiveMessage: object expected");a.interactiveMessage=E.proto.Message.InteractiveMessage.fromObject(e.interactiveMessage)}if(e.reactionMessage!=null){if(typeof e.reactionMessage!="object")throw TypeError(".proto.Message.reactionMessage: object expected");a.reactionMessage=E.proto.Message.ReactionMessage.fromObject(e.reactionMessage)}if(e.stickerSyncRmrMessage!=null){if(typeof e.stickerSyncRmrMessage!="object")throw TypeError(".proto.Message.stickerSyncRmrMessage: object expected");a.stickerSyncRmrMessage=E.proto.Message.StickerSyncRMRMessage.fromObject(e.stickerSyncRmrMessage)}if(e.interactiveResponseMessage!=null){if(typeof e.interactiveResponseMessage!="object")throw TypeError(".proto.Message.interactiveResponseMessage: object expected");a.interactiveResponseMessage=E.proto.Message.InteractiveResponseMessage.fromObject(e.interactiveResponseMessage)}if(e.pollCreationMessage!=null){if(typeof e.pollCreationMessage!="object")throw TypeError(".proto.Message.pollCreationMessage: object expected");a.pollCreationMessage=E.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessage)}if(e.pollUpdateMessage!=null){if(typeof e.pollUpdateMessage!="object")throw TypeError(".proto.Message.pollUpdateMessage: object expected");a.pollUpdateMessage=E.proto.Message.PollUpdateMessage.fromObject(e.pollUpdateMessage)}if(e.keepInChatMessage!=null){if(typeof e.keepInChatMessage!="object")throw TypeError(".proto.Message.keepInChatMessage: object expected");a.keepInChatMessage=E.proto.Message.KeepInChatMessage.fromObject(e.keepInChatMessage)}if(e.documentWithCaptionMessage!=null){if(typeof e.documentWithCaptionMessage!="object")throw TypeError(".proto.Message.documentWithCaptionMessage: object expected");a.documentWithCaptionMessage=E.proto.Message.FutureProofMessage.fromObject(e.documentWithCaptionMessage)}if(e.requestPhoneNumberMessage!=null){if(typeof e.requestPhoneNumberMessage!="object")throw TypeError(".proto.Message.requestPhoneNumberMessage: object expected");a.requestPhoneNumberMessage=E.proto.Message.RequestPhoneNumberMessage.fromObject(e.requestPhoneNumberMessage)}if(e.viewOnceMessageV2!=null){if(typeof e.viewOnceMessageV2!="object")throw TypeError(".proto.Message.viewOnceMessageV2: object expected");a.viewOnceMessageV2=E.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessageV2)}if(e.encReactionMessage!=null){if(typeof e.encReactionMessage!="object")throw TypeError(".proto.Message.encReactionMessage: object expected");a.encReactionMessage=E.proto.Message.EncReactionMessage.fromObject(e.encReactionMessage)}if(e.editedMessage!=null){if(typeof e.editedMessage!="object")throw TypeError(".proto.Message.editedMessage: object expected");a.editedMessage=E.proto.Message.FutureProofMessage.fromObject(e.editedMessage)}if(e.viewOnceMessageV2Extension!=null){if(typeof e.viewOnceMessageV2Extension!="object")throw TypeError(".proto.Message.viewOnceMessageV2Extension: object expected");a.viewOnceMessageV2Extension=E.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessageV2Extension)}if(e.pollCreationMessageV2!=null){if(typeof e.pollCreationMessageV2!="object")throw TypeError(".proto.Message.pollCreationMessageV2: object expected");a.pollCreationMessageV2=E.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV2)}if(e.scheduledCallCreationMessage!=null){if(typeof e.scheduledCallCreationMessage!="object")throw TypeError(".proto.Message.scheduledCallCreationMessage: object expected");a.scheduledCallCreationMessage=E.proto.Message.ScheduledCallCreationMessage.fromObject(e.scheduledCallCreationMessage)}if(e.groupMentionedMessage!=null){if(typeof e.groupMentionedMessage!="object")throw TypeError(".proto.Message.groupMentionedMessage: object expected");a.groupMentionedMessage=E.proto.Message.FutureProofMessage.fromObject(e.groupMentionedMessage)}if(e.pinInChatMessage!=null){if(typeof e.pinInChatMessage!="object")throw TypeError(".proto.Message.pinInChatMessage: object expected");a.pinInChatMessage=E.proto.Message.PinInChatMessage.fromObject(e.pinInChatMessage)}if(e.pollCreationMessageV3!=null){if(typeof e.pollCreationMessageV3!="object")throw TypeError(".proto.Message.pollCreationMessageV3: object expected");a.pollCreationMessageV3=E.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV3)}if(e.scheduledCallEditMessage!=null){if(typeof e.scheduledCallEditMessage!="object")throw TypeError(".proto.Message.scheduledCallEditMessage: object expected");a.scheduledCallEditMessage=E.proto.Message.ScheduledCallEditMessage.fromObject(e.scheduledCallEditMessage)}if(e.ptvMessage!=null){if(typeof e.ptvMessage!="object")throw TypeError(".proto.Message.ptvMessage: object expected");a.ptvMessage=E.proto.Message.VideoMessage.fromObject(e.ptvMessage)}if(e.botInvokeMessage!=null){if(typeof e.botInvokeMessage!="object")throw TypeError(".proto.Message.botInvokeMessage: object expected");a.botInvokeMessage=E.proto.Message.FutureProofMessage.fromObject(e.botInvokeMessage)}if(e.callLogMesssage!=null){if(typeof e.callLogMesssage!="object")throw TypeError(".proto.Message.callLogMesssage: object expected");a.callLogMesssage=E.proto.Message.CallLogMessage.fromObject(e.callLogMesssage)}if(e.messageHistoryBundle!=null){if(typeof e.messageHistoryBundle!="object")throw TypeError(".proto.Message.messageHistoryBundle: object expected");a.messageHistoryBundle=E.proto.Message.MessageHistoryBundle.fromObject(e.messageHistoryBundle)}if(e.encCommentMessage!=null){if(typeof e.encCommentMessage!="object")throw TypeError(".proto.Message.encCommentMessage: object expected");a.encCommentMessage=E.proto.Message.EncCommentMessage.fromObject(e.encCommentMessage)}if(e.bcallMessage!=null){if(typeof e.bcallMessage!="object")throw TypeError(".proto.Message.bcallMessage: object expected");a.bcallMessage=E.proto.Message.BCallMessage.fromObject(e.bcallMessage)}if(e.lottieStickerMessage!=null){if(typeof e.lottieStickerMessage!="object")throw TypeError(".proto.Message.lottieStickerMessage: object expected");a.lottieStickerMessage=E.proto.Message.FutureProofMessage.fromObject(e.lottieStickerMessage)}if(e.eventMessage!=null){if(typeof e.eventMessage!="object")throw TypeError(".proto.Message.eventMessage: object expected");a.eventMessage=E.proto.Message.EventMessage.fromObject(e.eventMessage)}if(e.encEventResponseMessage!=null){if(typeof e.encEventResponseMessage!="object")throw TypeError(".proto.Message.encEventResponseMessage: object expected");a.encEventResponseMessage=E.proto.Message.EncEventResponseMessage.fromObject(e.encEventResponseMessage)}if(e.commentMessage!=null){if(typeof e.commentMessage!="object")throw TypeError(".proto.Message.commentMessage: object expected");a.commentMessage=E.proto.Message.CommentMessage.fromObject(e.commentMessage)}if(e.newsletterAdminInviteMessage!=null){if(typeof e.newsletterAdminInviteMessage!="object")throw TypeError(".proto.Message.newsletterAdminInviteMessage: object expected");a.newsletterAdminInviteMessage=E.proto.Message.NewsletterAdminInviteMessage.fromObject(e.newsletterAdminInviteMessage)}if(e.placeholderMessage!=null){if(typeof e.placeholderMessage!="object")throw TypeError(".proto.Message.placeholderMessage: object expected");a.placeholderMessage=E.proto.Message.PlaceholderMessage.fromObject(e.placeholderMessage)}if(e.secretEncryptedMessage!=null){if(typeof e.secretEncryptedMessage!="object")throw TypeError(".proto.Message.secretEncryptedMessage: object expected");a.secretEncryptedMessage=E.proto.Message.SecretEncryptedMessage.fromObject(e.secretEncryptedMessage)}if(e.albumMessage!=null){if(typeof e.albumMessage!="object")throw TypeError(".proto.Message.albumMessage: object expected");a.albumMessage=E.proto.Message.AlbumMessage.fromObject(e.albumMessage)}if(e.eventCoverImage!=null){if(typeof e.eventCoverImage!="object")throw TypeError(".proto.Message.eventCoverImage: object expected");a.eventCoverImage=E.proto.Message.FutureProofMessage.fromObject(e.eventCoverImage)}if(e.stickerPackMessage!=null){if(typeof e.stickerPackMessage!="object")throw TypeError(".proto.Message.stickerPackMessage: object expected");a.stickerPackMessage=E.proto.Message.StickerPackMessage.fromObject(e.stickerPackMessage)}if(e.statusMentionMessage!=null){if(typeof e.statusMentionMessage!="object")throw TypeError(".proto.Message.statusMentionMessage: object expected");a.statusMentionMessage=E.proto.Message.FutureProofMessage.fromObject(e.statusMentionMessage)}if(e.pollResultSnapshotMessage!=null){if(typeof e.pollResultSnapshotMessage!="object")throw TypeError(".proto.Message.pollResultSnapshotMessage: object expected");a.pollResultSnapshotMessage=E.proto.Message.PollResultSnapshotMessage.fromObject(e.pollResultSnapshotMessage)}if(e.pollCreationOptionImageMessage!=null){if(typeof e.pollCreationOptionImageMessage!="object")throw TypeError(".proto.Message.pollCreationOptionImageMessage: object expected");a.pollCreationOptionImageMessage=E.proto.Message.FutureProofMessage.fromObject(e.pollCreationOptionImageMessage)}if(e.associatedChildMessage!=null){if(typeof e.associatedChildMessage!="object")throw TypeError(".proto.Message.associatedChildMessage: object expected");a.associatedChildMessage=E.proto.Message.FutureProofMessage.fromObject(e.associatedChildMessage)}if(e.groupStatusMentionMessage!=null){if(typeof e.groupStatusMentionMessage!="object")throw TypeError(".proto.Message.groupStatusMentionMessage: object expected");a.groupStatusMentionMessage=E.proto.Message.FutureProofMessage.fromObject(e.groupStatusMentionMessage)}if(e.pollCreationMessageV4!=null){if(typeof e.pollCreationMessageV4!="object")throw TypeError(".proto.Message.pollCreationMessageV4: object expected");a.pollCreationMessageV4=E.proto.Message.FutureProofMessage.fromObject(e.pollCreationMessageV4)}if(e.statusAddYours!=null){if(typeof e.statusAddYours!="object")throw TypeError(".proto.Message.statusAddYours: object expected");a.statusAddYours=E.proto.Message.FutureProofMessage.fromObject(e.statusAddYours)}if(e.groupStatusMessage!=null){if(typeof e.groupStatusMessage!="object")throw TypeError(".proto.Message.groupStatusMessage: object expected");a.groupStatusMessage=E.proto.Message.FutureProofMessage.fromObject(e.groupStatusMessage)}if(e.richResponseMessage!=null){if(typeof e.richResponseMessage!="object")throw TypeError(".proto.Message.richResponseMessage: object expected");a.richResponseMessage=E.proto.AIRichResponseMessage.fromObject(e.richResponseMessage)}if(e.statusNotificationMessage!=null){if(typeof e.statusNotificationMessage!="object")throw TypeError(".proto.Message.statusNotificationMessage: object expected");a.statusNotificationMessage=E.proto.Message.StatusNotificationMessage.fromObject(e.statusNotificationMessage)}if(e.limitSharingMessage!=null){if(typeof e.limitSharingMessage!="object")throw TypeError(".proto.Message.limitSharingMessage: object expected");a.limitSharingMessage=E.proto.Message.FutureProofMessage.fromObject(e.limitSharingMessage)}if(e.botTaskMessage!=null){if(typeof e.botTaskMessage!="object")throw TypeError(".proto.Message.botTaskMessage: object expected");a.botTaskMessage=E.proto.Message.FutureProofMessage.fromObject(e.botTaskMessage)}if(e.questionMessage!=null){if(typeof e.questionMessage!="object")throw TypeError(".proto.Message.questionMessage: object expected");a.questionMessage=E.proto.Message.FutureProofMessage.fromObject(e.questionMessage)}if(e.messageHistoryNotice!=null){if(typeof e.messageHistoryNotice!="object")throw TypeError(".proto.Message.messageHistoryNotice: object expected");a.messageHistoryNotice=E.proto.Message.MessageHistoryNotice.fromObject(e.messageHistoryNotice)}if(e.groupStatusMessageV2!=null){if(typeof e.groupStatusMessageV2!="object")throw TypeError(".proto.Message.groupStatusMessageV2: object expected");a.groupStatusMessageV2=E.proto.Message.FutureProofMessage.fromObject(e.groupStatusMessageV2)}if(e.botForwardedMessage!=null){if(typeof e.botForwardedMessage!="object")throw TypeError(".proto.Message.botForwardedMessage: object expected");a.botForwardedMessage=E.proto.Message.FutureProofMessage.fromObject(e.botForwardedMessage)}if(e.statusQuestionAnswerMessage!=null){if(typeof e.statusQuestionAnswerMessage!="object")throw TypeError(".proto.Message.statusQuestionAnswerMessage: object expected");a.statusQuestionAnswerMessage=E.proto.Message.StatusQuestionAnswerMessage.fromObject(e.statusQuestionAnswerMessage)}if(e.questionReplyMessage!=null){if(typeof e.questionReplyMessage!="object")throw TypeError(".proto.Message.questionReplyMessage: object expected");a.questionReplyMessage=E.proto.Message.FutureProofMessage.fromObject(e.questionReplyMessage)}if(e.questionResponseMessage!=null){if(typeof e.questionResponseMessage!="object")throw TypeError(".proto.Message.questionResponseMessage: object expected");a.questionResponseMessage=E.proto.Message.QuestionResponseMessage.fromObject(e.questionResponseMessage)}if(e.statusQuotedMessage!=null){if(typeof e.statusQuotedMessage!="object")throw TypeError(".proto.Message.statusQuotedMessage: object expected");a.statusQuotedMessage=E.proto.Message.StatusQuotedMessage.fromObject(e.statusQuotedMessage)}if(e.statusStickerInteractionMessage!=null){if(typeof e.statusStickerInteractionMessage!="object")throw TypeError(".proto.Message.statusStickerInteractionMessage: object expected");a.statusStickerInteractionMessage=E.proto.Message.StatusStickerInteractionMessage.fromObject(e.statusStickerInteractionMessage)}if(e.pollCreationMessageV5!=null){if(typeof e.pollCreationMessageV5!="object")throw TypeError(".proto.Message.pollCreationMessageV5: object expected");a.pollCreationMessageV5=E.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV5)}if(e.newsletterFollowerInviteMessageV2!=null){if(typeof e.newsletterFollowerInviteMessageV2!="object")throw TypeError(".proto.Message.newsletterFollowerInviteMessageV2: object expected");a.newsletterFollowerInviteMessageV2=E.proto.Message.NewsletterFollowerInviteMessage.fromObject(e.newsletterFollowerInviteMessageV2)}if(e.pollResultSnapshotMessageV3!=null){if(typeof e.pollResultSnapshotMessageV3!="object")throw TypeError(".proto.Message.pollResultSnapshotMessageV3: object expected");a.pollResultSnapshotMessageV3=E.proto.Message.PollResultSnapshotMessage.fromObject(e.pollResultSnapshotMessageV3)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.conversation!=null&&e.hasOwnProperty("conversation")&&(A.conversation=e.conversation,a.oneofs&&(A._conversation="conversation")),e.senderKeyDistributionMessage!=null&&e.hasOwnProperty("senderKeyDistributionMessage")&&(A.senderKeyDistributionMessage=E.proto.Message.SenderKeyDistributionMessage.toObject(e.senderKeyDistributionMessage,a),a.oneofs&&(A._senderKeyDistributionMessage="senderKeyDistributionMessage")),e.imageMessage!=null&&e.hasOwnProperty("imageMessage")&&(A.imageMessage=E.proto.Message.ImageMessage.toObject(e.imageMessage,a),a.oneofs&&(A._imageMessage="imageMessage")),e.contactMessage!=null&&e.hasOwnProperty("contactMessage")&&(A.contactMessage=E.proto.Message.ContactMessage.toObject(e.contactMessage,a),a.oneofs&&(A._contactMessage="contactMessage")),e.locationMessage!=null&&e.hasOwnProperty("locationMessage")&&(A.locationMessage=E.proto.Message.LocationMessage.toObject(e.locationMessage,a),a.oneofs&&(A._locationMessage="locationMessage")),e.extendedTextMessage!=null&&e.hasOwnProperty("extendedTextMessage")&&(A.extendedTextMessage=E.proto.Message.ExtendedTextMessage.toObject(e.extendedTextMessage,a),a.oneofs&&(A._extendedTextMessage="extendedTextMessage")),e.documentMessage!=null&&e.hasOwnProperty("documentMessage")&&(A.documentMessage=E.proto.Message.DocumentMessage.toObject(e.documentMessage,a),a.oneofs&&(A._documentMessage="documentMessage")),e.audioMessage!=null&&e.hasOwnProperty("audioMessage")&&(A.audioMessage=E.proto.Message.AudioMessage.toObject(e.audioMessage,a),a.oneofs&&(A._audioMessage="audioMessage")),e.videoMessage!=null&&e.hasOwnProperty("videoMessage")&&(A.videoMessage=E.proto.Message.VideoMessage.toObject(e.videoMessage,a),a.oneofs&&(A._videoMessage="videoMessage")),e.call!=null&&e.hasOwnProperty("call")&&(A.call=E.proto.Message.Call.toObject(e.call,a),a.oneofs&&(A._call="call")),e.chat!=null&&e.hasOwnProperty("chat")&&(A.chat=E.proto.Message.Chat.toObject(e.chat,a),a.oneofs&&(A._chat="chat")),e.protocolMessage!=null&&e.hasOwnProperty("protocolMessage")&&(A.protocolMessage=E.proto.Message.ProtocolMessage.toObject(e.protocolMessage,a),a.oneofs&&(A._protocolMessage="protocolMessage")),e.contactsArrayMessage!=null&&e.hasOwnProperty("contactsArrayMessage")&&(A.contactsArrayMessage=E.proto.Message.ContactsArrayMessage.toObject(e.contactsArrayMessage,a),a.oneofs&&(A._contactsArrayMessage="contactsArrayMessage")),e.highlyStructuredMessage!=null&&e.hasOwnProperty("highlyStructuredMessage")&&(A.highlyStructuredMessage=E.proto.Message.HighlyStructuredMessage.toObject(e.highlyStructuredMessage,a),a.oneofs&&(A._highlyStructuredMessage="highlyStructuredMessage")),e.fastRatchetKeySenderKeyDistributionMessage!=null&&e.hasOwnProperty("fastRatchetKeySenderKeyDistributionMessage")&&(A.fastRatchetKeySenderKeyDistributionMessage=E.proto.Message.SenderKeyDistributionMessage.toObject(e.fastRatchetKeySenderKeyDistributionMessage,a),a.oneofs&&(A._fastRatchetKeySenderKeyDistributionMessage="fastRatchetKeySenderKeyDistributionMessage")),e.sendPaymentMessage!=null&&e.hasOwnProperty("sendPaymentMessage")&&(A.sendPaymentMessage=E.proto.Message.SendPaymentMessage.toObject(e.sendPaymentMessage,a),a.oneofs&&(A._sendPaymentMessage="sendPaymentMessage")),e.liveLocationMessage!=null&&e.hasOwnProperty("liveLocationMessage")&&(A.liveLocationMessage=E.proto.Message.LiveLocationMessage.toObject(e.liveLocationMessage,a),a.oneofs&&(A._liveLocationMessage="liveLocationMessage")),e.requestPaymentMessage!=null&&e.hasOwnProperty("requestPaymentMessage")&&(A.requestPaymentMessage=E.proto.Message.RequestPaymentMessage.toObject(e.requestPaymentMessage,a),a.oneofs&&(A._requestPaymentMessage="requestPaymentMessage")),e.declinePaymentRequestMessage!=null&&e.hasOwnProperty("declinePaymentRequestMessage")&&(A.declinePaymentRequestMessage=E.proto.Message.DeclinePaymentRequestMessage.toObject(e.declinePaymentRequestMessage,a),a.oneofs&&(A._declinePaymentRequestMessage="declinePaymentRequestMessage")),e.cancelPaymentRequestMessage!=null&&e.hasOwnProperty("cancelPaymentRequestMessage")&&(A.cancelPaymentRequestMessage=E.proto.Message.CancelPaymentRequestMessage.toObject(e.cancelPaymentRequestMessage,a),a.oneofs&&(A._cancelPaymentRequestMessage="cancelPaymentRequestMessage")),e.templateMessage!=null&&e.hasOwnProperty("templateMessage")&&(A.templateMessage=E.proto.Message.TemplateMessage.toObject(e.templateMessage,a),a.oneofs&&(A._templateMessage="templateMessage")),e.stickerMessage!=null&&e.hasOwnProperty("stickerMessage")&&(A.stickerMessage=E.proto.Message.StickerMessage.toObject(e.stickerMessage,a),a.oneofs&&(A._stickerMessage="stickerMessage")),e.groupInviteMessage!=null&&e.hasOwnProperty("groupInviteMessage")&&(A.groupInviteMessage=E.proto.Message.GroupInviteMessage.toObject(e.groupInviteMessage,a),a.oneofs&&(A._groupInviteMessage="groupInviteMessage")),e.templateButtonReplyMessage!=null&&e.hasOwnProperty("templateButtonReplyMessage")&&(A.templateButtonReplyMessage=E.proto.Message.TemplateButtonReplyMessage.toObject(e.templateButtonReplyMessage,a),a.oneofs&&(A._templateButtonReplyMessage="templateButtonReplyMessage")),e.productMessage!=null&&e.hasOwnProperty("productMessage")&&(A.productMessage=E.proto.Message.ProductMessage.toObject(e.productMessage,a),a.oneofs&&(A._productMessage="productMessage")),e.deviceSentMessage!=null&&e.hasOwnProperty("deviceSentMessage")&&(A.deviceSentMessage=E.proto.Message.DeviceSentMessage.toObject(e.deviceSentMessage,a),a.oneofs&&(A._deviceSentMessage="deviceSentMessage")),e.messageContextInfo!=null&&e.hasOwnProperty("messageContextInfo")&&(A.messageContextInfo=E.proto.MessageContextInfo.toObject(e.messageContextInfo,a),a.oneofs&&(A._messageContextInfo="messageContextInfo")),e.listMessage!=null&&e.hasOwnProperty("listMessage")&&(A.listMessage=E.proto.Message.ListMessage.toObject(e.listMessage,a),a.oneofs&&(A._listMessage="listMessage")),e.viewOnceMessage!=null&&e.hasOwnProperty("viewOnceMessage")&&(A.viewOnceMessage=E.proto.Message.FutureProofMessage.toObject(e.viewOnceMessage,a),a.oneofs&&(A._viewOnceMessage="viewOnceMessage")),e.orderMessage!=null&&e.hasOwnProperty("orderMessage")&&(A.orderMessage=E.proto.Message.OrderMessage.toObject(e.orderMessage,a),a.oneofs&&(A._orderMessage="orderMessage")),e.listResponseMessage!=null&&e.hasOwnProperty("listResponseMessage")&&(A.listResponseMessage=E.proto.Message.ListResponseMessage.toObject(e.listResponseMessage,a),a.oneofs&&(A._listResponseMessage="listResponseMessage")),e.ephemeralMessage!=null&&e.hasOwnProperty("ephemeralMessage")&&(A.ephemeralMessage=E.proto.Message.FutureProofMessage.toObject(e.ephemeralMessage,a),a.oneofs&&(A._ephemeralMessage="ephemeralMessage")),e.invoiceMessage!=null&&e.hasOwnProperty("invoiceMessage")&&(A.invoiceMessage=E.proto.Message.InvoiceMessage.toObject(e.invoiceMessage,a),a.oneofs&&(A._invoiceMessage="invoiceMessage")),e.buttonsMessage!=null&&e.hasOwnProperty("buttonsMessage")&&(A.buttonsMessage=E.proto.Message.ButtonsMessage.toObject(e.buttonsMessage,a),a.oneofs&&(A._buttonsMessage="buttonsMessage")),e.buttonsResponseMessage!=null&&e.hasOwnProperty("buttonsResponseMessage")&&(A.buttonsResponseMessage=E.proto.Message.ButtonsResponseMessage.toObject(e.buttonsResponseMessage,a),a.oneofs&&(A._buttonsResponseMessage="buttonsResponseMessage")),e.paymentInviteMessage!=null&&e.hasOwnProperty("paymentInviteMessage")&&(A.paymentInviteMessage=E.proto.Message.PaymentInviteMessage.toObject(e.paymentInviteMessage,a),a.oneofs&&(A._paymentInviteMessage="paymentInviteMessage")),e.interactiveMessage!=null&&e.hasOwnProperty("interactiveMessage")&&(A.interactiveMessage=E.proto.Message.InteractiveMessage.toObject(e.interactiveMessage,a),a.oneofs&&(A._interactiveMessage="interactiveMessage")),e.reactionMessage!=null&&e.hasOwnProperty("reactionMessage")&&(A.reactionMessage=E.proto.Message.ReactionMessage.toObject(e.reactionMessage,a),a.oneofs&&(A._reactionMessage="reactionMessage")),e.stickerSyncRmrMessage!=null&&e.hasOwnProperty("stickerSyncRmrMessage")&&(A.stickerSyncRmrMessage=E.proto.Message.StickerSyncRMRMessage.toObject(e.stickerSyncRmrMessage,a),a.oneofs&&(A._stickerSyncRmrMessage="stickerSyncRmrMessage")),e.interactiveResponseMessage!=null&&e.hasOwnProperty("interactiveResponseMessage")&&(A.interactiveResponseMessage=E.proto.Message.InteractiveResponseMessage.toObject(e.interactiveResponseMessage,a),a.oneofs&&(A._interactiveResponseMessage="interactiveResponseMessage")),e.pollCreationMessage!=null&&e.hasOwnProperty("pollCreationMessage")&&(A.pollCreationMessage=E.proto.Message.PollCreationMessage.toObject(e.pollCreationMessage,a),a.oneofs&&(A._pollCreationMessage="pollCreationMessage")),e.pollUpdateMessage!=null&&e.hasOwnProperty("pollUpdateMessage")&&(A.pollUpdateMessage=E.proto.Message.PollUpdateMessage.toObject(e.pollUpdateMessage,a),a.oneofs&&(A._pollUpdateMessage="pollUpdateMessage")),e.keepInChatMessage!=null&&e.hasOwnProperty("keepInChatMessage")&&(A.keepInChatMessage=E.proto.Message.KeepInChatMessage.toObject(e.keepInChatMessage,a),a.oneofs&&(A._keepInChatMessage="keepInChatMessage")),e.documentWithCaptionMessage!=null&&e.hasOwnProperty("documentWithCaptionMessage")&&(A.documentWithCaptionMessage=E.proto.Message.FutureProofMessage.toObject(e.documentWithCaptionMessage,a),a.oneofs&&(A._documentWithCaptionMessage="documentWithCaptionMessage")),e.requestPhoneNumberMessage!=null&&e.hasOwnProperty("requestPhoneNumberMessage")&&(A.requestPhoneNumberMessage=E.proto.Message.RequestPhoneNumberMessage.toObject(e.requestPhoneNumberMessage,a),a.oneofs&&(A._requestPhoneNumberMessage="requestPhoneNumberMessage")),e.viewOnceMessageV2!=null&&e.hasOwnProperty("viewOnceMessageV2")&&(A.viewOnceMessageV2=E.proto.Message.FutureProofMessage.toObject(e.viewOnceMessageV2,a),a.oneofs&&(A._viewOnceMessageV2="viewOnceMessageV2")),e.encReactionMessage!=null&&e.hasOwnProperty("encReactionMessage")&&(A.encReactionMessage=E.proto.Message.EncReactionMessage.toObject(e.encReactionMessage,a),a.oneofs&&(A._encReactionMessage="encReactionMessage")),e.editedMessage!=null&&e.hasOwnProperty("editedMessage")&&(A.editedMessage=E.proto.Message.FutureProofMessage.toObject(e.editedMessage,a),a.oneofs&&(A._editedMessage="editedMessage")),e.viewOnceMessageV2Extension!=null&&e.hasOwnProperty("viewOnceMessageV2Extension")&&(A.viewOnceMessageV2Extension=E.proto.Message.FutureProofMessage.toObject(e.viewOnceMessageV2Extension,a),a.oneofs&&(A._viewOnceMessageV2Extension="viewOnceMessageV2Extension")),e.pollCreationMessageV2!=null&&e.hasOwnProperty("pollCreationMessageV2")&&(A.pollCreationMessageV2=E.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV2,a),a.oneofs&&(A._pollCreationMessageV2="pollCreationMessageV2")),e.scheduledCallCreationMessage!=null&&e.hasOwnProperty("scheduledCallCreationMessage")&&(A.scheduledCallCreationMessage=E.proto.Message.ScheduledCallCreationMessage.toObject(e.scheduledCallCreationMessage,a),a.oneofs&&(A._scheduledCallCreationMessage="scheduledCallCreationMessage")),e.groupMentionedMessage!=null&&e.hasOwnProperty("groupMentionedMessage")&&(A.groupMentionedMessage=E.proto.Message.FutureProofMessage.toObject(e.groupMentionedMessage,a),a.oneofs&&(A._groupMentionedMessage="groupMentionedMessage")),e.pinInChatMessage!=null&&e.hasOwnProperty("pinInChatMessage")&&(A.pinInChatMessage=E.proto.Message.PinInChatMessage.toObject(e.pinInChatMessage,a),a.oneofs&&(A._pinInChatMessage="pinInChatMessage")),e.pollCreationMessageV3!=null&&e.hasOwnProperty("pollCreationMessageV3")&&(A.pollCreationMessageV3=E.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV3,a),a.oneofs&&(A._pollCreationMessageV3="pollCreationMessageV3")),e.scheduledCallEditMessage!=null&&e.hasOwnProperty("scheduledCallEditMessage")&&(A.scheduledCallEditMessage=E.proto.Message.ScheduledCallEditMessage.toObject(e.scheduledCallEditMessage,a),a.oneofs&&(A._scheduledCallEditMessage="scheduledCallEditMessage")),e.ptvMessage!=null&&e.hasOwnProperty("ptvMessage")&&(A.ptvMessage=E.proto.Message.VideoMessage.toObject(e.ptvMessage,a),a.oneofs&&(A._ptvMessage="ptvMessage")),e.botInvokeMessage!=null&&e.hasOwnProperty("botInvokeMessage")&&(A.botInvokeMessage=E.proto.Message.FutureProofMessage.toObject(e.botInvokeMessage,a),a.oneofs&&(A._botInvokeMessage="botInvokeMessage")),e.callLogMesssage!=null&&e.hasOwnProperty("callLogMesssage")&&(A.callLogMesssage=E.proto.Message.CallLogMessage.toObject(e.callLogMesssage,a),a.oneofs&&(A._callLogMesssage="callLogMesssage")),e.messageHistoryBundle!=null&&e.hasOwnProperty("messageHistoryBundle")&&(A.messageHistoryBundle=E.proto.Message.MessageHistoryBundle.toObject(e.messageHistoryBundle,a),a.oneofs&&(A._messageHistoryBundle="messageHistoryBundle")),e.encCommentMessage!=null&&e.hasOwnProperty("encCommentMessage")&&(A.encCommentMessage=E.proto.Message.EncCommentMessage.toObject(e.encCommentMessage,a),a.oneofs&&(A._encCommentMessage="encCommentMessage")),e.bcallMessage!=null&&e.hasOwnProperty("bcallMessage")&&(A.bcallMessage=E.proto.Message.BCallMessage.toObject(e.bcallMessage,a),a.oneofs&&(A._bcallMessage="bcallMessage")),e.lottieStickerMessage!=null&&e.hasOwnProperty("lottieStickerMessage")&&(A.lottieStickerMessage=E.proto.Message.FutureProofMessage.toObject(e.lottieStickerMessage,a),a.oneofs&&(A._lottieStickerMessage="lottieStickerMessage")),e.eventMessage!=null&&e.hasOwnProperty("eventMessage")&&(A.eventMessage=E.proto.Message.EventMessage.toObject(e.eventMessage,a),a.oneofs&&(A._eventMessage="eventMessage")),e.encEventResponseMessage!=null&&e.hasOwnProperty("encEventResponseMessage")&&(A.encEventResponseMessage=E.proto.Message.EncEventResponseMessage.toObject(e.encEventResponseMessage,a),a.oneofs&&(A._encEventResponseMessage="encEventResponseMessage")),e.commentMessage!=null&&e.hasOwnProperty("commentMessage")&&(A.commentMessage=E.proto.Message.CommentMessage.toObject(e.commentMessage,a),a.oneofs&&(A._commentMessage="commentMessage")),e.newsletterAdminInviteMessage!=null&&e.hasOwnProperty("newsletterAdminInviteMessage")&&(A.newsletterAdminInviteMessage=E.proto.Message.NewsletterAdminInviteMessage.toObject(e.newsletterAdminInviteMessage,a),a.oneofs&&(A._newsletterAdminInviteMessage="newsletterAdminInviteMessage")),e.placeholderMessage!=null&&e.hasOwnProperty("placeholderMessage")&&(A.placeholderMessage=E.proto.Message.PlaceholderMessage.toObject(e.placeholderMessage,a),a.oneofs&&(A._placeholderMessage="placeholderMessage")),e.secretEncryptedMessage!=null&&e.hasOwnProperty("secretEncryptedMessage")&&(A.secretEncryptedMessage=E.proto.Message.SecretEncryptedMessage.toObject(e.secretEncryptedMessage,a),a.oneofs&&(A._secretEncryptedMessage="secretEncryptedMessage")),e.albumMessage!=null&&e.hasOwnProperty("albumMessage")&&(A.albumMessage=E.proto.Message.AlbumMessage.toObject(e.albumMessage,a),a.oneofs&&(A._albumMessage="albumMessage")),e.eventCoverImage!=null&&e.hasOwnProperty("eventCoverImage")&&(A.eventCoverImage=E.proto.Message.FutureProofMessage.toObject(e.eventCoverImage,a),a.oneofs&&(A._eventCoverImage="eventCoverImage")),e.stickerPackMessage!=null&&e.hasOwnProperty("stickerPackMessage")&&(A.stickerPackMessage=E.proto.Message.StickerPackMessage.toObject(e.stickerPackMessage,a),a.oneofs&&(A._stickerPackMessage="stickerPackMessage")),e.statusMentionMessage!=null&&e.hasOwnProperty("statusMentionMessage")&&(A.statusMentionMessage=E.proto.Message.FutureProofMessage.toObject(e.statusMentionMessage,a),a.oneofs&&(A._statusMentionMessage="statusMentionMessage")),e.pollResultSnapshotMessage!=null&&e.hasOwnProperty("pollResultSnapshotMessage")&&(A.pollResultSnapshotMessage=E.proto.Message.PollResultSnapshotMessage.toObject(e.pollResultSnapshotMessage,a),a.oneofs&&(A._pollResultSnapshotMessage="pollResultSnapshotMessage")),e.pollCreationOptionImageMessage!=null&&e.hasOwnProperty("pollCreationOptionImageMessage")&&(A.pollCreationOptionImageMessage=E.proto.Message.FutureProofMessage.toObject(e.pollCreationOptionImageMessage,a),a.oneofs&&(A._pollCreationOptionImageMessage="pollCreationOptionImageMessage")),e.associatedChildMessage!=null&&e.hasOwnProperty("associatedChildMessage")&&(A.associatedChildMessage=E.proto.Message.FutureProofMessage.toObject(e.associatedChildMessage,a),a.oneofs&&(A._associatedChildMessage="associatedChildMessage")),e.groupStatusMentionMessage!=null&&e.hasOwnProperty("groupStatusMentionMessage")&&(A.groupStatusMentionMessage=E.proto.Message.FutureProofMessage.toObject(e.groupStatusMentionMessage,a),a.oneofs&&(A._groupStatusMentionMessage="groupStatusMentionMessage")),e.pollCreationMessageV4!=null&&e.hasOwnProperty("pollCreationMessageV4")&&(A.pollCreationMessageV4=E.proto.Message.FutureProofMessage.toObject(e.pollCreationMessageV4,a),a.oneofs&&(A._pollCreationMessageV4="pollCreationMessageV4")),e.statusAddYours!=null&&e.hasOwnProperty("statusAddYours")&&(A.statusAddYours=E.proto.Message.FutureProofMessage.toObject(e.statusAddYours,a),a.oneofs&&(A._statusAddYours="statusAddYours")),e.groupStatusMessage!=null&&e.hasOwnProperty("groupStatusMessage")&&(A.groupStatusMessage=E.proto.Message.FutureProofMessage.toObject(e.groupStatusMessage,a),a.oneofs&&(A._groupStatusMessage="groupStatusMessage")),e.richResponseMessage!=null&&e.hasOwnProperty("richResponseMessage")&&(A.richResponseMessage=E.proto.AIRichResponseMessage.toObject(e.richResponseMessage,a),a.oneofs&&(A._richResponseMessage="richResponseMessage")),e.statusNotificationMessage!=null&&e.hasOwnProperty("statusNotificationMessage")&&(A.statusNotificationMessage=E.proto.Message.StatusNotificationMessage.toObject(e.statusNotificationMessage,a),a.oneofs&&(A._statusNotificationMessage="statusNotificationMessage")),e.limitSharingMessage!=null&&e.hasOwnProperty("limitSharingMessage")&&(A.limitSharingMessage=E.proto.Message.FutureProofMessage.toObject(e.limitSharingMessage,a),a.oneofs&&(A._limitSharingMessage="limitSharingMessage")),e.botTaskMessage!=null&&e.hasOwnProperty("botTaskMessage")&&(A.botTaskMessage=E.proto.Message.FutureProofMessage.toObject(e.botTaskMessage,a),a.oneofs&&(A._botTaskMessage="botTaskMessage")),e.questionMessage!=null&&e.hasOwnProperty("questionMessage")&&(A.questionMessage=E.proto.Message.FutureProofMessage.toObject(e.questionMessage,a),a.oneofs&&(A._questionMessage="questionMessage")),e.messageHistoryNotice!=null&&e.hasOwnProperty("messageHistoryNotice")&&(A.messageHistoryNotice=E.proto.Message.MessageHistoryNotice.toObject(e.messageHistoryNotice,a),a.oneofs&&(A._messageHistoryNotice="messageHistoryNotice")),e.groupStatusMessageV2!=null&&e.hasOwnProperty("groupStatusMessageV2")&&(A.groupStatusMessageV2=E.proto.Message.FutureProofMessage.toObject(e.groupStatusMessageV2,a),a.oneofs&&(A._groupStatusMessageV2="groupStatusMessageV2")),e.botForwardedMessage!=null&&e.hasOwnProperty("botForwardedMessage")&&(A.botForwardedMessage=E.proto.Message.FutureProofMessage.toObject(e.botForwardedMessage,a),a.oneofs&&(A._botForwardedMessage="botForwardedMessage")),e.statusQuestionAnswerMessage!=null&&e.hasOwnProperty("statusQuestionAnswerMessage")&&(A.statusQuestionAnswerMessage=E.proto.Message.StatusQuestionAnswerMessage.toObject(e.statusQuestionAnswerMessage,a),a.oneofs&&(A._statusQuestionAnswerMessage="statusQuestionAnswerMessage")),e.questionReplyMessage!=null&&e.hasOwnProperty("questionReplyMessage")&&(A.questionReplyMessage=E.proto.Message.FutureProofMessage.toObject(e.questionReplyMessage,a),a.oneofs&&(A._questionReplyMessage="questionReplyMessage")),e.questionResponseMessage!=null&&e.hasOwnProperty("questionResponseMessage")&&(A.questionResponseMessage=E.proto.Message.QuestionResponseMessage.toObject(e.questionResponseMessage,a),a.oneofs&&(A._questionResponseMessage="questionResponseMessage")),e.statusQuotedMessage!=null&&e.hasOwnProperty("statusQuotedMessage")&&(A.statusQuotedMessage=E.proto.Message.StatusQuotedMessage.toObject(e.statusQuotedMessage,a),a.oneofs&&(A._statusQuotedMessage="statusQuotedMessage")),e.statusStickerInteractionMessage!=null&&e.hasOwnProperty("statusStickerInteractionMessage")&&(A.statusStickerInteractionMessage=E.proto.Message.StatusStickerInteractionMessage.toObject(e.statusStickerInteractionMessage,a),a.oneofs&&(A._statusStickerInteractionMessage="statusStickerInteractionMessage")),e.pollCreationMessageV5!=null&&e.hasOwnProperty("pollCreationMessageV5")&&(A.pollCreationMessageV5=E.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV5,a),a.oneofs&&(A._pollCreationMessageV5="pollCreationMessageV5")),e.newsletterFollowerInviteMessageV2!=null&&e.hasOwnProperty("newsletterFollowerInviteMessageV2")&&(A.newsletterFollowerInviteMessageV2=E.proto.Message.NewsletterFollowerInviteMessage.toObject(e.newsletterFollowerInviteMessageV2,a),a.oneofs&&(A._newsletterFollowerInviteMessageV2="newsletterFollowerInviteMessageV2")),e.pollResultSnapshotMessageV3!=null&&e.hasOwnProperty("pollResultSnapshotMessageV3")&&(A.pollResultSnapshotMessageV3=E.proto.Message.PollResultSnapshotMessage.toObject(e.pollResultSnapshotMessageV3,a),a.oneofs&&(A._pollResultSnapshotMessageV3="pollResultSnapshotMessageV3")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Message"},r.AlbumMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 2:{c.expectedImageCount=A.uint32();break}case 3:{c.expectedVideoCount=A.uint32();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.AlbumMessage)return A;var t=new E.proto.Message.AlbumMessage;if(A.expectedImageCount!=null&&(t.expectedImageCount=A.expectedImageCount>>>0),A.expectedVideoCount!=null&&(t.expectedVideoCount=A.expectedVideoCount>>>0),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.AlbumMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.expectedImageCount!=null&&A.hasOwnProperty("expectedImageCount")&&(s.expectedImageCount=A.expectedImageCount,t.oneofs&&(s._expectedImageCount="expectedImageCount")),A.expectedVideoCount!=null&&A.hasOwnProperty("expectedVideoCount")&&(s.expectedVideoCount=A.expectedVideoCount,t.oneofs&&(s._expectedVideoCount="expectedVideoCount")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AlbumMessage"},i})(),r.AppStateFatalExceptionNotification=(function(){function i(a){if(this.collectionNames=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.collectionNames&&c.collectionNames.length||(c.collectionNames=[]),c.collectionNames.push(A.string());break}case 2:{c.timestamp=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.AppStateFatalExceptionNotification)return A;var t=new E.proto.Message.AppStateFatalExceptionNotification;if(A.collectionNames){if(!Array.isArray(A.collectionNames))throw TypeError(".proto.Message.AppStateFatalExceptionNotification.collectionNames: array expected");t.collectionNames=[];for(var s=0;s>>0,A.timestamp.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.collectionNames=[]),A.collectionNames&&A.collectionNames.length){s.collectionNames=[];for(var g=0;g>>3){case 1:{c.keyId=E.proto.Message.AppStateSyncKeyId.decode(A,A.uint32());break}case 2:{c.keyData=E.proto.Message.AppStateSyncKeyData.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.AppStateSyncKey)return A;var t=new E.proto.Message.AppStateSyncKey;if(A.keyId!=null){if(typeof A.keyId!="object")throw TypeError(".proto.Message.AppStateSyncKey.keyId: object expected");t.keyId=E.proto.Message.AppStateSyncKeyId.fromObject(A.keyId)}if(A.keyData!=null){if(typeof A.keyData!="object")throw TypeError(".proto.Message.AppStateSyncKey.keyData: object expected");t.keyData=E.proto.Message.AppStateSyncKeyData.fromObject(A.keyData)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.keyId!=null&&A.hasOwnProperty("keyId")&&(s.keyId=E.proto.Message.AppStateSyncKeyId.toObject(A.keyId,t),t.oneofs&&(s._keyId="keyId")),A.keyData!=null&&A.hasOwnProperty("keyData")&&(s.keyData=E.proto.Message.AppStateSyncKeyData.toObject(A.keyData,t),t.oneofs&&(s._keyData="keyData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKey"},i})(),r.AppStateSyncKeyData=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.keyData=A.bytes();break}case 2:{c.fingerprint=E.proto.Message.AppStateSyncKeyFingerprint.decode(A,A.uint32());break}case 3:{c.timestamp=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.AppStateSyncKeyData)return A;var t=new E.proto.Message.AppStateSyncKeyData;if(A.keyData!=null&&(typeof A.keyData=="string"?I.base64.decode(A.keyData,t.keyData=I.newBuffer(I.base64.length(A.keyData)),0):A.keyData.length>=0&&(t.keyData=A.keyData)),A.fingerprint!=null){if(typeof A.fingerprint!="object")throw TypeError(".proto.Message.AppStateSyncKeyData.fingerprint: object expected");t.fingerprint=E.proto.Message.AppStateSyncKeyFingerprint.fromObject(A.fingerprint)}return A.timestamp!=null&&(I.Long?(t.timestamp=I.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?t.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?t.timestamp=A.timestamp:typeof A.timestamp=="object"&&(t.timestamp=new I.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.keyData!=null&&A.hasOwnProperty("keyData")&&(s.keyData=t.bytes===String?I.base64.encode(A.keyData,0,A.keyData.length):t.bytes===Array?Array.prototype.slice.call(A.keyData):A.keyData,t.oneofs&&(s._keyData="keyData")),A.fingerprint!=null&&A.hasOwnProperty("fingerprint")&&(s.fingerprint=E.proto.Message.AppStateSyncKeyFingerprint.toObject(A.fingerprint,t),t.oneofs&&(s._fingerprint="fingerprint")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=t.longs===String?String(A.timestamp):A.timestamp:s.timestamp=t.longs===String?re(A.timestamp):t.longs===Number?ae(A.timestamp):A.timestamp,t.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKeyData"},i})(),r.AppStateSyncKeyFingerprint=(function(){function i(a){if(this.deviceIndexes=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.rawId=A.uint32();break}case 2:{c.currentIndex=A.uint32();break}case 3:{if(c.deviceIndexes&&c.deviceIndexes.length||(c.deviceIndexes=[]),(l&7)===2)for(var p=A.uint32()+A.pos;A.pos>>0),A.currentIndex!=null&&(t.currentIndex=A.currentIndex>>>0),A.deviceIndexes){if(!Array.isArray(A.deviceIndexes))throw TypeError(".proto.Message.AppStateSyncKeyFingerprint.deviceIndexes: array expected");t.deviceIndexes=[];for(var s=0;s>>0}return t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.deviceIndexes=[]),A.rawId!=null&&A.hasOwnProperty("rawId")&&(s.rawId=A.rawId,t.oneofs&&(s._rawId="rawId")),A.currentIndex!=null&&A.hasOwnProperty("currentIndex")&&(s.currentIndex=A.currentIndex,t.oneofs&&(s._currentIndex="currentIndex")),A.deviceIndexes&&A.deviceIndexes.length){s.deviceIndexes=[];for(var g=0;g>>3){case 1:{c.keyId=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.AppStateSyncKeyId)return A;var t=new E.proto.Message.AppStateSyncKeyId;return A.keyId!=null&&(typeof A.keyId=="string"?I.base64.decode(A.keyId,t.keyId=I.newBuffer(I.base64.length(A.keyId)),0):A.keyId.length>=0&&(t.keyId=A.keyId)),t},i.toObject=function(A,t){t||(t={});var s={};return A.keyId!=null&&A.hasOwnProperty("keyId")&&(s.keyId=t.bytes===String?I.base64.encode(A.keyId,0,A.keyId.length):t.bytes===Array?Array.prototype.slice.call(A.keyId):A.keyId,t.oneofs&&(s._keyId="keyId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKeyId"},i})(),r.AppStateSyncKeyRequest=(function(){function i(e){if(this.keyIds=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.keyIds&&g.keyIds.length||(g.keyIds=[]),g.keyIds.push(E.proto.Message.AppStateSyncKeyId.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.Message.AppStateSyncKeyRequest)return a;var A=new E.proto.Message.AppStateSyncKeyRequest;if(a.keyIds){if(!Array.isArray(a.keyIds))throw TypeError(".proto.Message.AppStateSyncKeyRequest.keyIds: array expected");A.keyIds=[];for(var t=0;t>>3){case 1:{g.keys&&g.keys.length||(g.keys=[]),g.keys.push(E.proto.Message.AppStateSyncKey.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.Message.AppStateSyncKeyShare)return a;var A=new E.proto.Message.AppStateSyncKeyShare;if(a.keys){if(!Array.isArray(a.keys))throw TypeError(".proto.Message.AppStateSyncKeyShare.keys: array expected");A.keys=[];for(var t=0;t>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileLength=A.uint64();break}case 5:{c.seconds=A.uint32();break}case 6:{c.ptt=A.bool();break}case 7:{c.mediaKey=A.bytes();break}case 8:{c.fileEncSha256=A.bytes();break}case 9:{c.directPath=A.string();break}case 10:{c.mediaKeyTimestamp=A.int64();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.streamingSidecar=A.bytes();break}case 19:{c.waveform=A.bytes();break}case 20:{c.backgroundArgb=A.fixed32();break}case 21:{c.viewOnce=A.bool();break}case 22:{c.accessibilityLabel=A.string();break}case 23:{c.mediaKeyDomain=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.AudioMessage)return A;var t=new E.proto.Message.AudioMessage;if(A.url!=null&&(t.url=String(A.url)),A.mimetype!=null&&(t.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.fileLength!=null&&(I.Long?(t.fileLength=I.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?t.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?t.fileLength=A.fileLength:typeof A.fileLength=="object"&&(t.fileLength=new I.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.seconds!=null&&(t.seconds=A.seconds>>>0),A.ptt!=null&&(t.ptt=!!A.ptt),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(t.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.AudioMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.streamingSidecar!=null&&(typeof A.streamingSidecar=="string"?I.base64.decode(A.streamingSidecar,t.streamingSidecar=I.newBuffer(I.base64.length(A.streamingSidecar)),0):A.streamingSidecar.length>=0&&(t.streamingSidecar=A.streamingSidecar)),A.waveform!=null&&(typeof A.waveform=="string"?I.base64.decode(A.waveform,t.waveform=I.newBuffer(I.base64.length(A.waveform)),0):A.waveform.length>=0&&(t.waveform=A.waveform)),A.backgroundArgb!=null&&(t.backgroundArgb=A.backgroundArgb>>>0),A.viewOnce!=null&&(t.viewOnce=!!A.viewOnce),A.accessibilityLabel!=null&&(t.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){t.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:t.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:t.mediaKeyDomain=1;break;case"STATUS":case 2:t.mediaKeyDomain=2;break;case"CAPI":case 3:t.mediaKeyDomain=3;break;case"BOT":case 4:t.mediaKeyDomain=4;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,t.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=t.bytes===String?I.base64.encode(A.fileSha256,0,A.fileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,t.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=t.longs===String?String(A.fileLength):A.fileLength:s.fileLength=t.longs===String?re(A.fileLength,!0):t.longs===Number?ae(A.fileLength,!0):A.fileLength,t.oneofs&&(s._fileLength="fileLength")),A.seconds!=null&&A.hasOwnProperty("seconds")&&(s.seconds=A.seconds,t.oneofs&&(s._seconds="seconds")),A.ptt!=null&&A.hasOwnProperty("ptt")&&(s.ptt=A.ptt,t.oneofs&&(s._ptt="ptt")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,t.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=t.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=t.longs===String?re(A.mediaKeyTimestamp):t.longs===Number?ae(A.mediaKeyTimestamp):A.mediaKeyTimestamp,t.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.streamingSidecar!=null&&A.hasOwnProperty("streamingSidecar")&&(s.streamingSidecar=t.bytes===String?I.base64.encode(A.streamingSidecar,0,A.streamingSidecar.length):t.bytes===Array?Array.prototype.slice.call(A.streamingSidecar):A.streamingSidecar,t.oneofs&&(s._streamingSidecar="streamingSidecar")),A.waveform!=null&&A.hasOwnProperty("waveform")&&(s.waveform=t.bytes===String?I.base64.encode(A.waveform,0,A.waveform.length):t.bytes===Array?Array.prototype.slice.call(A.waveform):A.waveform,t.oneofs&&(s._waveform="waveform")),A.backgroundArgb!=null&&A.hasOwnProperty("backgroundArgb")&&(s.backgroundArgb=A.backgroundArgb,t.oneofs&&(s._backgroundArgb="backgroundArgb")),A.viewOnce!=null&&A.hasOwnProperty("viewOnce")&&(s.viewOnce=A.viewOnce,t.oneofs&&(s._viewOnce="viewOnce")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,t.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=t.enums===String?E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,t.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AudioMessage"},i})(),r.BCallMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.sessionId=A.string();break}case 2:{c.mediaType=A.int32();break}case 3:{c.masterKey=A.bytes();break}case 4:{c.caption=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.BCallMessage)return A;var t=new E.proto.Message.BCallMessage;switch(A.sessionId!=null&&(t.sessionId=String(A.sessionId)),A.mediaType){default:if(typeof A.mediaType=="number"){t.mediaType=A.mediaType;break}break;case"UNKNOWN":case 0:t.mediaType=0;break;case"AUDIO":case 1:t.mediaType=1;break;case"VIDEO":case 2:t.mediaType=2;break}return A.masterKey!=null&&(typeof A.masterKey=="string"?I.base64.decode(A.masterKey,t.masterKey=I.newBuffer(I.base64.length(A.masterKey)),0):A.masterKey.length>=0&&(t.masterKey=A.masterKey)),A.caption!=null&&(t.caption=String(A.caption)),t},i.toObject=function(A,t){t||(t={});var s={};return A.sessionId!=null&&A.hasOwnProperty("sessionId")&&(s.sessionId=A.sessionId,t.oneofs&&(s._sessionId="sessionId")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=t.enums===String?E.proto.Message.BCallMessage.MediaType[A.mediaType]===void 0?A.mediaType:E.proto.Message.BCallMessage.MediaType[A.mediaType]:A.mediaType,t.oneofs&&(s._mediaType="mediaType")),A.masterKey!=null&&A.hasOwnProperty("masterKey")&&(s.masterKey=t.bytes===String?I.base64.encode(A.masterKey,0,A.masterKey.length):t.bytes===Array?Array.prototype.slice.call(A.masterKey):A.masterKey,t.oneofs&&(s._masterKey="masterKey")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.BCallMessage"},i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="AUDIO"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),r.ButtonsMessage=(function(){function i(a){if(this.buttons=[],a)for(var A=Object.keys(a),t=0;t>>3){case 6:{c.contentText=A.string();break}case 7:{c.footerText=A.string();break}case 8:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 9:{c.buttons&&c.buttons.length||(c.buttons=[]),c.buttons.push(E.proto.Message.ButtonsMessage.Button.decode(A,A.uint32()));break}case 10:{c.headerType=A.int32();break}case 1:{c.text=A.string();break}case 2:{c.documentMessage=E.proto.Message.DocumentMessage.decode(A,A.uint32());break}case 3:{c.imageMessage=E.proto.Message.ImageMessage.decode(A,A.uint32());break}case 4:{c.videoMessage=E.proto.Message.VideoMessage.decode(A,A.uint32());break}case 5:{c.locationMessage=E.proto.Message.LocationMessage.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ButtonsMessage)return A;var t=new E.proto.Message.ButtonsMessage;if(A.contentText!=null&&(t.contentText=String(A.contentText)),A.footerText!=null&&(t.footerText=String(A.footerText)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ButtonsMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.buttons){if(!Array.isArray(A.buttons))throw TypeError(".proto.Message.ButtonsMessage.buttons: array expected");t.buttons=[];for(var s=0;s>>3){case 1:{p.buttonId=s.string();break}case 2:{p.buttonText=E.proto.Message.ButtonsMessage.Button.ButtonText.decode(s,s.uint32());break}case 3:{p.type=s.int32();break}case 4:{p.nativeFlowInfo=E.proto.Message.ButtonsMessage.Button.NativeFlowInfo.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ButtonsMessage.Button)return s;var g=new E.proto.Message.ButtonsMessage.Button;if(s.buttonId!=null&&(g.buttonId=String(s.buttonId)),s.buttonText!=null){if(typeof s.buttonText!="object")throw TypeError(".proto.Message.ButtonsMessage.Button.buttonText: object expected");g.buttonText=E.proto.Message.ButtonsMessage.Button.ButtonText.fromObject(s.buttonText)}switch(s.type){default:if(typeof s.type=="number"){g.type=s.type;break}break;case"UNKNOWN":case 0:g.type=0;break;case"RESPONSE":case 1:g.type=1;break;case"NATIVE_FLOW":case 2:g.type=2;break}if(s.nativeFlowInfo!=null){if(typeof s.nativeFlowInfo!="object")throw TypeError(".proto.Message.ButtonsMessage.Button.nativeFlowInfo: object expected");g.nativeFlowInfo=E.proto.Message.ButtonsMessage.Button.NativeFlowInfo.fromObject(s.nativeFlowInfo)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.buttonId!=null&&s.hasOwnProperty("buttonId")&&(c.buttonId=s.buttonId,g.oneofs&&(c._buttonId="buttonId")),s.buttonText!=null&&s.hasOwnProperty("buttonText")&&(c.buttonText=E.proto.Message.ButtonsMessage.Button.ButtonText.toObject(s.buttonText,g),g.oneofs&&(c._buttonText="buttonText")),s.type!=null&&s.hasOwnProperty("type")&&(c.type=g.enums===String?E.proto.Message.ButtonsMessage.Button.Type[s.type]===void 0?s.type:E.proto.Message.ButtonsMessage.Button.Type[s.type]:s.type,g.oneofs&&(c._type="type")),s.nativeFlowInfo!=null&&s.hasOwnProperty("nativeFlowInfo")&&(c.nativeFlowInfo=E.proto.Message.ButtonsMessage.Button.NativeFlowInfo.toObject(s.nativeFlowInfo,g),g.oneofs&&(c._nativeFlowInfo="nativeFlowInfo")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ButtonsMessage.Button"},a.ButtonText=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.displayText=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.ButtonsMessage.Button.ButtonText)return c;var l=new E.proto.Message.ButtonsMessage.Button.ButtonText;return c.displayText!=null&&(l.displayText=String(c.displayText)),l},t.toObject=function(c,l){l||(l={});var p={};return c.displayText!=null&&c.hasOwnProperty("displayText")&&(p.displayText=c.displayText,l.oneofs&&(p._displayText="displayText")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.ButtonsMessage.Button.ButtonText"},t})(),a.NativeFlowInfo=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.name=c.string();break}case 2:{Q.paramsJson=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.ButtonsMessage.Button.NativeFlowInfo)return c;var l=new E.proto.Message.ButtonsMessage.Button.NativeFlowInfo;return c.name!=null&&(l.name=String(c.name)),c.paramsJson!=null&&(l.paramsJson=String(c.paramsJson)),l},t.toObject=function(c,l){l||(l={});var p={};return c.name!=null&&c.hasOwnProperty("name")&&(p.name=c.name,l.oneofs&&(p._name="name")),c.paramsJson!=null&&c.hasOwnProperty("paramsJson")&&(p.paramsJson=c.paramsJson,l.oneofs&&(p._paramsJson="paramsJson")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.ButtonsMessage.Button.NativeFlowInfo"},t})(),a.Type=(function(){let t={},s=Object.create(t);return s[t[0]="UNKNOWN"]=0,s[t[1]="RESPONSE"]=1,s[t[2]="NATIVE_FLOW"]=2,s})(),a})(),i.HeaderType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="EMPTY"]=1,A[a[2]="TEXT"]=2,A[a[3]="DOCUMENT"]=3,A[a[4]="IMAGE"]=4,A[a[5]="VIDEO"]=5,A[a[6]="LOCATION"]=6,A})(),i})(),r.ButtonsResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.selectedButtonId=A.string();break}case 3:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.type=A.int32();break}case 2:{c.selectedDisplayText=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ButtonsResponseMessage)return A;var t=new E.proto.Message.ButtonsResponseMessage;if(A.selectedButtonId!=null&&(t.selectedButtonId=String(A.selectedButtonId)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ButtonsResponseMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"UNKNOWN":case 0:t.type=0;break;case"DISPLAY_TEXT":case 1:t.type=1;break}return A.selectedDisplayText!=null&&(t.selectedDisplayText=String(A.selectedDisplayText)),t},i.toObject=function(A,t){t||(t={});var s={};return A.selectedButtonId!=null&&A.hasOwnProperty("selectedButtonId")&&(s.selectedButtonId=A.selectedButtonId,t.oneofs&&(s._selectedButtonId="selectedButtonId")),A.selectedDisplayText!=null&&A.hasOwnProperty("selectedDisplayText")&&(s.selectedDisplayText=A.selectedDisplayText,t.oneofs&&(s.response="selectedDisplayText")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.Message.ButtonsResponseMessage.Type[A.type]===void 0?A.type:E.proto.Message.ButtonsResponseMessage.Type[A.type]:A.type,t.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ButtonsResponseMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="DISPLAY_TEXT"]=1,A})(),i})(),r.Call=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.callKey=A.bytes();break}case 2:{c.conversionSource=A.string();break}case 3:{c.conversionData=A.bytes();break}case 4:{c.conversionDelaySeconds=A.uint32();break}case 5:{c.ctwaSignals=A.string();break}case 6:{c.ctwaPayload=A.bytes();break}case 7:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.nativeFlowCallButtonPayload=A.string();break}case 9:{c.deeplinkPayload=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.Call)return A;var t=new E.proto.Message.Call;if(A.callKey!=null&&(typeof A.callKey=="string"?I.base64.decode(A.callKey,t.callKey=I.newBuffer(I.base64.length(A.callKey)),0):A.callKey.length>=0&&(t.callKey=A.callKey)),A.conversionSource!=null&&(t.conversionSource=String(A.conversionSource)),A.conversionData!=null&&(typeof A.conversionData=="string"?I.base64.decode(A.conversionData,t.conversionData=I.newBuffer(I.base64.length(A.conversionData)),0):A.conversionData.length>=0&&(t.conversionData=A.conversionData)),A.conversionDelaySeconds!=null&&(t.conversionDelaySeconds=A.conversionDelaySeconds>>>0),A.ctwaSignals!=null&&(t.ctwaSignals=String(A.ctwaSignals)),A.ctwaPayload!=null&&(typeof A.ctwaPayload=="string"?I.base64.decode(A.ctwaPayload,t.ctwaPayload=I.newBuffer(I.base64.length(A.ctwaPayload)),0):A.ctwaPayload.length>=0&&(t.ctwaPayload=A.ctwaPayload)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.Call.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return A.nativeFlowCallButtonPayload!=null&&(t.nativeFlowCallButtonPayload=String(A.nativeFlowCallButtonPayload)),A.deeplinkPayload!=null&&(t.deeplinkPayload=String(A.deeplinkPayload)),t},i.toObject=function(A,t){t||(t={});var s={};return A.callKey!=null&&A.hasOwnProperty("callKey")&&(s.callKey=t.bytes===String?I.base64.encode(A.callKey,0,A.callKey.length):t.bytes===Array?Array.prototype.slice.call(A.callKey):A.callKey,t.oneofs&&(s._callKey="callKey")),A.conversionSource!=null&&A.hasOwnProperty("conversionSource")&&(s.conversionSource=A.conversionSource,t.oneofs&&(s._conversionSource="conversionSource")),A.conversionData!=null&&A.hasOwnProperty("conversionData")&&(s.conversionData=t.bytes===String?I.base64.encode(A.conversionData,0,A.conversionData.length):t.bytes===Array?Array.prototype.slice.call(A.conversionData):A.conversionData,t.oneofs&&(s._conversionData="conversionData")),A.conversionDelaySeconds!=null&&A.hasOwnProperty("conversionDelaySeconds")&&(s.conversionDelaySeconds=A.conversionDelaySeconds,t.oneofs&&(s._conversionDelaySeconds="conversionDelaySeconds")),A.ctwaSignals!=null&&A.hasOwnProperty("ctwaSignals")&&(s.ctwaSignals=A.ctwaSignals,t.oneofs&&(s._ctwaSignals="ctwaSignals")),A.ctwaPayload!=null&&A.hasOwnProperty("ctwaPayload")&&(s.ctwaPayload=t.bytes===String?I.base64.encode(A.ctwaPayload,0,A.ctwaPayload.length):t.bytes===Array?Array.prototype.slice.call(A.ctwaPayload):A.ctwaPayload,t.oneofs&&(s._ctwaPayload="ctwaPayload")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.nativeFlowCallButtonPayload!=null&&A.hasOwnProperty("nativeFlowCallButtonPayload")&&(s.nativeFlowCallButtonPayload=A.nativeFlowCallButtonPayload,t.oneofs&&(s._nativeFlowCallButtonPayload="nativeFlowCallButtonPayload")),A.deeplinkPayload!=null&&A.hasOwnProperty("deeplinkPayload")&&(s.deeplinkPayload=A.deeplinkPayload,t.oneofs&&(s._deeplinkPayload="deeplinkPayload")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.Call"},i})(),r.CallLogMessage=(function(){function i(a){if(this.participants=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isVideo=A.bool();break}case 2:{c.callOutcome=A.int32();break}case 3:{c.durationSecs=A.int64();break}case 4:{c.callType=A.int32();break}case 5:{c.participants&&c.participants.length||(c.participants=[]),c.participants.push(E.proto.Message.CallLogMessage.CallParticipant.decode(A,A.uint32()));break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.CallLogMessage)return A;var t=new E.proto.Message.CallLogMessage;switch(A.isVideo!=null&&(t.isVideo=!!A.isVideo),A.callOutcome){default:if(typeof A.callOutcome=="number"){t.callOutcome=A.callOutcome;break}break;case"CONNECTED":case 0:t.callOutcome=0;break;case"MISSED":case 1:t.callOutcome=1;break;case"FAILED":case 2:t.callOutcome=2;break;case"REJECTED":case 3:t.callOutcome=3;break;case"ACCEPTED_ELSEWHERE":case 4:t.callOutcome=4;break;case"ONGOING":case 5:t.callOutcome=5;break;case"SILENCED_BY_DND":case 6:t.callOutcome=6;break;case"SILENCED_UNKNOWN_CALLER":case 7:t.callOutcome=7;break}switch(A.durationSecs!=null&&(I.Long?(t.durationSecs=I.Long.fromValue(A.durationSecs)).unsigned=!1:typeof A.durationSecs=="string"?t.durationSecs=parseInt(A.durationSecs,10):typeof A.durationSecs=="number"?t.durationSecs=A.durationSecs:typeof A.durationSecs=="object"&&(t.durationSecs=new I.LongBits(A.durationSecs.low>>>0,A.durationSecs.high>>>0).toNumber())),A.callType){default:if(typeof A.callType=="number"){t.callType=A.callType;break}break;case"REGULAR":case 0:t.callType=0;break;case"SCHEDULED_CALL":case 1:t.callType=1;break;case"VOICE_CHAT":case 2:t.callType=2;break}if(A.participants){if(!Array.isArray(A.participants))throw TypeError(".proto.Message.CallLogMessage.participants: array expected");t.participants=[];for(var s=0;s>>3){case 1:{p.jid=s.string();break}case 2:{p.callOutcome=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.CallLogMessage.CallParticipant)return s;var g=new E.proto.Message.CallLogMessage.CallParticipant;switch(s.jid!=null&&(g.jid=String(s.jid)),s.callOutcome){default:if(typeof s.callOutcome=="number"){g.callOutcome=s.callOutcome;break}break;case"CONNECTED":case 0:g.callOutcome=0;break;case"MISSED":case 1:g.callOutcome=1;break;case"FAILED":case 2:g.callOutcome=2;break;case"REJECTED":case 3:g.callOutcome=3;break;case"ACCEPTED_ELSEWHERE":case 4:g.callOutcome=4;break;case"ONGOING":case 5:g.callOutcome=5;break;case"SILENCED_BY_DND":case 6:g.callOutcome=6;break;case"SILENCED_UNKNOWN_CALLER":case 7:g.callOutcome=7;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.jid!=null&&s.hasOwnProperty("jid")&&(c.jid=s.jid,g.oneofs&&(c._jid="jid")),s.callOutcome!=null&&s.hasOwnProperty("callOutcome")&&(c.callOutcome=g.enums===String?E.proto.Message.CallLogMessage.CallOutcome[s.callOutcome]===void 0?s.callOutcome:E.proto.Message.CallLogMessage.CallOutcome[s.callOutcome]:s.callOutcome,g.oneofs&&(c._callOutcome="callOutcome")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.CallLogMessage.CallParticipant"},a})(),i.CallType=(function(){let a={},A=Object.create(a);return A[a[0]="REGULAR"]=0,A[a[1]="SCHEDULED_CALL"]=1,A[a[2]="VOICE_CHAT"]=2,A})(),i})(),r.CancelPaymentRequestMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.CancelPaymentRequestMessage)return A;var t=new E.proto.Message.CancelPaymentRequestMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.CancelPaymentRequestMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CancelPaymentRequestMessage"},i})(),r.Chat=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayName=A.string();break}case 2:{c.id=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.Chat)return A;var t=new E.proto.Message.Chat;return A.displayName!=null&&(t.displayName=String(A.displayName)),A.id!=null&&(t.id=String(A.id)),t},i.toObject=function(A,t){t||(t={});var s={};return A.displayName!=null&&A.hasOwnProperty("displayName")&&(s.displayName=A.displayName,t.oneofs&&(s._displayName="displayName")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,t.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.Chat"},i})(),r.CloudAPIThreadControlNotification=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.status=A.int32();break}case 2:{c.senderNotificationTimestampMs=A.int64();break}case 3:{c.consumerLid=A.string();break}case 4:{c.consumerPhoneNumber=A.string();break}case 5:{c.notificationContent=E.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.decode(A,A.uint32());break}case 6:{c.shouldSuppressNotification=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.CloudAPIThreadControlNotification)return A;var t=new E.proto.Message.CloudAPIThreadControlNotification;switch(A.status){default:if(typeof A.status=="number"){t.status=A.status;break}break;case"UNKNOWN":case 0:t.status=0;break;case"CONTROL_PASSED":case 1:t.status=1;break;case"CONTROL_TAKEN":case 2:t.status=2;break}if(A.senderNotificationTimestampMs!=null&&(I.Long?(t.senderNotificationTimestampMs=I.Long.fromValue(A.senderNotificationTimestampMs)).unsigned=!1:typeof A.senderNotificationTimestampMs=="string"?t.senderNotificationTimestampMs=parseInt(A.senderNotificationTimestampMs,10):typeof A.senderNotificationTimestampMs=="number"?t.senderNotificationTimestampMs=A.senderNotificationTimestampMs:typeof A.senderNotificationTimestampMs=="object"&&(t.senderNotificationTimestampMs=new I.LongBits(A.senderNotificationTimestampMs.low>>>0,A.senderNotificationTimestampMs.high>>>0).toNumber())),A.consumerLid!=null&&(t.consumerLid=String(A.consumerLid)),A.consumerPhoneNumber!=null&&(t.consumerPhoneNumber=String(A.consumerPhoneNumber)),A.notificationContent!=null){if(typeof A.notificationContent!="object")throw TypeError(".proto.Message.CloudAPIThreadControlNotification.notificationContent: object expected");t.notificationContent=E.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.fromObject(A.notificationContent)}return A.shouldSuppressNotification!=null&&(t.shouldSuppressNotification=!!A.shouldSuppressNotification),t},i.toObject=function(A,t){t||(t={});var s={};return A.status!=null&&A.hasOwnProperty("status")&&(s.status=t.enums===String?E.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControl[A.status]===void 0?A.status:E.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControl[A.status]:A.status,t.oneofs&&(s._status="status")),A.senderNotificationTimestampMs!=null&&A.hasOwnProperty("senderNotificationTimestampMs")&&(typeof A.senderNotificationTimestampMs=="number"?s.senderNotificationTimestampMs=t.longs===String?String(A.senderNotificationTimestampMs):A.senderNotificationTimestampMs:s.senderNotificationTimestampMs=t.longs===String?re(A.senderNotificationTimestampMs):t.longs===Number?ae(A.senderNotificationTimestampMs):A.senderNotificationTimestampMs,t.oneofs&&(s._senderNotificationTimestampMs="senderNotificationTimestampMs")),A.consumerLid!=null&&A.hasOwnProperty("consumerLid")&&(s.consumerLid=A.consumerLid,t.oneofs&&(s._consumerLid="consumerLid")),A.consumerPhoneNumber!=null&&A.hasOwnProperty("consumerPhoneNumber")&&(s.consumerPhoneNumber=A.consumerPhoneNumber,t.oneofs&&(s._consumerPhoneNumber="consumerPhoneNumber")),A.notificationContent!=null&&A.hasOwnProperty("notificationContent")&&(s.notificationContent=E.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.toObject(A.notificationContent,t),t.oneofs&&(s._notificationContent="notificationContent")),A.shouldSuppressNotification!=null&&A.hasOwnProperty("shouldSuppressNotification")&&(s.shouldSuppressNotification=A.shouldSuppressNotification,t.oneofs&&(s._shouldSuppressNotification="shouldSuppressNotification")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CloudAPIThreadControlNotification"},i.CloudAPIThreadControl=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CONTROL_PASSED"]=1,A[a[2]="CONTROL_TAKEN"]=2,A})(),i.CloudAPIThreadControlNotificationContent=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.handoffNotificationText=s.string();break}case 2:{p.extraJson=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent)return s;var g=new E.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent;return s.handoffNotificationText!=null&&(g.handoffNotificationText=String(s.handoffNotificationText)),s.extraJson!=null&&(g.extraJson=String(s.extraJson)),g},a.toObject=function(s,g){g||(g={});var c={};return s.handoffNotificationText!=null&&s.hasOwnProperty("handoffNotificationText")&&(c.handoffNotificationText=s.handoffNotificationText,g.oneofs&&(c._handoffNotificationText="handoffNotificationText")),s.extraJson!=null&&s.hasOwnProperty("extraJson")&&(c.extraJson=s.extraJson,g.oneofs&&(c._extraJson="extraJson")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent"},a})(),i})(),r.CommentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.message=E.proto.Message.decode(A,A.uint32());break}case 2:{c.targetMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.CommentMessage)return A;var t=new E.proto.Message.CommentMessage;if(A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.CommentMessage.message: object expected");t.message=E.proto.Message.fromObject(A.message)}if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.CommentMessage.targetMessageKey: object expected");t.targetMessageKey=E.proto.MessageKey.fromObject(A.targetMessageKey)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.message!=null&&A.hasOwnProperty("message")&&(s.message=E.proto.Message.toObject(A.message,t),t.oneofs&&(s._message="message")),A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=E.proto.MessageKey.toObject(A.targetMessageKey,t),t.oneofs&&(s._targetMessageKey="targetMessageKey")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CommentMessage"},i})(),r.ContactMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayName=A.string();break}case 16:{c.vcard=A.string();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ContactMessage)return A;var t=new E.proto.Message.ContactMessage;if(A.displayName!=null&&(t.displayName=String(A.displayName)),A.vcard!=null&&(t.vcard=String(A.vcard)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ContactMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.displayName!=null&&A.hasOwnProperty("displayName")&&(s.displayName=A.displayName,t.oneofs&&(s._displayName="displayName")),A.vcard!=null&&A.hasOwnProperty("vcard")&&(s.vcard=A.vcard,t.oneofs&&(s._vcard="vcard")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ContactMessage"},i})(),r.ContactsArrayMessage=(function(){function i(a){if(this.contacts=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayName=A.string();break}case 2:{c.contacts&&c.contacts.length||(c.contacts=[]),c.contacts.push(E.proto.Message.ContactMessage.decode(A,A.uint32()));break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ContactsArrayMessage)return A;var t=new E.proto.Message.ContactsArrayMessage;if(A.displayName!=null&&(t.displayName=String(A.displayName)),A.contacts){if(!Array.isArray(A.contacts))throw TypeError(".proto.Message.ContactsArrayMessage.contacts: array expected");t.contacts=[];for(var s=0;s>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.DeclinePaymentRequestMessage)return A;var t=new E.proto.Message.DeclinePaymentRequestMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.DeclinePaymentRequestMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DeclinePaymentRequestMessage"},i})(),r.DeviceSentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.destinationJid=A.string();break}case 2:{c.message=E.proto.Message.decode(A,A.uint32());break}case 3:{c.phash=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.DeviceSentMessage)return A;var t=new E.proto.Message.DeviceSentMessage;if(A.destinationJid!=null&&(t.destinationJid=String(A.destinationJid)),A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.DeviceSentMessage.message: object expected");t.message=E.proto.Message.fromObject(A.message)}return A.phash!=null&&(t.phash=String(A.phash)),t},i.toObject=function(A,t){t||(t={});var s={};return A.destinationJid!=null&&A.hasOwnProperty("destinationJid")&&(s.destinationJid=A.destinationJid,t.oneofs&&(s._destinationJid="destinationJid")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=E.proto.Message.toObject(A.message,t),t.oneofs&&(s._message="message")),A.phash!=null&&A.hasOwnProperty("phash")&&(s.phash=A.phash,t.oneofs&&(s._phash="phash")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DeviceSentMessage"},i})(),r.DocumentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.title=A.string();break}case 4:{c.fileSha256=A.bytes();break}case 5:{c.fileLength=A.uint64();break}case 6:{c.pageCount=A.uint32();break}case 7:{c.mediaKey=A.bytes();break}case 8:{c.fileName=A.string();break}case 9:{c.fileEncSha256=A.bytes();break}case 10:{c.directPath=A.string();break}case 11:{c.mediaKeyTimestamp=A.int64();break}case 12:{c.contactVcard=A.bool();break}case 13:{c.thumbnailDirectPath=A.string();break}case 14:{c.thumbnailSha256=A.bytes();break}case 15:{c.thumbnailEncSha256=A.bytes();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.thumbnailHeight=A.uint32();break}case 19:{c.thumbnailWidth=A.uint32();break}case 20:{c.caption=A.string();break}case 21:{c.accessibilityLabel=A.string();break}case 22:{c.mediaKeyDomain=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.DocumentMessage)return A;var t=new E.proto.Message.DocumentMessage;if(A.url!=null&&(t.url=String(A.url)),A.mimetype!=null&&(t.mimetype=String(A.mimetype)),A.title!=null&&(t.title=String(A.title)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.fileLength!=null&&(I.Long?(t.fileLength=I.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?t.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?t.fileLength=A.fileLength:typeof A.fileLength=="object"&&(t.fileLength=new I.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.pageCount!=null&&(t.pageCount=A.pageCount>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.fileName!=null&&(t.fileName=String(A.fileName)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(t.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contactVcard!=null&&(t.contactVcard=!!A.contactVcard),A.thumbnailDirectPath!=null&&(t.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?I.base64.decode(A.thumbnailSha256,t.thumbnailSha256=I.newBuffer(I.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(t.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?I.base64.decode(A.thumbnailEncSha256,t.thumbnailEncSha256=I.newBuffer(I.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(t.thumbnailEncSha256=A.thumbnailEncSha256)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.DocumentMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.thumbnailHeight!=null&&(t.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(t.thumbnailWidth=A.thumbnailWidth>>>0),A.caption!=null&&(t.caption=String(A.caption)),A.accessibilityLabel!=null&&(t.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){t.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:t.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:t.mediaKeyDomain=1;break;case"STATUS":case 2:t.mediaKeyDomain=2;break;case"CAPI":case 3:t.mediaKeyDomain=3;break;case"BOT":case 4:t.mediaKeyDomain=4;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,t.oneofs&&(s._mimetype="mimetype")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=t.bytes===String?I.base64.encode(A.fileSha256,0,A.fileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,t.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=t.longs===String?String(A.fileLength):A.fileLength:s.fileLength=t.longs===String?re(A.fileLength,!0):t.longs===Number?ae(A.fileLength,!0):A.fileLength,t.oneofs&&(s._fileLength="fileLength")),A.pageCount!=null&&A.hasOwnProperty("pageCount")&&(s.pageCount=A.pageCount,t.oneofs&&(s._pageCount="pageCount")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.fileName!=null&&A.hasOwnProperty("fileName")&&(s.fileName=A.fileName,t.oneofs&&(s._fileName="fileName")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,t.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=t.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=t.longs===String?re(A.mediaKeyTimestamp):t.longs===Number?ae(A.mediaKeyTimestamp):A.mediaKeyTimestamp,t.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contactVcard!=null&&A.hasOwnProperty("contactVcard")&&(s.contactVcard=A.contactVcard,t.oneofs&&(s._contactVcard="contactVcard")),A.thumbnailDirectPath!=null&&A.hasOwnProperty("thumbnailDirectPath")&&(s.thumbnailDirectPath=A.thumbnailDirectPath,t.oneofs&&(s._thumbnailDirectPath="thumbnailDirectPath")),A.thumbnailSha256!=null&&A.hasOwnProperty("thumbnailSha256")&&(s.thumbnailSha256=t.bytes===String?I.base64.encode(A.thumbnailSha256,0,A.thumbnailSha256.length):t.bytes===Array?Array.prototype.slice.call(A.thumbnailSha256):A.thumbnailSha256,t.oneofs&&(s._thumbnailSha256="thumbnailSha256")),A.thumbnailEncSha256!=null&&A.hasOwnProperty("thumbnailEncSha256")&&(s.thumbnailEncSha256=t.bytes===String?I.base64.encode(A.thumbnailEncSha256,0,A.thumbnailEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.thumbnailEncSha256):A.thumbnailEncSha256,t.oneofs&&(s._thumbnailEncSha256="thumbnailEncSha256")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.thumbnailHeight!=null&&A.hasOwnProperty("thumbnailHeight")&&(s.thumbnailHeight=A.thumbnailHeight,t.oneofs&&(s._thumbnailHeight="thumbnailHeight")),A.thumbnailWidth!=null&&A.hasOwnProperty("thumbnailWidth")&&(s.thumbnailWidth=A.thumbnailWidth,t.oneofs&&(s._thumbnailWidth="thumbnailWidth")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,t.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=t.enums===String?E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,t.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DocumentMessage"},i})(),r.EncCommentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.targetMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.EncCommentMessage)return A;var t=new E.proto.Message.EncCommentMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.EncCommentMessage.targetMessageKey: object expected");t.targetMessageKey=E.proto.MessageKey.fromObject(A.targetMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?I.base64.decode(A.encPayload,t.encPayload=I.newBuffer(I.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(t.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?I.base64.decode(A.encIv,t.encIv=I.newBuffer(I.base64.length(A.encIv)),0):A.encIv.length>=0&&(t.encIv=A.encIv)),t},i.toObject=function(A,t){t||(t={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=E.proto.MessageKey.toObject(A.targetMessageKey,t),t.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=t.bytes===String?I.base64.encode(A.encPayload,0,A.encPayload.length):t.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,t.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=t.bytes===String?I.base64.encode(A.encIv,0,A.encIv.length):t.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,t.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncCommentMessage"},i})(),r.EncEventResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.eventCreationMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.EncEventResponseMessage)return A;var t=new E.proto.Message.EncEventResponseMessage;if(A.eventCreationMessageKey!=null){if(typeof A.eventCreationMessageKey!="object")throw TypeError(".proto.Message.EncEventResponseMessage.eventCreationMessageKey: object expected");t.eventCreationMessageKey=E.proto.MessageKey.fromObject(A.eventCreationMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?I.base64.decode(A.encPayload,t.encPayload=I.newBuffer(I.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(t.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?I.base64.decode(A.encIv,t.encIv=I.newBuffer(I.base64.length(A.encIv)),0):A.encIv.length>=0&&(t.encIv=A.encIv)),t},i.toObject=function(A,t){t||(t={});var s={};return A.eventCreationMessageKey!=null&&A.hasOwnProperty("eventCreationMessageKey")&&(s.eventCreationMessageKey=E.proto.MessageKey.toObject(A.eventCreationMessageKey,t),t.oneofs&&(s._eventCreationMessageKey="eventCreationMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=t.bytes===String?I.base64.encode(A.encPayload,0,A.encPayload.length):t.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,t.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=t.bytes===String?I.base64.encode(A.encIv,0,A.encIv.length):t.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,t.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncEventResponseMessage"},i})(),r.EncReactionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.targetMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.EncReactionMessage)return A;var t=new E.proto.Message.EncReactionMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.EncReactionMessage.targetMessageKey: object expected");t.targetMessageKey=E.proto.MessageKey.fromObject(A.targetMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?I.base64.decode(A.encPayload,t.encPayload=I.newBuffer(I.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(t.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?I.base64.decode(A.encIv,t.encIv=I.newBuffer(I.base64.length(A.encIv)),0):A.encIv.length>=0&&(t.encIv=A.encIv)),t},i.toObject=function(A,t){t||(t={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=E.proto.MessageKey.toObject(A.targetMessageKey,t),t.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=t.bytes===String?I.base64.encode(A.encPayload,0,A.encPayload.length):t.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,t.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=t.bytes===String?I.base64.encode(A.encIv,0,A.encIv.length):t.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,t.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncReactionMessage"},i})(),r.EventMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.isCanceled=A.bool();break}case 3:{c.name=A.string();break}case 4:{c.description=A.string();break}case 5:{c.location=E.proto.Message.LocationMessage.decode(A,A.uint32());break}case 6:{c.joinLink=A.string();break}case 7:{c.startTime=A.int64();break}case 8:{c.endTime=A.int64();break}case 9:{c.extraGuestsAllowed=A.bool();break}case 10:{c.isScheduleCall=A.bool();break}case 11:{c.hasReminder=A.bool();break}case 12:{c.reminderOffsetSec=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.EventMessage)return A;var t=new E.proto.Message.EventMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.EventMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.isCanceled!=null&&(t.isCanceled=!!A.isCanceled),A.name!=null&&(t.name=String(A.name)),A.description!=null&&(t.description=String(A.description)),A.location!=null){if(typeof A.location!="object")throw TypeError(".proto.Message.EventMessage.location: object expected");t.location=E.proto.Message.LocationMessage.fromObject(A.location)}return A.joinLink!=null&&(t.joinLink=String(A.joinLink)),A.startTime!=null&&(I.Long?(t.startTime=I.Long.fromValue(A.startTime)).unsigned=!1:typeof A.startTime=="string"?t.startTime=parseInt(A.startTime,10):typeof A.startTime=="number"?t.startTime=A.startTime:typeof A.startTime=="object"&&(t.startTime=new I.LongBits(A.startTime.low>>>0,A.startTime.high>>>0).toNumber())),A.endTime!=null&&(I.Long?(t.endTime=I.Long.fromValue(A.endTime)).unsigned=!1:typeof A.endTime=="string"?t.endTime=parseInt(A.endTime,10):typeof A.endTime=="number"?t.endTime=A.endTime:typeof A.endTime=="object"&&(t.endTime=new I.LongBits(A.endTime.low>>>0,A.endTime.high>>>0).toNumber())),A.extraGuestsAllowed!=null&&(t.extraGuestsAllowed=!!A.extraGuestsAllowed),A.isScheduleCall!=null&&(t.isScheduleCall=!!A.isScheduleCall),A.hasReminder!=null&&(t.hasReminder=!!A.hasReminder),A.reminderOffsetSec!=null&&(I.Long?(t.reminderOffsetSec=I.Long.fromValue(A.reminderOffsetSec)).unsigned=!1:typeof A.reminderOffsetSec=="string"?t.reminderOffsetSec=parseInt(A.reminderOffsetSec,10):typeof A.reminderOffsetSec=="number"?t.reminderOffsetSec=A.reminderOffsetSec:typeof A.reminderOffsetSec=="object"&&(t.reminderOffsetSec=new I.LongBits(A.reminderOffsetSec.low>>>0,A.reminderOffsetSec.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.isCanceled!=null&&A.hasOwnProperty("isCanceled")&&(s.isCanceled=A.isCanceled,t.oneofs&&(s._isCanceled="isCanceled")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.description!=null&&A.hasOwnProperty("description")&&(s.description=A.description,t.oneofs&&(s._description="description")),A.location!=null&&A.hasOwnProperty("location")&&(s.location=E.proto.Message.LocationMessage.toObject(A.location,t),t.oneofs&&(s._location="location")),A.joinLink!=null&&A.hasOwnProperty("joinLink")&&(s.joinLink=A.joinLink,t.oneofs&&(s._joinLink="joinLink")),A.startTime!=null&&A.hasOwnProperty("startTime")&&(typeof A.startTime=="number"?s.startTime=t.longs===String?String(A.startTime):A.startTime:s.startTime=t.longs===String?re(A.startTime):t.longs===Number?ae(A.startTime):A.startTime,t.oneofs&&(s._startTime="startTime")),A.endTime!=null&&A.hasOwnProperty("endTime")&&(typeof A.endTime=="number"?s.endTime=t.longs===String?String(A.endTime):A.endTime:s.endTime=t.longs===String?re(A.endTime):t.longs===Number?ae(A.endTime):A.endTime,t.oneofs&&(s._endTime="endTime")),A.extraGuestsAllowed!=null&&A.hasOwnProperty("extraGuestsAllowed")&&(s.extraGuestsAllowed=A.extraGuestsAllowed,t.oneofs&&(s._extraGuestsAllowed="extraGuestsAllowed")),A.isScheduleCall!=null&&A.hasOwnProperty("isScheduleCall")&&(s.isScheduleCall=A.isScheduleCall,t.oneofs&&(s._isScheduleCall="isScheduleCall")),A.hasReminder!=null&&A.hasOwnProperty("hasReminder")&&(s.hasReminder=A.hasReminder,t.oneofs&&(s._hasReminder="hasReminder")),A.reminderOffsetSec!=null&&A.hasOwnProperty("reminderOffsetSec")&&(typeof A.reminderOffsetSec=="number"?s.reminderOffsetSec=t.longs===String?String(A.reminderOffsetSec):A.reminderOffsetSec:s.reminderOffsetSec=t.longs===String?re(A.reminderOffsetSec):t.longs===Number?ae(A.reminderOffsetSec):A.reminderOffsetSec,t.oneofs&&(s._reminderOffsetSec="reminderOffsetSec")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EventMessage"},i})(),r.EventResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.response=A.int32();break}case 2:{c.timestampMs=A.int64();break}case 3:{c.extraGuestCount=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.EventResponseMessage)return A;var t=new E.proto.Message.EventResponseMessage;switch(A.response){default:if(typeof A.response=="number"){t.response=A.response;break}break;case"UNKNOWN":case 0:t.response=0;break;case"GOING":case 1:t.response=1;break;case"NOT_GOING":case 2:t.response=2;break;case"MAYBE":case 3:t.response=3;break}return A.timestampMs!=null&&(I.Long?(t.timestampMs=I.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?t.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?t.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(t.timestampMs=new I.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),A.extraGuestCount!=null&&(t.extraGuestCount=A.extraGuestCount|0),t},i.toObject=function(A,t){t||(t={});var s={};return A.response!=null&&A.hasOwnProperty("response")&&(s.response=t.enums===String?E.proto.Message.EventResponseMessage.EventResponseType[A.response]===void 0?A.response:E.proto.Message.EventResponseMessage.EventResponseType[A.response]:A.response,t.oneofs&&(s._response="response")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=t.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=t.longs===String?re(A.timestampMs):t.longs===Number?ae(A.timestampMs):A.timestampMs,t.oneofs&&(s._timestampMs="timestampMs")),A.extraGuestCount!=null&&A.hasOwnProperty("extraGuestCount")&&(s.extraGuestCount=A.extraGuestCount,t.oneofs&&(s._extraGuestCount="extraGuestCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EventResponseMessage"},i.EventResponseType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="GOING"]=1,A[a[2]="NOT_GOING"]=2,A[a[3]="MAYBE"]=3,A})(),i})(),r.ExtendedTextMessage=(function(){function i(a){if(this.endCardTiles=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.text=A.string();break}case 2:{c.matchedText=A.string();break}case 5:{c.description=A.string();break}case 6:{c.title=A.string();break}case 7:{c.textArgb=A.fixed32();break}case 8:{c.backgroundArgb=A.fixed32();break}case 9:{c.font=A.int32();break}case 10:{c.previewType=A.int32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.doNotPlayInline=A.bool();break}case 19:{c.thumbnailDirectPath=A.string();break}case 20:{c.thumbnailSha256=A.bytes();break}case 21:{c.thumbnailEncSha256=A.bytes();break}case 22:{c.mediaKey=A.bytes();break}case 23:{c.mediaKeyTimestamp=A.int64();break}case 24:{c.thumbnailHeight=A.uint32();break}case 25:{c.thumbnailWidth=A.uint32();break}case 26:{c.inviteLinkGroupType=A.int32();break}case 27:{c.inviteLinkParentGroupSubjectV2=A.string();break}case 28:{c.inviteLinkParentGroupThumbnailV2=A.bytes();break}case 29:{c.inviteLinkGroupTypeV2=A.int32();break}case 30:{c.viewOnce=A.bool();break}case 31:{c.videoHeight=A.uint32();break}case 32:{c.videoWidth=A.uint32();break}case 33:{c.faviconMMSMetadata=E.proto.Message.MMSThumbnailMetadata.decode(A,A.uint32());break}case 34:{c.linkPreviewMetadata=E.proto.Message.LinkPreviewMetadata.decode(A,A.uint32());break}case 35:{c.paymentLinkMetadata=E.proto.Message.PaymentLinkMetadata.decode(A,A.uint32());break}case 36:{c.endCardTiles&&c.endCardTiles.length||(c.endCardTiles=[]),c.endCardTiles.push(E.proto.Message.VideoEndCard.decode(A,A.uint32()));break}case 37:{c.videoContentUrl=A.string();break}case 38:{c.musicMetadata=E.proto.EmbeddedMusic.decode(A,A.uint32());break}case 39:{c.paymentExtendedMetadata=E.proto.Message.PaymentExtendedMetadata.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ExtendedTextMessage)return A;var t=new E.proto.Message.ExtendedTextMessage;switch(A.text!=null&&(t.text=String(A.text)),A.matchedText!=null&&(t.matchedText=String(A.matchedText)),A.description!=null&&(t.description=String(A.description)),A.title!=null&&(t.title=String(A.title)),A.textArgb!=null&&(t.textArgb=A.textArgb>>>0),A.backgroundArgb!=null&&(t.backgroundArgb=A.backgroundArgb>>>0),A.font){default:if(typeof A.font=="number"){t.font=A.font;break}break;case"SYSTEM":case 0:t.font=0;break;case"SYSTEM_TEXT":case 1:t.font=1;break;case"FB_SCRIPT":case 2:t.font=2;break;case"SYSTEM_BOLD":case 6:t.font=6;break;case"MORNINGBREEZE_REGULAR":case 7:t.font=7;break;case"CALISTOGA_REGULAR":case 8:t.font=8;break;case"EXO2_EXTRABOLD":case 9:t.font=9;break;case"COURIERPRIME_BOLD":case 10:t.font=10;break}switch(A.previewType){default:if(typeof A.previewType=="number"){t.previewType=A.previewType;break}break;case"NONE":case 0:t.previewType=0;break;case"VIDEO":case 1:t.previewType=1;break;case"PLACEHOLDER":case 4:t.previewType=4;break;case"IMAGE":case 5:t.previewType=5;break;case"PAYMENT_LINKS":case 6:t.previewType=6;break;case"PROFILE":case 7:t.previewType=7;break}if(A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ExtendedTextMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.doNotPlayInline!=null&&(t.doNotPlayInline=!!A.doNotPlayInline),A.thumbnailDirectPath!=null&&(t.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?I.base64.decode(A.thumbnailSha256,t.thumbnailSha256=I.newBuffer(I.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(t.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?I.base64.decode(A.thumbnailEncSha256,t.thumbnailEncSha256=I.newBuffer(I.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(t.thumbnailEncSha256=A.thumbnailEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.thumbnailHeight!=null&&(t.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(t.thumbnailWidth=A.thumbnailWidth>>>0),A.inviteLinkGroupType){default:if(typeof A.inviteLinkGroupType=="number"){t.inviteLinkGroupType=A.inviteLinkGroupType;break}break;case"DEFAULT":case 0:t.inviteLinkGroupType=0;break;case"PARENT":case 1:t.inviteLinkGroupType=1;break;case"SUB":case 2:t.inviteLinkGroupType=2;break;case"DEFAULT_SUB":case 3:t.inviteLinkGroupType=3;break}switch(A.inviteLinkParentGroupSubjectV2!=null&&(t.inviteLinkParentGroupSubjectV2=String(A.inviteLinkParentGroupSubjectV2)),A.inviteLinkParentGroupThumbnailV2!=null&&(typeof A.inviteLinkParentGroupThumbnailV2=="string"?I.base64.decode(A.inviteLinkParentGroupThumbnailV2,t.inviteLinkParentGroupThumbnailV2=I.newBuffer(I.base64.length(A.inviteLinkParentGroupThumbnailV2)),0):A.inviteLinkParentGroupThumbnailV2.length>=0&&(t.inviteLinkParentGroupThumbnailV2=A.inviteLinkParentGroupThumbnailV2)),A.inviteLinkGroupTypeV2){default:if(typeof A.inviteLinkGroupTypeV2=="number"){t.inviteLinkGroupTypeV2=A.inviteLinkGroupTypeV2;break}break;case"DEFAULT":case 0:t.inviteLinkGroupTypeV2=0;break;case"PARENT":case 1:t.inviteLinkGroupTypeV2=1;break;case"SUB":case 2:t.inviteLinkGroupTypeV2=2;break;case"DEFAULT_SUB":case 3:t.inviteLinkGroupTypeV2=3;break}if(A.viewOnce!=null&&(t.viewOnce=!!A.viewOnce),A.videoHeight!=null&&(t.videoHeight=A.videoHeight>>>0),A.videoWidth!=null&&(t.videoWidth=A.videoWidth>>>0),A.faviconMMSMetadata!=null){if(typeof A.faviconMMSMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.faviconMMSMetadata: object expected");t.faviconMMSMetadata=E.proto.Message.MMSThumbnailMetadata.fromObject(A.faviconMMSMetadata)}if(A.linkPreviewMetadata!=null){if(typeof A.linkPreviewMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.linkPreviewMetadata: object expected");t.linkPreviewMetadata=E.proto.Message.LinkPreviewMetadata.fromObject(A.linkPreviewMetadata)}if(A.paymentLinkMetadata!=null){if(typeof A.paymentLinkMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.paymentLinkMetadata: object expected");t.paymentLinkMetadata=E.proto.Message.PaymentLinkMetadata.fromObject(A.paymentLinkMetadata)}if(A.endCardTiles){if(!Array.isArray(A.endCardTiles))throw TypeError(".proto.Message.ExtendedTextMessage.endCardTiles: array expected");t.endCardTiles=[];for(var s=0;s>>3){case 1:{c.requestId=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.FullHistorySyncOnDemandRequestMetadata)return A;var t=new E.proto.Message.FullHistorySyncOnDemandRequestMetadata;return A.requestId!=null&&(t.requestId=String(A.requestId)),t},i.toObject=function(A,t){t||(t={});var s={};return A.requestId!=null&&A.hasOwnProperty("requestId")&&(s.requestId=A.requestId,t.oneofs&&(s._requestId="requestId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.FullHistorySyncOnDemandRequestMetadata"},i})(),r.FutureProofMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.message=E.proto.Message.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.FutureProofMessage)return A;var t=new E.proto.Message.FutureProofMessage;if(A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.FutureProofMessage.message: object expected");t.message=E.proto.Message.fromObject(A.message)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.message!=null&&A.hasOwnProperty("message")&&(s.message=E.proto.Message.toObject(A.message,t),t.oneofs&&(s._message="message")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.FutureProofMessage"},i})(),r.GroupInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.groupJid=A.string();break}case 2:{c.inviteCode=A.string();break}case 3:{c.inviteExpiration=A.int64();break}case 4:{c.groupName=A.string();break}case 5:{c.jpegThumbnail=A.bytes();break}case 6:{c.caption=A.string();break}case 7:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.groupType=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.GroupInviteMessage)return A;var t=new E.proto.Message.GroupInviteMessage;if(A.groupJid!=null&&(t.groupJid=String(A.groupJid)),A.inviteCode!=null&&(t.inviteCode=String(A.inviteCode)),A.inviteExpiration!=null&&(I.Long?(t.inviteExpiration=I.Long.fromValue(A.inviteExpiration)).unsigned=!1:typeof A.inviteExpiration=="string"?t.inviteExpiration=parseInt(A.inviteExpiration,10):typeof A.inviteExpiration=="number"?t.inviteExpiration=A.inviteExpiration:typeof A.inviteExpiration=="object"&&(t.inviteExpiration=new I.LongBits(A.inviteExpiration.low>>>0,A.inviteExpiration.high>>>0).toNumber())),A.groupName!=null&&(t.groupName=String(A.groupName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(t.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.GroupInviteMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.groupType){default:if(typeof A.groupType=="number"){t.groupType=A.groupType;break}break;case"DEFAULT":case 0:t.groupType=0;break;case"PARENT":case 1:t.groupType=1;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.groupJid!=null&&A.hasOwnProperty("groupJid")&&(s.groupJid=A.groupJid,t.oneofs&&(s._groupJid="groupJid")),A.inviteCode!=null&&A.hasOwnProperty("inviteCode")&&(s.inviteCode=A.inviteCode,t.oneofs&&(s._inviteCode="inviteCode")),A.inviteExpiration!=null&&A.hasOwnProperty("inviteExpiration")&&(typeof A.inviteExpiration=="number"?s.inviteExpiration=t.longs===String?String(A.inviteExpiration):A.inviteExpiration:s.inviteExpiration=t.longs===String?re(A.inviteExpiration):t.longs===Number?ae(A.inviteExpiration):A.inviteExpiration,t.oneofs&&(s._inviteExpiration="inviteExpiration")),A.groupName!=null&&A.hasOwnProperty("groupName")&&(s.groupName=A.groupName,t.oneofs&&(s._groupName="groupName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.groupType!=null&&A.hasOwnProperty("groupType")&&(s.groupType=t.enums===String?E.proto.Message.GroupInviteMessage.GroupType[A.groupType]===void 0?A.groupType:E.proto.Message.GroupInviteMessage.GroupType[A.groupType]:A.groupType,t.oneofs&&(s._groupType="groupType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.GroupInviteMessage"},i.GroupType=(function(){let a={},A=Object.create(a);return A[a[0]="DEFAULT"]=0,A[a[1]="PARENT"]=1,A})(),i})(),r.HighlyStructuredMessage=(function(){function i(a){if(this.params=[],this.localizableParams=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.namespace=A.string();break}case 2:{c.elementName=A.string();break}case 3:{c.params&&c.params.length||(c.params=[]),c.params.push(A.string());break}case 4:{c.fallbackLg=A.string();break}case 5:{c.fallbackLc=A.string();break}case 6:{c.localizableParams&&c.localizableParams.length||(c.localizableParams=[]),c.localizableParams.push(E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.decode(A,A.uint32()));break}case 7:{c.deterministicLg=A.string();break}case 8:{c.deterministicLc=A.string();break}case 9:{c.hydratedHsm=E.proto.Message.TemplateMessage.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.HighlyStructuredMessage)return A;var t=new E.proto.Message.HighlyStructuredMessage;if(A.namespace!=null&&(t.namespace=String(A.namespace)),A.elementName!=null&&(t.elementName=String(A.elementName)),A.params){if(!Array.isArray(A.params))throw TypeError(".proto.Message.HighlyStructuredMessage.params: array expected");t.params=[];for(var s=0;s>>3){case 1:{p.default=s.string();break}case 2:{p.currency=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.decode(s,s.uint32());break}case 3:{p.dateTime=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter)return s;var g=new E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter;if(s.default!=null&&(g.default=String(s.default)),s.currency!=null){if(typeof s.currency!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.currency: object expected");g.currency=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.fromObject(s.currency)}if(s.dateTime!=null){if(typeof s.dateTime!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.dateTime: object expected");g.dateTime=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.fromObject(s.dateTime)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.default!=null&&s.hasOwnProperty("default")&&(c.default=s.default,g.oneofs&&(c._default="default")),s.currency!=null&&s.hasOwnProperty("currency")&&(c.currency=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.toObject(s.currency,g),g.oneofs&&(c.paramOneof="currency")),s.dateTime!=null&&s.hasOwnProperty("dateTime")&&(c.dateTime=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.toObject(s.dateTime,g),g.oneofs&&(c.paramOneof="dateTime")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter"},a.HSMCurrency=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.currencyCode=c.string();break}case 2:{Q.amount1000=c.int64();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency)return c;var l=new E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency;return c.currencyCode!=null&&(l.currencyCode=String(c.currencyCode)),c.amount1000!=null&&(I.Long?(l.amount1000=I.Long.fromValue(c.amount1000)).unsigned=!1:typeof c.amount1000=="string"?l.amount1000=parseInt(c.amount1000,10):typeof c.amount1000=="number"?l.amount1000=c.amount1000:typeof c.amount1000=="object"&&(l.amount1000=new I.LongBits(c.amount1000.low>>>0,c.amount1000.high>>>0).toNumber())),l},t.toObject=function(c,l){l||(l={});var p={};return c.currencyCode!=null&&c.hasOwnProperty("currencyCode")&&(p.currencyCode=c.currencyCode,l.oneofs&&(p._currencyCode="currencyCode")),c.amount1000!=null&&c.hasOwnProperty("amount1000")&&(typeof c.amount1000=="number"?p.amount1000=l.longs===String?String(c.amount1000):c.amount1000:p.amount1000=l.longs===String?re(c.amount1000):l.longs===Number?ae(c.amount1000):c.amount1000,l.oneofs&&(p._amount1000="amount1000")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency"},t})(),a.HSMDateTime=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.component=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.decode(c,c.uint32());break}case 2:{Q.unixEpoch=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.decode(c,c.uint32());break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime)return c;var l=new E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime;if(c.component!=null){if(typeof c.component!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.component: object expected");l.component=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.fromObject(c.component)}if(c.unixEpoch!=null){if(typeof c.unixEpoch!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.unixEpoch: object expected");l.unixEpoch=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.fromObject(c.unixEpoch)}return l},t.toObject=function(c,l){l||(l={});var p={};return c.component!=null&&c.hasOwnProperty("component")&&(p.component=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.toObject(c.component,l),l.oneofs&&(p.datetimeOneof="component")),c.unixEpoch!=null&&c.hasOwnProperty("unixEpoch")&&(p.unixEpoch=E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.toObject(c.unixEpoch,l),l.oneofs&&(p.datetimeOneof="unixEpoch")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime"},t.HSMDateTimeComponent=(function(){function g(l){if(l)for(var p=Object.keys(l),B=0;B>>3){case 1:{y.dayOfWeek=p.int32();break}case 2:{y.year=p.uint32();break}case 3:{y.month=p.uint32();break}case 4:{y.dayOfMonth=p.uint32();break}case 5:{y.hour=p.uint32();break}case 6:{y.minute=p.uint32();break}case 7:{y.calendar=p.int32();break}default:p.skipType(m&7);break}}return y},g.fromObject=function(p){if(p instanceof E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent)return p;var B=new E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent;switch(p.dayOfWeek){default:if(typeof p.dayOfWeek=="number"){B.dayOfWeek=p.dayOfWeek;break}break;case"MONDAY":case 1:B.dayOfWeek=1;break;case"TUESDAY":case 2:B.dayOfWeek=2;break;case"WEDNESDAY":case 3:B.dayOfWeek=3;break;case"THURSDAY":case 4:B.dayOfWeek=4;break;case"FRIDAY":case 5:B.dayOfWeek=5;break;case"SATURDAY":case 6:B.dayOfWeek=6;break;case"SUNDAY":case 7:B.dayOfWeek=7;break}switch(p.year!=null&&(B.year=p.year>>>0),p.month!=null&&(B.month=p.month>>>0),p.dayOfMonth!=null&&(B.dayOfMonth=p.dayOfMonth>>>0),p.hour!=null&&(B.hour=p.hour>>>0),p.minute!=null&&(B.minute=p.minute>>>0),p.calendar){default:if(typeof p.calendar=="number"){B.calendar=p.calendar;break}break;case"GREGORIAN":case 1:B.calendar=1;break;case"SOLAR_HIJRI":case 2:B.calendar=2;break}return B},g.toObject=function(p,B){B||(B={});var Q={};return p.dayOfWeek!=null&&p.hasOwnProperty("dayOfWeek")&&(Q.dayOfWeek=B.enums===String?E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.DayOfWeekType[p.dayOfWeek]===void 0?p.dayOfWeek:E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.DayOfWeekType[p.dayOfWeek]:p.dayOfWeek,B.oneofs&&(Q._dayOfWeek="dayOfWeek")),p.year!=null&&p.hasOwnProperty("year")&&(Q.year=p.year,B.oneofs&&(Q._year="year")),p.month!=null&&p.hasOwnProperty("month")&&(Q.month=p.month,B.oneofs&&(Q._month="month")),p.dayOfMonth!=null&&p.hasOwnProperty("dayOfMonth")&&(Q.dayOfMonth=p.dayOfMonth,B.oneofs&&(Q._dayOfMonth="dayOfMonth")),p.hour!=null&&p.hasOwnProperty("hour")&&(Q.hour=p.hour,B.oneofs&&(Q._hour="hour")),p.minute!=null&&p.hasOwnProperty("minute")&&(Q.minute=p.minute,B.oneofs&&(Q._minute="minute")),p.calendar!=null&&p.hasOwnProperty("calendar")&&(Q.calendar=B.enums===String?E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.CalendarType[p.calendar]===void 0?p.calendar:E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.CalendarType[p.calendar]:p.calendar,B.oneofs&&(Q._calendar="calendar")),Q},g.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},g.getTypeUrl=function(p){return p===void 0&&(p="type.googleapis.com"),p+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent"},g.CalendarType=(function(){let l={},p=Object.create(l);return p[l[1]="GREGORIAN"]=1,p[l[2]="SOLAR_HIJRI"]=2,p})(),g.DayOfWeekType=(function(){let l={},p=Object.create(l);return p[l[1]="MONDAY"]=1,p[l[2]="TUESDAY"]=2,p[l[3]="WEDNESDAY"]=3,p[l[4]="THURSDAY"]=4,p[l[5]="FRIDAY"]=5,p[l[6]="SATURDAY"]=6,p[l[7]="SUNDAY"]=7,p})(),g})(),t.HSMDateTimeUnixEpoch=(function(){function g(l){if(l)for(var p=Object.keys(l),B=0;B>>3){case 1:{y.timestamp=p.int64();break}default:p.skipType(m&7);break}}return y},g.fromObject=function(p){if(p instanceof E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch)return p;var B=new E.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch;return p.timestamp!=null&&(I.Long?(B.timestamp=I.Long.fromValue(p.timestamp)).unsigned=!1:typeof p.timestamp=="string"?B.timestamp=parseInt(p.timestamp,10):typeof p.timestamp=="number"?B.timestamp=p.timestamp:typeof p.timestamp=="object"&&(B.timestamp=new I.LongBits(p.timestamp.low>>>0,p.timestamp.high>>>0).toNumber())),B},g.toObject=function(p,B){B||(B={});var Q={};return p.timestamp!=null&&p.hasOwnProperty("timestamp")&&(typeof p.timestamp=="number"?Q.timestamp=B.longs===String?String(p.timestamp):p.timestamp:Q.timestamp=B.longs===String?re(p.timestamp):B.longs===Number?ae(p.timestamp):p.timestamp,B.oneofs&&(Q._timestamp="timestamp")),Q},g.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},g.getTypeUrl=function(p){return p===void 0&&(p="type.googleapis.com"),p+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch"},g})(),t})(),a})(),i})(),r.HistorySyncMessageAccessStatus=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.completeAccessGranted=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.HistorySyncMessageAccessStatus)return A;var t=new E.proto.Message.HistorySyncMessageAccessStatus;return A.completeAccessGranted!=null&&(t.completeAccessGranted=!!A.completeAccessGranted),t},i.toObject=function(A,t){t||(t={});var s={};return A.completeAccessGranted!=null&&A.hasOwnProperty("completeAccessGranted")&&(s.completeAccessGranted=A.completeAccessGranted,t.oneofs&&(s._completeAccessGranted="completeAccessGranted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.HistorySyncMessageAccessStatus"},i})(),r.HistorySyncNotification=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.fileSha256=A.bytes();break}case 2:{c.fileLength=A.uint64();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}case 6:{c.syncType=A.int32();break}case 7:{c.chunkOrder=A.uint32();break}case 8:{c.originalMessageId=A.string();break}case 9:{c.progress=A.uint32();break}case 10:{c.oldestMsgInChunkTimestampSec=A.int64();break}case 11:{c.initialHistBootstrapInlinePayload=A.bytes();break}case 12:{c.peerDataRequestSessionId=A.string();break}case 13:{c.fullHistorySyncOnDemandRequestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(A,A.uint32());break}case 14:{c.encHandle=A.string();break}case 15:{c.messageAccessStatus=E.proto.Message.HistorySyncMessageAccessStatus.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.HistorySyncNotification)return A;var t=new E.proto.Message.HistorySyncNotification;switch(A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.fileLength!=null&&(I.Long?(t.fileLength=I.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?t.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?t.fileLength=A.fileLength:typeof A.fileLength=="object"&&(t.fileLength=new I.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(t.directPath=String(A.directPath)),A.syncType){default:if(typeof A.syncType=="number"){t.syncType=A.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:t.syncType=0;break;case"INITIAL_STATUS_V3":case 1:t.syncType=1;break;case"FULL":case 2:t.syncType=2;break;case"RECENT":case 3:t.syncType=3;break;case"PUSH_NAME":case 4:t.syncType=4;break;case"NON_BLOCKING_DATA":case 5:t.syncType=5;break;case"ON_DEMAND":case 6:t.syncType=6;break;case"NO_HISTORY":case 7:t.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:t.syncType=8;break}if(A.chunkOrder!=null&&(t.chunkOrder=A.chunkOrder>>>0),A.originalMessageId!=null&&(t.originalMessageId=String(A.originalMessageId)),A.progress!=null&&(t.progress=A.progress>>>0),A.oldestMsgInChunkTimestampSec!=null&&(I.Long?(t.oldestMsgInChunkTimestampSec=I.Long.fromValue(A.oldestMsgInChunkTimestampSec)).unsigned=!1:typeof A.oldestMsgInChunkTimestampSec=="string"?t.oldestMsgInChunkTimestampSec=parseInt(A.oldestMsgInChunkTimestampSec,10):typeof A.oldestMsgInChunkTimestampSec=="number"?t.oldestMsgInChunkTimestampSec=A.oldestMsgInChunkTimestampSec:typeof A.oldestMsgInChunkTimestampSec=="object"&&(t.oldestMsgInChunkTimestampSec=new I.LongBits(A.oldestMsgInChunkTimestampSec.low>>>0,A.oldestMsgInChunkTimestampSec.high>>>0).toNumber())),A.initialHistBootstrapInlinePayload!=null&&(typeof A.initialHistBootstrapInlinePayload=="string"?I.base64.decode(A.initialHistBootstrapInlinePayload,t.initialHistBootstrapInlinePayload=I.newBuffer(I.base64.length(A.initialHistBootstrapInlinePayload)),0):A.initialHistBootstrapInlinePayload.length>=0&&(t.initialHistBootstrapInlinePayload=A.initialHistBootstrapInlinePayload)),A.peerDataRequestSessionId!=null&&(t.peerDataRequestSessionId=String(A.peerDataRequestSessionId)),A.fullHistorySyncOnDemandRequestMetadata!=null){if(typeof A.fullHistorySyncOnDemandRequestMetadata!="object")throw TypeError(".proto.Message.HistorySyncNotification.fullHistorySyncOnDemandRequestMetadata: object expected");t.fullHistorySyncOnDemandRequestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(A.fullHistorySyncOnDemandRequestMetadata)}if(A.encHandle!=null&&(t.encHandle=String(A.encHandle)),A.messageAccessStatus!=null){if(typeof A.messageAccessStatus!="object")throw TypeError(".proto.Message.HistorySyncNotification.messageAccessStatus: object expected");t.messageAccessStatus=E.proto.Message.HistorySyncMessageAccessStatus.fromObject(A.messageAccessStatus)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=t.bytes===String?I.base64.encode(A.fileSha256,0,A.fileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,t.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=t.longs===String?String(A.fileLength):A.fileLength:s.fileLength=t.longs===String?re(A.fileLength,!0):t.longs===Number?ae(A.fileLength,!0):A.fileLength,t.oneofs&&(s._fileLength="fileLength")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,t.oneofs&&(s._directPath="directPath")),A.syncType!=null&&A.hasOwnProperty("syncType")&&(s.syncType=t.enums===String?E.proto.Message.HistorySyncType[A.syncType]===void 0?A.syncType:E.proto.Message.HistorySyncType[A.syncType]:A.syncType,t.oneofs&&(s._syncType="syncType")),A.chunkOrder!=null&&A.hasOwnProperty("chunkOrder")&&(s.chunkOrder=A.chunkOrder,t.oneofs&&(s._chunkOrder="chunkOrder")),A.originalMessageId!=null&&A.hasOwnProperty("originalMessageId")&&(s.originalMessageId=A.originalMessageId,t.oneofs&&(s._originalMessageId="originalMessageId")),A.progress!=null&&A.hasOwnProperty("progress")&&(s.progress=A.progress,t.oneofs&&(s._progress="progress")),A.oldestMsgInChunkTimestampSec!=null&&A.hasOwnProperty("oldestMsgInChunkTimestampSec")&&(typeof A.oldestMsgInChunkTimestampSec=="number"?s.oldestMsgInChunkTimestampSec=t.longs===String?String(A.oldestMsgInChunkTimestampSec):A.oldestMsgInChunkTimestampSec:s.oldestMsgInChunkTimestampSec=t.longs===String?re(A.oldestMsgInChunkTimestampSec):t.longs===Number?ae(A.oldestMsgInChunkTimestampSec):A.oldestMsgInChunkTimestampSec,t.oneofs&&(s._oldestMsgInChunkTimestampSec="oldestMsgInChunkTimestampSec")),A.initialHistBootstrapInlinePayload!=null&&A.hasOwnProperty("initialHistBootstrapInlinePayload")&&(s.initialHistBootstrapInlinePayload=t.bytes===String?I.base64.encode(A.initialHistBootstrapInlinePayload,0,A.initialHistBootstrapInlinePayload.length):t.bytes===Array?Array.prototype.slice.call(A.initialHistBootstrapInlinePayload):A.initialHistBootstrapInlinePayload,t.oneofs&&(s._initialHistBootstrapInlinePayload="initialHistBootstrapInlinePayload")),A.peerDataRequestSessionId!=null&&A.hasOwnProperty("peerDataRequestSessionId")&&(s.peerDataRequestSessionId=A.peerDataRequestSessionId,t.oneofs&&(s._peerDataRequestSessionId="peerDataRequestSessionId")),A.fullHistorySyncOnDemandRequestMetadata!=null&&A.hasOwnProperty("fullHistorySyncOnDemandRequestMetadata")&&(s.fullHistorySyncOnDemandRequestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(A.fullHistorySyncOnDemandRequestMetadata,t),t.oneofs&&(s._fullHistorySyncOnDemandRequestMetadata="fullHistorySyncOnDemandRequestMetadata")),A.encHandle!=null&&A.hasOwnProperty("encHandle")&&(s.encHandle=A.encHandle,t.oneofs&&(s._encHandle="encHandle")),A.messageAccessStatus!=null&&A.hasOwnProperty("messageAccessStatus")&&(s.messageAccessStatus=E.proto.Message.HistorySyncMessageAccessStatus.toObject(A.messageAccessStatus,t),t.oneofs&&(s._messageAccessStatus="messageAccessStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.HistorySyncNotification"},i})(),r.HistorySyncType=(function(){let i={},e=Object.create(i);return e[i[0]="INITIAL_BOOTSTRAP"]=0,e[i[1]="INITIAL_STATUS_V3"]=1,e[i[2]="FULL"]=2,e[i[3]="RECENT"]=3,e[i[4]="PUSH_NAME"]=4,e[i[5]="NON_BLOCKING_DATA"]=5,e[i[6]="ON_DEMAND"]=6,e[i[7]="NO_HISTORY"]=7,e[i[8]="MESSAGE_ACCESS_STATUS"]=8,e})(),r.ImageMessage=(function(){function i(a){if(this.interactiveAnnotations=[],this.scanLengths=[],this.annotations=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.caption=A.string();break}case 4:{c.fileSha256=A.bytes();break}case 5:{c.fileLength=A.uint64();break}case 6:{c.height=A.uint32();break}case 7:{c.width=A.uint32();break}case 8:{c.mediaKey=A.bytes();break}case 9:{c.fileEncSha256=A.bytes();break}case 10:{c.interactiveAnnotations&&c.interactiveAnnotations.length||(c.interactiveAnnotations=[]),c.interactiveAnnotations.push(E.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 11:{c.directPath=A.string();break}case 12:{c.mediaKeyTimestamp=A.int64();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.firstScanSidecar=A.bytes();break}case 19:{c.firstScanLength=A.uint32();break}case 20:{c.experimentGroupId=A.uint32();break}case 21:{c.scansSidecar=A.bytes();break}case 22:{if(c.scanLengths&&c.scanLengths.length||(c.scanLengths=[]),(l&7)===2)for(var p=A.uint32()+A.pos;A.pos=0&&(t.fileSha256=A.fileSha256)),A.fileLength!=null&&(I.Long?(t.fileLength=I.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?t.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?t.fileLength=A.fileLength:typeof A.fileLength=="object"&&(t.fileLength=new I.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.height!=null&&(t.height=A.height>>>0),A.width!=null&&(t.width=A.width>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.interactiveAnnotations){if(!Array.isArray(A.interactiveAnnotations))throw TypeError(".proto.Message.ImageMessage.interactiveAnnotations: array expected");t.interactiveAnnotations=[];for(var s=0;s>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ImageMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.firstScanSidecar!=null&&(typeof A.firstScanSidecar=="string"?I.base64.decode(A.firstScanSidecar,t.firstScanSidecar=I.newBuffer(I.base64.length(A.firstScanSidecar)),0):A.firstScanSidecar.length>=0&&(t.firstScanSidecar=A.firstScanSidecar)),A.firstScanLength!=null&&(t.firstScanLength=A.firstScanLength>>>0),A.experimentGroupId!=null&&(t.experimentGroupId=A.experimentGroupId>>>0),A.scansSidecar!=null&&(typeof A.scansSidecar=="string"?I.base64.decode(A.scansSidecar,t.scansSidecar=I.newBuffer(I.base64.length(A.scansSidecar)),0):A.scansSidecar.length>=0&&(t.scansSidecar=A.scansSidecar)),A.scanLengths){if(!Array.isArray(A.scanLengths))throw TypeError(".proto.Message.ImageMessage.scanLengths: array expected");t.scanLengths=[];for(var s=0;s>>0}if(A.midQualityFileSha256!=null&&(typeof A.midQualityFileSha256=="string"?I.base64.decode(A.midQualityFileSha256,t.midQualityFileSha256=I.newBuffer(I.base64.length(A.midQualityFileSha256)),0):A.midQualityFileSha256.length>=0&&(t.midQualityFileSha256=A.midQualityFileSha256)),A.midQualityFileEncSha256!=null&&(typeof A.midQualityFileEncSha256=="string"?I.base64.decode(A.midQualityFileEncSha256,t.midQualityFileEncSha256=I.newBuffer(I.base64.length(A.midQualityFileEncSha256)),0):A.midQualityFileEncSha256.length>=0&&(t.midQualityFileEncSha256=A.midQualityFileEncSha256)),A.viewOnce!=null&&(t.viewOnce=!!A.viewOnce),A.thumbnailDirectPath!=null&&(t.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?I.base64.decode(A.thumbnailSha256,t.thumbnailSha256=I.newBuffer(I.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(t.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?I.base64.decode(A.thumbnailEncSha256,t.thumbnailEncSha256=I.newBuffer(I.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(t.thumbnailEncSha256=A.thumbnailEncSha256)),A.staticUrl!=null&&(t.staticUrl=String(A.staticUrl)),A.annotations){if(!Array.isArray(A.annotations))throw TypeError(".proto.Message.ImageMessage.annotations: array expected");t.annotations=[];for(var s=0;s>>3){case 1:{c.securityNotificationEnabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.InitialSecurityNotificationSettingSync)return A;var t=new E.proto.Message.InitialSecurityNotificationSettingSync;return A.securityNotificationEnabled!=null&&(t.securityNotificationEnabled=!!A.securityNotificationEnabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.securityNotificationEnabled!=null&&A.hasOwnProperty("securityNotificationEnabled")&&(s.securityNotificationEnabled=A.securityNotificationEnabled,t.oneofs&&(s._securityNotificationEnabled="securityNotificationEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InitialSecurityNotificationSettingSync"},i})(),r.InteractiveMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.header=E.proto.Message.InteractiveMessage.Header.decode(A,A.uint32());break}case 2:{c.body=E.proto.Message.InteractiveMessage.Body.decode(A,A.uint32());break}case 3:{c.footer=E.proto.Message.InteractiveMessage.Footer.decode(A,A.uint32());break}case 15:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 16:{c.urlTrackingMap=E.proto.UrlTrackingMap.decode(A,A.uint32());break}case 4:{c.shopStorefrontMessage=E.proto.Message.InteractiveMessage.ShopMessage.decode(A,A.uint32());break}case 5:{c.collectionMessage=E.proto.Message.InteractiveMessage.CollectionMessage.decode(A,A.uint32());break}case 6:{c.nativeFlowMessage=E.proto.Message.InteractiveMessage.NativeFlowMessage.decode(A,A.uint32());break}case 7:{c.carouselMessage=E.proto.Message.InteractiveMessage.CarouselMessage.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.InteractiveMessage)return A;var t=new E.proto.Message.InteractiveMessage;if(A.header!=null){if(typeof A.header!="object")throw TypeError(".proto.Message.InteractiveMessage.header: object expected");t.header=E.proto.Message.InteractiveMessage.Header.fromObject(A.header)}if(A.body!=null){if(typeof A.body!="object")throw TypeError(".proto.Message.InteractiveMessage.body: object expected");t.body=E.proto.Message.InteractiveMessage.Body.fromObject(A.body)}if(A.footer!=null){if(typeof A.footer!="object")throw TypeError(".proto.Message.InteractiveMessage.footer: object expected");t.footer=E.proto.Message.InteractiveMessage.Footer.fromObject(A.footer)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.InteractiveMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.urlTrackingMap!=null){if(typeof A.urlTrackingMap!="object")throw TypeError(".proto.Message.InteractiveMessage.urlTrackingMap: object expected");t.urlTrackingMap=E.proto.UrlTrackingMap.fromObject(A.urlTrackingMap)}if(A.shopStorefrontMessage!=null){if(typeof A.shopStorefrontMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.shopStorefrontMessage: object expected");t.shopStorefrontMessage=E.proto.Message.InteractiveMessage.ShopMessage.fromObject(A.shopStorefrontMessage)}if(A.collectionMessage!=null){if(typeof A.collectionMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.collectionMessage: object expected");t.collectionMessage=E.proto.Message.InteractiveMessage.CollectionMessage.fromObject(A.collectionMessage)}if(A.nativeFlowMessage!=null){if(typeof A.nativeFlowMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.nativeFlowMessage: object expected");t.nativeFlowMessage=E.proto.Message.InteractiveMessage.NativeFlowMessage.fromObject(A.nativeFlowMessage)}if(A.carouselMessage!=null){if(typeof A.carouselMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.carouselMessage: object expected");t.carouselMessage=E.proto.Message.InteractiveMessage.CarouselMessage.fromObject(A.carouselMessage)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.header!=null&&A.hasOwnProperty("header")&&(s.header=E.proto.Message.InteractiveMessage.Header.toObject(A.header,t),t.oneofs&&(s._header="header")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=E.proto.Message.InteractiveMessage.Body.toObject(A.body,t),t.oneofs&&(s._body="body")),A.footer!=null&&A.hasOwnProperty("footer")&&(s.footer=E.proto.Message.InteractiveMessage.Footer.toObject(A.footer,t),t.oneofs&&(s._footer="footer")),A.shopStorefrontMessage!=null&&A.hasOwnProperty("shopStorefrontMessage")&&(s.shopStorefrontMessage=E.proto.Message.InteractiveMessage.ShopMessage.toObject(A.shopStorefrontMessage,t),t.oneofs&&(s.interactiveMessage="shopStorefrontMessage")),A.collectionMessage!=null&&A.hasOwnProperty("collectionMessage")&&(s.collectionMessage=E.proto.Message.InteractiveMessage.CollectionMessage.toObject(A.collectionMessage,t),t.oneofs&&(s.interactiveMessage="collectionMessage")),A.nativeFlowMessage!=null&&A.hasOwnProperty("nativeFlowMessage")&&(s.nativeFlowMessage=E.proto.Message.InteractiveMessage.NativeFlowMessage.toObject(A.nativeFlowMessage,t),t.oneofs&&(s.interactiveMessage="nativeFlowMessage")),A.carouselMessage!=null&&A.hasOwnProperty("carouselMessage")&&(s.carouselMessage=E.proto.Message.InteractiveMessage.CarouselMessage.toObject(A.carouselMessage,t),t.oneofs&&(s.interactiveMessage="carouselMessage")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.urlTrackingMap!=null&&A.hasOwnProperty("urlTrackingMap")&&(s.urlTrackingMap=E.proto.UrlTrackingMap.toObject(A.urlTrackingMap,t),t.oneofs&&(s._urlTrackingMap="urlTrackingMap")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InteractiveMessage"},i.Body=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.text=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveMessage.Body)return s;var g=new E.proto.Message.InteractiveMessage.Body;return s.text!=null&&(g.text=String(s.text)),g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Body"},a})(),i.CarouselMessage=(function(){function a(t){if(this.cards=[],t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.cards&&p.cards.length||(p.cards=[]),p.cards.push(E.proto.Message.InteractiveMessage.decode(s,s.uint32()));break}case 2:{p.messageVersion=s.int32();break}case 3:{p.carouselCardType=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveMessage.CarouselMessage)return s;var g=new E.proto.Message.InteractiveMessage.CarouselMessage;if(s.cards){if(!Array.isArray(s.cards))throw TypeError(".proto.Message.InteractiveMessage.CarouselMessage.cards: array expected");g.cards=[];for(var c=0;c>>3){case 1:{p.bizJid=s.string();break}case 2:{p.id=s.string();break}case 3:{p.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveMessage.CollectionMessage)return s;var g=new E.proto.Message.InteractiveMessage.CollectionMessage;return s.bizJid!=null&&(g.bizJid=String(s.bizJid)),s.id!=null&&(g.id=String(s.id)),s.messageVersion!=null&&(g.messageVersion=s.messageVersion|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.bizJid!=null&&s.hasOwnProperty("bizJid")&&(c.bizJid=s.bizJid,g.oneofs&&(c._bizJid="bizJid")),s.id!=null&&s.hasOwnProperty("id")&&(c.id=s.id,g.oneofs&&(c._id="id")),s.messageVersion!=null&&s.hasOwnProperty("messageVersion")&&(c.messageVersion=s.messageVersion,g.oneofs&&(c._messageVersion="messageVersion")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.CollectionMessage"},a})(),i.Footer=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.text=s.string();break}case 3:{p.hasMediaAttachment=s.bool();break}case 2:{p.audioMessage=E.proto.Message.AudioMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveMessage.Footer)return s;var g=new E.proto.Message.InteractiveMessage.Footer;if(s.text!=null&&(g.text=String(s.text)),s.hasMediaAttachment!=null&&(g.hasMediaAttachment=!!s.hasMediaAttachment),s.audioMessage!=null){if(typeof s.audioMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Footer.audioMessage: object expected");g.audioMessage=E.proto.Message.AudioMessage.fromObject(s.audioMessage)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),s.audioMessage!=null&&s.hasOwnProperty("audioMessage")&&(c.audioMessage=E.proto.Message.AudioMessage.toObject(s.audioMessage,g),g.oneofs&&(c.media="audioMessage")),s.hasMediaAttachment!=null&&s.hasOwnProperty("hasMediaAttachment")&&(c.hasMediaAttachment=s.hasMediaAttachment,g.oneofs&&(c._hasMediaAttachment="hasMediaAttachment")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Footer"},a})(),i.Header=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.title=s.string();break}case 2:{p.subtitle=s.string();break}case 5:{p.hasMediaAttachment=s.bool();break}case 3:{p.documentMessage=E.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 4:{p.imageMessage=E.proto.Message.ImageMessage.decode(s,s.uint32());break}case 6:{p.jpegThumbnail=s.bytes();break}case 7:{p.videoMessage=E.proto.Message.VideoMessage.decode(s,s.uint32());break}case 8:{p.locationMessage=E.proto.Message.LocationMessage.decode(s,s.uint32());break}case 9:{p.productMessage=E.proto.Message.ProductMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveMessage.Header)return s;var g=new E.proto.Message.InteractiveMessage.Header;if(s.title!=null&&(g.title=String(s.title)),s.subtitle!=null&&(g.subtitle=String(s.subtitle)),s.hasMediaAttachment!=null&&(g.hasMediaAttachment=!!s.hasMediaAttachment),s.documentMessage!=null){if(typeof s.documentMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.documentMessage: object expected");g.documentMessage=E.proto.Message.DocumentMessage.fromObject(s.documentMessage)}if(s.imageMessage!=null){if(typeof s.imageMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.imageMessage: object expected");g.imageMessage=E.proto.Message.ImageMessage.fromObject(s.imageMessage)}if(s.jpegThumbnail!=null&&(typeof s.jpegThumbnail=="string"?I.base64.decode(s.jpegThumbnail,g.jpegThumbnail=I.newBuffer(I.base64.length(s.jpegThumbnail)),0):s.jpegThumbnail.length>=0&&(g.jpegThumbnail=s.jpegThumbnail)),s.videoMessage!=null){if(typeof s.videoMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.videoMessage: object expected");g.videoMessage=E.proto.Message.VideoMessage.fromObject(s.videoMessage)}if(s.locationMessage!=null){if(typeof s.locationMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.locationMessage: object expected");g.locationMessage=E.proto.Message.LocationMessage.fromObject(s.locationMessage)}if(s.productMessage!=null){if(typeof s.productMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.productMessage: object expected");g.productMessage=E.proto.Message.ProductMessage.fromObject(s.productMessage)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.subtitle!=null&&s.hasOwnProperty("subtitle")&&(c.subtitle=s.subtitle,g.oneofs&&(c._subtitle="subtitle")),s.documentMessage!=null&&s.hasOwnProperty("documentMessage")&&(c.documentMessage=E.proto.Message.DocumentMessage.toObject(s.documentMessage,g),g.oneofs&&(c.media="documentMessage")),s.imageMessage!=null&&s.hasOwnProperty("imageMessage")&&(c.imageMessage=E.proto.Message.ImageMessage.toObject(s.imageMessage,g),g.oneofs&&(c.media="imageMessage")),s.hasMediaAttachment!=null&&s.hasOwnProperty("hasMediaAttachment")&&(c.hasMediaAttachment=s.hasMediaAttachment,g.oneofs&&(c._hasMediaAttachment="hasMediaAttachment")),s.jpegThumbnail!=null&&s.hasOwnProperty("jpegThumbnail")&&(c.jpegThumbnail=g.bytes===String?I.base64.encode(s.jpegThumbnail,0,s.jpegThumbnail.length):g.bytes===Array?Array.prototype.slice.call(s.jpegThumbnail):s.jpegThumbnail,g.oneofs&&(c.media="jpegThumbnail")),s.videoMessage!=null&&s.hasOwnProperty("videoMessage")&&(c.videoMessage=E.proto.Message.VideoMessage.toObject(s.videoMessage,g),g.oneofs&&(c.media="videoMessage")),s.locationMessage!=null&&s.hasOwnProperty("locationMessage")&&(c.locationMessage=E.proto.Message.LocationMessage.toObject(s.locationMessage,g),g.oneofs&&(c.media="locationMessage")),s.productMessage!=null&&s.hasOwnProperty("productMessage")&&(c.productMessage=E.proto.Message.ProductMessage.toObject(s.productMessage,g),g.oneofs&&(c.media="productMessage")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Header"},a})(),i.NativeFlowMessage=(function(){function a(t){if(this.buttons=[],t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.buttons&&p.buttons.length||(p.buttons=[]),p.buttons.push(E.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton.decode(s,s.uint32()));break}case 2:{p.messageParamsJson=s.string();break}case 3:{p.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveMessage.NativeFlowMessage)return s;var g=new E.proto.Message.InteractiveMessage.NativeFlowMessage;if(s.buttons){if(!Array.isArray(s.buttons))throw TypeError(".proto.Message.InteractiveMessage.NativeFlowMessage.buttons: array expected");g.buttons=[];for(var c=0;c>>3){case 1:{Q.name=c.string();break}case 2:{Q.buttonParamsJson=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton)return c;var l=new E.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton;return c.name!=null&&(l.name=String(c.name)),c.buttonParamsJson!=null&&(l.buttonParamsJson=String(c.buttonParamsJson)),l},t.toObject=function(c,l){l||(l={});var p={};return c.name!=null&&c.hasOwnProperty("name")&&(p.name=c.name,l.oneofs&&(p._name="name")),c.buttonParamsJson!=null&&c.hasOwnProperty("buttonParamsJson")&&(p.buttonParamsJson=c.buttonParamsJson,l.oneofs&&(p._buttonParamsJson="buttonParamsJson")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton"},t})(),a})(),i.ShopMessage=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.id=s.string();break}case 2:{p.surface=s.int32();break}case 3:{p.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveMessage.ShopMessage)return s;var g=new E.proto.Message.InteractiveMessage.ShopMessage;switch(s.id!=null&&(g.id=String(s.id)),s.surface){default:if(typeof s.surface=="number"){g.surface=s.surface;break}break;case"UNKNOWN_SURFACE":case 0:g.surface=0;break;case"FB":case 1:g.surface=1;break;case"IG":case 2:g.surface=2;break;case"WA":case 3:g.surface=3;break}return s.messageVersion!=null&&(g.messageVersion=s.messageVersion|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.id!=null&&s.hasOwnProperty("id")&&(c.id=s.id,g.oneofs&&(c._id="id")),s.surface!=null&&s.hasOwnProperty("surface")&&(c.surface=g.enums===String?E.proto.Message.InteractiveMessage.ShopMessage.Surface[s.surface]===void 0?s.surface:E.proto.Message.InteractiveMessage.ShopMessage.Surface[s.surface]:s.surface,g.oneofs&&(c._surface="surface")),s.messageVersion!=null&&s.hasOwnProperty("messageVersion")&&(c.messageVersion=s.messageVersion,g.oneofs&&(c._messageVersion="messageVersion")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.ShopMessage"},a.Surface=(function(){let t={},s=Object.create(t);return s[t[0]="UNKNOWN_SURFACE"]=0,s[t[1]="FB"]=1,s[t[2]="IG"]=2,s[t[3]="WA"]=3,s})(),a})(),i})(),r.InteractiveResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.body=E.proto.Message.InteractiveResponseMessage.Body.decode(A,A.uint32());break}case 15:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.nativeFlowResponseMessage=E.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.InteractiveResponseMessage)return A;var t=new E.proto.Message.InteractiveResponseMessage;if(A.body!=null){if(typeof A.body!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.body: object expected");t.body=E.proto.Message.InteractiveResponseMessage.Body.fromObject(A.body)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.nativeFlowResponseMessage!=null){if(typeof A.nativeFlowResponseMessage!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.nativeFlowResponseMessage: object expected");t.nativeFlowResponseMessage=E.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.fromObject(A.nativeFlowResponseMessage)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.body!=null&&A.hasOwnProperty("body")&&(s.body=E.proto.Message.InteractiveResponseMessage.Body.toObject(A.body,t),t.oneofs&&(s._body="body")),A.nativeFlowResponseMessage!=null&&A.hasOwnProperty("nativeFlowResponseMessage")&&(s.nativeFlowResponseMessage=E.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.toObject(A.nativeFlowResponseMessage,t),t.oneofs&&(s.interactiveResponseMessage="nativeFlowResponseMessage")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InteractiveResponseMessage"},i.Body=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.text=s.string();break}case 2:{p.format=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveResponseMessage.Body)return s;var g=new E.proto.Message.InteractiveResponseMessage.Body;switch(s.text!=null&&(g.text=String(s.text)),s.format){default:if(typeof s.format=="number"){g.format=s.format;break}break;case"DEFAULT":case 0:g.format=0;break;case"EXTENSIONS_1":case 1:g.format=1;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),s.format!=null&&s.hasOwnProperty("format")&&(c.format=g.enums===String?E.proto.Message.InteractiveResponseMessage.Body.Format[s.format]===void 0?s.format:E.proto.Message.InteractiveResponseMessage.Body.Format[s.format]:s.format,g.oneofs&&(c._format="format")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveResponseMessage.Body"},a.Format=(function(){let t={},s=Object.create(t);return s[t[0]="DEFAULT"]=0,s[t[1]="EXTENSIONS_1"]=1,s})(),a})(),i.NativeFlowResponseMessage=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.name=s.string();break}case 2:{p.paramsJson=s.string();break}case 3:{p.version=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage)return s;var g=new E.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage;return s.name!=null&&(g.name=String(s.name)),s.paramsJson!=null&&(g.paramsJson=String(s.paramsJson)),s.version!=null&&(g.version=s.version|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.name!=null&&s.hasOwnProperty("name")&&(c.name=s.name,g.oneofs&&(c._name="name")),s.paramsJson!=null&&s.hasOwnProperty("paramsJson")&&(c.paramsJson=s.paramsJson,g.oneofs&&(c._paramsJson="paramsJson")),s.version!=null&&s.hasOwnProperty("version")&&(c.version=s.version,g.oneofs&&(c._version="version")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage"},a})(),i})(),r.InvoiceMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.note=A.string();break}case 2:{c.token=A.string();break}case 3:{c.attachmentType=A.int32();break}case 4:{c.attachmentMimetype=A.string();break}case 5:{c.attachmentMediaKey=A.bytes();break}case 6:{c.attachmentMediaKeyTimestamp=A.int64();break}case 7:{c.attachmentFileSha256=A.bytes();break}case 8:{c.attachmentFileEncSha256=A.bytes();break}case 9:{c.attachmentDirectPath=A.string();break}case 10:{c.attachmentJpegThumbnail=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.InvoiceMessage)return A;var t=new E.proto.Message.InvoiceMessage;switch(A.note!=null&&(t.note=String(A.note)),A.token!=null&&(t.token=String(A.token)),A.attachmentType){default:if(typeof A.attachmentType=="number"){t.attachmentType=A.attachmentType;break}break;case"IMAGE":case 0:t.attachmentType=0;break;case"PDF":case 1:t.attachmentType=1;break}return A.attachmentMimetype!=null&&(t.attachmentMimetype=String(A.attachmentMimetype)),A.attachmentMediaKey!=null&&(typeof A.attachmentMediaKey=="string"?I.base64.decode(A.attachmentMediaKey,t.attachmentMediaKey=I.newBuffer(I.base64.length(A.attachmentMediaKey)),0):A.attachmentMediaKey.length>=0&&(t.attachmentMediaKey=A.attachmentMediaKey)),A.attachmentMediaKeyTimestamp!=null&&(I.Long?(t.attachmentMediaKeyTimestamp=I.Long.fromValue(A.attachmentMediaKeyTimestamp)).unsigned=!1:typeof A.attachmentMediaKeyTimestamp=="string"?t.attachmentMediaKeyTimestamp=parseInt(A.attachmentMediaKeyTimestamp,10):typeof A.attachmentMediaKeyTimestamp=="number"?t.attachmentMediaKeyTimestamp=A.attachmentMediaKeyTimestamp:typeof A.attachmentMediaKeyTimestamp=="object"&&(t.attachmentMediaKeyTimestamp=new I.LongBits(A.attachmentMediaKeyTimestamp.low>>>0,A.attachmentMediaKeyTimestamp.high>>>0).toNumber())),A.attachmentFileSha256!=null&&(typeof A.attachmentFileSha256=="string"?I.base64.decode(A.attachmentFileSha256,t.attachmentFileSha256=I.newBuffer(I.base64.length(A.attachmentFileSha256)),0):A.attachmentFileSha256.length>=0&&(t.attachmentFileSha256=A.attachmentFileSha256)),A.attachmentFileEncSha256!=null&&(typeof A.attachmentFileEncSha256=="string"?I.base64.decode(A.attachmentFileEncSha256,t.attachmentFileEncSha256=I.newBuffer(I.base64.length(A.attachmentFileEncSha256)),0):A.attachmentFileEncSha256.length>=0&&(t.attachmentFileEncSha256=A.attachmentFileEncSha256)),A.attachmentDirectPath!=null&&(t.attachmentDirectPath=String(A.attachmentDirectPath)),A.attachmentJpegThumbnail!=null&&(typeof A.attachmentJpegThumbnail=="string"?I.base64.decode(A.attachmentJpegThumbnail,t.attachmentJpegThumbnail=I.newBuffer(I.base64.length(A.attachmentJpegThumbnail)),0):A.attachmentJpegThumbnail.length>=0&&(t.attachmentJpegThumbnail=A.attachmentJpegThumbnail)),t},i.toObject=function(A,t){t||(t={});var s={};return A.note!=null&&A.hasOwnProperty("note")&&(s.note=A.note,t.oneofs&&(s._note="note")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=A.token,t.oneofs&&(s._token="token")),A.attachmentType!=null&&A.hasOwnProperty("attachmentType")&&(s.attachmentType=t.enums===String?E.proto.Message.InvoiceMessage.AttachmentType[A.attachmentType]===void 0?A.attachmentType:E.proto.Message.InvoiceMessage.AttachmentType[A.attachmentType]:A.attachmentType,t.oneofs&&(s._attachmentType="attachmentType")),A.attachmentMimetype!=null&&A.hasOwnProperty("attachmentMimetype")&&(s.attachmentMimetype=A.attachmentMimetype,t.oneofs&&(s._attachmentMimetype="attachmentMimetype")),A.attachmentMediaKey!=null&&A.hasOwnProperty("attachmentMediaKey")&&(s.attachmentMediaKey=t.bytes===String?I.base64.encode(A.attachmentMediaKey,0,A.attachmentMediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.attachmentMediaKey):A.attachmentMediaKey,t.oneofs&&(s._attachmentMediaKey="attachmentMediaKey")),A.attachmentMediaKeyTimestamp!=null&&A.hasOwnProperty("attachmentMediaKeyTimestamp")&&(typeof A.attachmentMediaKeyTimestamp=="number"?s.attachmentMediaKeyTimestamp=t.longs===String?String(A.attachmentMediaKeyTimestamp):A.attachmentMediaKeyTimestamp:s.attachmentMediaKeyTimestamp=t.longs===String?re(A.attachmentMediaKeyTimestamp):t.longs===Number?ae(A.attachmentMediaKeyTimestamp):A.attachmentMediaKeyTimestamp,t.oneofs&&(s._attachmentMediaKeyTimestamp="attachmentMediaKeyTimestamp")),A.attachmentFileSha256!=null&&A.hasOwnProperty("attachmentFileSha256")&&(s.attachmentFileSha256=t.bytes===String?I.base64.encode(A.attachmentFileSha256,0,A.attachmentFileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.attachmentFileSha256):A.attachmentFileSha256,t.oneofs&&(s._attachmentFileSha256="attachmentFileSha256")),A.attachmentFileEncSha256!=null&&A.hasOwnProperty("attachmentFileEncSha256")&&(s.attachmentFileEncSha256=t.bytes===String?I.base64.encode(A.attachmentFileEncSha256,0,A.attachmentFileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.attachmentFileEncSha256):A.attachmentFileEncSha256,t.oneofs&&(s._attachmentFileEncSha256="attachmentFileEncSha256")),A.attachmentDirectPath!=null&&A.hasOwnProperty("attachmentDirectPath")&&(s.attachmentDirectPath=A.attachmentDirectPath,t.oneofs&&(s._attachmentDirectPath="attachmentDirectPath")),A.attachmentJpegThumbnail!=null&&A.hasOwnProperty("attachmentJpegThumbnail")&&(s.attachmentJpegThumbnail=t.bytes===String?I.base64.encode(A.attachmentJpegThumbnail,0,A.attachmentJpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.attachmentJpegThumbnail):A.attachmentJpegThumbnail,t.oneofs&&(s._attachmentJpegThumbnail="attachmentJpegThumbnail")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InvoiceMessage"},i.AttachmentType=(function(){let a={},A=Object.create(a);return A[a[0]="IMAGE"]=0,A[a[1]="PDF"]=1,A})(),i})(),r.KeepInChatMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.keepType=A.int32();break}case 3:{c.timestampMs=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.KeepInChatMessage)return A;var t=new E.proto.Message.KeepInChatMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.KeepInChatMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}switch(A.keepType){default:if(typeof A.keepType=="number"){t.keepType=A.keepType;break}break;case"UNKNOWN":case 0:t.keepType=0;break;case"KEEP_FOR_ALL":case 1:t.keepType=1;break;case"UNDO_KEEP_FOR_ALL":case 2:t.keepType=2;break}return A.timestampMs!=null&&(I.Long?(t.timestampMs=I.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?t.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?t.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(t.timestampMs=new I.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.keepType!=null&&A.hasOwnProperty("keepType")&&(s.keepType=t.enums===String?E.proto.KeepType[A.keepType]===void 0?A.keepType:E.proto.KeepType[A.keepType]:A.keepType,t.oneofs&&(s._keepType="keepType")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=t.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=t.longs===String?re(A.timestampMs):t.longs===Number?ae(A.timestampMs):A.timestampMs,t.oneofs&&(s._timestampMs="timestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.KeepInChatMessage"},i})(),r.LinkPreviewMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.paymentLinkMetadata=E.proto.Message.PaymentLinkMetadata.decode(A,A.uint32());break}case 2:{c.urlMetadata=E.proto.Message.URLMetadata.decode(A,A.uint32());break}case 3:{c.fbExperimentId=A.uint32();break}case 4:{c.linkMediaDuration=A.uint32();break}case 5:{c.socialMediaPostType=A.int32();break}case 6:{c.linkInlineVideoMuted=A.bool();break}case 7:{c.videoContentUrl=A.string();break}case 8:{c.musicMetadata=E.proto.EmbeddedMusic.decode(A,A.uint32());break}case 9:{c.videoContentCaption=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.LinkPreviewMetadata)return A;var t=new E.proto.Message.LinkPreviewMetadata;if(A.paymentLinkMetadata!=null){if(typeof A.paymentLinkMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.paymentLinkMetadata: object expected");t.paymentLinkMetadata=E.proto.Message.PaymentLinkMetadata.fromObject(A.paymentLinkMetadata)}if(A.urlMetadata!=null){if(typeof A.urlMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.urlMetadata: object expected");t.urlMetadata=E.proto.Message.URLMetadata.fromObject(A.urlMetadata)}switch(A.fbExperimentId!=null&&(t.fbExperimentId=A.fbExperimentId>>>0),A.linkMediaDuration!=null&&(t.linkMediaDuration=A.linkMediaDuration>>>0),A.socialMediaPostType){default:if(typeof A.socialMediaPostType=="number"){t.socialMediaPostType=A.socialMediaPostType;break}break;case"NONE":case 0:t.socialMediaPostType=0;break;case"REEL":case 1:t.socialMediaPostType=1;break;case"LIVE_VIDEO":case 2:t.socialMediaPostType=2;break;case"LONG_VIDEO":case 3:t.socialMediaPostType=3;break;case"SINGLE_IMAGE":case 4:t.socialMediaPostType=4;break;case"CAROUSEL":case 5:t.socialMediaPostType=5;break}if(A.linkInlineVideoMuted!=null&&(t.linkInlineVideoMuted=!!A.linkInlineVideoMuted),A.videoContentUrl!=null&&(t.videoContentUrl=String(A.videoContentUrl)),A.musicMetadata!=null){if(typeof A.musicMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.musicMetadata: object expected");t.musicMetadata=E.proto.EmbeddedMusic.fromObject(A.musicMetadata)}return A.videoContentCaption!=null&&(t.videoContentCaption=String(A.videoContentCaption)),t},i.toObject=function(A,t){t||(t={});var s={};return A.paymentLinkMetadata!=null&&A.hasOwnProperty("paymentLinkMetadata")&&(s.paymentLinkMetadata=E.proto.Message.PaymentLinkMetadata.toObject(A.paymentLinkMetadata,t),t.oneofs&&(s._paymentLinkMetadata="paymentLinkMetadata")),A.urlMetadata!=null&&A.hasOwnProperty("urlMetadata")&&(s.urlMetadata=E.proto.Message.URLMetadata.toObject(A.urlMetadata,t),t.oneofs&&(s._urlMetadata="urlMetadata")),A.fbExperimentId!=null&&A.hasOwnProperty("fbExperimentId")&&(s.fbExperimentId=A.fbExperimentId,t.oneofs&&(s._fbExperimentId="fbExperimentId")),A.linkMediaDuration!=null&&A.hasOwnProperty("linkMediaDuration")&&(s.linkMediaDuration=A.linkMediaDuration,t.oneofs&&(s._linkMediaDuration="linkMediaDuration")),A.socialMediaPostType!=null&&A.hasOwnProperty("socialMediaPostType")&&(s.socialMediaPostType=t.enums===String?E.proto.Message.LinkPreviewMetadata.SocialMediaPostType[A.socialMediaPostType]===void 0?A.socialMediaPostType:E.proto.Message.LinkPreviewMetadata.SocialMediaPostType[A.socialMediaPostType]:A.socialMediaPostType,t.oneofs&&(s._socialMediaPostType="socialMediaPostType")),A.linkInlineVideoMuted!=null&&A.hasOwnProperty("linkInlineVideoMuted")&&(s.linkInlineVideoMuted=A.linkInlineVideoMuted,t.oneofs&&(s._linkInlineVideoMuted="linkInlineVideoMuted")),A.videoContentUrl!=null&&A.hasOwnProperty("videoContentUrl")&&(s.videoContentUrl=A.videoContentUrl,t.oneofs&&(s._videoContentUrl="videoContentUrl")),A.musicMetadata!=null&&A.hasOwnProperty("musicMetadata")&&(s.musicMetadata=E.proto.EmbeddedMusic.toObject(A.musicMetadata,t),t.oneofs&&(s._musicMetadata="musicMetadata")),A.videoContentCaption!=null&&A.hasOwnProperty("videoContentCaption")&&(s.videoContentCaption=A.videoContentCaption,t.oneofs&&(s._videoContentCaption="videoContentCaption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LinkPreviewMetadata"},i.SocialMediaPostType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="REEL"]=1,A[a[2]="LIVE_VIDEO"]=2,A[a[3]="LONG_VIDEO"]=3,A[a[4]="SINGLE_IMAGE"]=4,A[a[5]="CAROUSEL"]=5,A})(),i})(),r.ListMessage=(function(){function i(a){if(this.sections=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.title=A.string();break}case 2:{c.description=A.string();break}case 3:{c.buttonText=A.string();break}case 4:{c.listType=A.int32();break}case 5:{c.sections&&c.sections.length||(c.sections=[]),c.sections.push(E.proto.Message.ListMessage.Section.decode(A,A.uint32()));break}case 6:{c.productListInfo=E.proto.Message.ListMessage.ProductListInfo.decode(A,A.uint32());break}case 7:{c.footerText=A.string();break}case 8:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ListMessage)return A;var t=new E.proto.Message.ListMessage;switch(A.title!=null&&(t.title=String(A.title)),A.description!=null&&(t.description=String(A.description)),A.buttonText!=null&&(t.buttonText=String(A.buttonText)),A.listType){default:if(typeof A.listType=="number"){t.listType=A.listType;break}break;case"UNKNOWN":case 0:t.listType=0;break;case"SINGLE_SELECT":case 1:t.listType=1;break;case"PRODUCT_LIST":case 2:t.listType=2;break}if(A.sections){if(!Array.isArray(A.sections))throw TypeError(".proto.Message.ListMessage.sections: array expected");t.sections=[];for(var s=0;s>>3){case 1:{p.productId=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ListMessage.Product)return s;var g=new E.proto.Message.ListMessage.Product;return s.productId!=null&&(g.productId=String(s.productId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.Product"},a})(),i.ProductListHeaderImage=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.productId=s.string();break}case 2:{p.jpegThumbnail=s.bytes();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ListMessage.ProductListHeaderImage)return s;var g=new E.proto.Message.ListMessage.ProductListHeaderImage;return s.productId!=null&&(g.productId=String(s.productId)),s.jpegThumbnail!=null&&(typeof s.jpegThumbnail=="string"?I.base64.decode(s.jpegThumbnail,g.jpegThumbnail=I.newBuffer(I.base64.length(s.jpegThumbnail)),0):s.jpegThumbnail.length>=0&&(g.jpegThumbnail=s.jpegThumbnail)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),s.jpegThumbnail!=null&&s.hasOwnProperty("jpegThumbnail")&&(c.jpegThumbnail=g.bytes===String?I.base64.encode(s.jpegThumbnail,0,s.jpegThumbnail.length):g.bytes===Array?Array.prototype.slice.call(s.jpegThumbnail):s.jpegThumbnail,g.oneofs&&(c._jpegThumbnail="jpegThumbnail")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.ProductListHeaderImage"},a})(),i.ProductListInfo=(function(){function a(t){if(this.productSections=[],t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.productSections&&p.productSections.length||(p.productSections=[]),p.productSections.push(E.proto.Message.ListMessage.ProductSection.decode(s,s.uint32()));break}case 2:{p.headerImage=E.proto.Message.ListMessage.ProductListHeaderImage.decode(s,s.uint32());break}case 3:{p.businessOwnerJid=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ListMessage.ProductListInfo)return s;var g=new E.proto.Message.ListMessage.ProductListInfo;if(s.productSections){if(!Array.isArray(s.productSections))throw TypeError(".proto.Message.ListMessage.ProductListInfo.productSections: array expected");g.productSections=[];for(var c=0;c>>3){case 1:{p.title=s.string();break}case 2:{p.products&&p.products.length||(p.products=[]),p.products.push(E.proto.Message.ListMessage.Product.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ListMessage.ProductSection)return s;var g=new E.proto.Message.ListMessage.ProductSection;if(s.title!=null&&(g.title=String(s.title)),s.products){if(!Array.isArray(s.products))throw TypeError(".proto.Message.ListMessage.ProductSection.products: array expected");g.products=[];for(var c=0;c>>3){case 1:{p.title=s.string();break}case 2:{p.description=s.string();break}case 3:{p.rowId=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ListMessage.Row)return s;var g=new E.proto.Message.ListMessage.Row;return s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.rowId!=null&&(g.rowId=String(s.rowId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.rowId!=null&&s.hasOwnProperty("rowId")&&(c.rowId=s.rowId,g.oneofs&&(c._rowId="rowId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.Row"},a})(),i.Section=(function(){function a(t){if(this.rows=[],t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.title=s.string();break}case 2:{p.rows&&p.rows.length||(p.rows=[]),p.rows.push(E.proto.Message.ListMessage.Row.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ListMessage.Section)return s;var g=new E.proto.Message.ListMessage.Section;if(s.title!=null&&(g.title=String(s.title)),s.rows){if(!Array.isArray(s.rows))throw TypeError(".proto.Message.ListMessage.Section.rows: array expected");g.rows=[];for(var c=0;c>>3){case 1:{c.title=A.string();break}case 2:{c.listType=A.int32();break}case 3:{c.singleSelectReply=E.proto.Message.ListResponseMessage.SingleSelectReply.decode(A,A.uint32());break}case 4:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 5:{c.description=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ListResponseMessage)return A;var t=new E.proto.Message.ListResponseMessage;switch(A.title!=null&&(t.title=String(A.title)),A.listType){default:if(typeof A.listType=="number"){t.listType=A.listType;break}break;case"UNKNOWN":case 0:t.listType=0;break;case"SINGLE_SELECT":case 1:t.listType=1;break}if(A.singleSelectReply!=null){if(typeof A.singleSelectReply!="object")throw TypeError(".proto.Message.ListResponseMessage.singleSelectReply: object expected");t.singleSelectReply=E.proto.Message.ListResponseMessage.SingleSelectReply.fromObject(A.singleSelectReply)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ListResponseMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return A.description!=null&&(t.description=String(A.description)),t},i.toObject=function(A,t){t||(t={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),A.listType!=null&&A.hasOwnProperty("listType")&&(s.listType=t.enums===String?E.proto.Message.ListResponseMessage.ListType[A.listType]===void 0?A.listType:E.proto.Message.ListResponseMessage.ListType[A.listType]:A.listType,t.oneofs&&(s._listType="listType")),A.singleSelectReply!=null&&A.hasOwnProperty("singleSelectReply")&&(s.singleSelectReply=E.proto.Message.ListResponseMessage.SingleSelectReply.toObject(A.singleSelectReply,t),t.oneofs&&(s._singleSelectReply="singleSelectReply")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.description!=null&&A.hasOwnProperty("description")&&(s.description=A.description,t.oneofs&&(s._description="description")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ListResponseMessage"},i.ListType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="SINGLE_SELECT"]=1,A})(),i.SingleSelectReply=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.selectedRowId=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ListResponseMessage.SingleSelectReply)return s;var g=new E.proto.Message.ListResponseMessage.SingleSelectReply;return s.selectedRowId!=null&&(g.selectedRowId=String(s.selectedRowId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.selectedRowId!=null&&s.hasOwnProperty("selectedRowId")&&(c.selectedRowId=s.selectedRowId,g.oneofs&&(c._selectedRowId="selectedRowId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListResponseMessage.SingleSelectReply"},a})(),i})(),r.LiveLocationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.accuracyInMeters=A.uint32();break}case 4:{c.speedInMps=A.float();break}case 5:{c.degreesClockwiseFromMagneticNorth=A.uint32();break}case 6:{c.caption=A.string();break}case 7:{c.sequenceNumber=A.int64();break}case 8:{c.timeOffset=A.uint32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.LiveLocationMessage)return A;var t=new E.proto.Message.LiveLocationMessage;if(A.degreesLatitude!=null&&(t.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(t.degreesLongitude=Number(A.degreesLongitude)),A.accuracyInMeters!=null&&(t.accuracyInMeters=A.accuracyInMeters>>>0),A.speedInMps!=null&&(t.speedInMps=Number(A.speedInMps)),A.degreesClockwiseFromMagneticNorth!=null&&(t.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth>>>0),A.caption!=null&&(t.caption=String(A.caption)),A.sequenceNumber!=null&&(I.Long?(t.sequenceNumber=I.Long.fromValue(A.sequenceNumber)).unsigned=!1:typeof A.sequenceNumber=="string"?t.sequenceNumber=parseInt(A.sequenceNumber,10):typeof A.sequenceNumber=="number"?t.sequenceNumber=A.sequenceNumber:typeof A.sequenceNumber=="object"&&(t.sequenceNumber=new I.LongBits(A.sequenceNumber.low>>>0,A.sequenceNumber.high>>>0).toNumber())),A.timeOffset!=null&&(t.timeOffset=A.timeOffset>>>0),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.LiveLocationMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=t.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,t.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=t.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,t.oneofs&&(s._degreesLongitude="degreesLongitude")),A.accuracyInMeters!=null&&A.hasOwnProperty("accuracyInMeters")&&(s.accuracyInMeters=A.accuracyInMeters,t.oneofs&&(s._accuracyInMeters="accuracyInMeters")),A.speedInMps!=null&&A.hasOwnProperty("speedInMps")&&(s.speedInMps=t.json&&!isFinite(A.speedInMps)?String(A.speedInMps):A.speedInMps,t.oneofs&&(s._speedInMps="speedInMps")),A.degreesClockwiseFromMagneticNorth!=null&&A.hasOwnProperty("degreesClockwiseFromMagneticNorth")&&(s.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth,t.oneofs&&(s._degreesClockwiseFromMagneticNorth="degreesClockwiseFromMagneticNorth")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),A.sequenceNumber!=null&&A.hasOwnProperty("sequenceNumber")&&(typeof A.sequenceNumber=="number"?s.sequenceNumber=t.longs===String?String(A.sequenceNumber):A.sequenceNumber:s.sequenceNumber=t.longs===String?re(A.sequenceNumber):t.longs===Number?ae(A.sequenceNumber):A.sequenceNumber,t.oneofs&&(s._sequenceNumber="sequenceNumber")),A.timeOffset!=null&&A.hasOwnProperty("timeOffset")&&(s.timeOffset=A.timeOffset,t.oneofs&&(s._timeOffset="timeOffset")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LiveLocationMessage"},i})(),r.LocationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.name=A.string();break}case 4:{c.address=A.string();break}case 5:{c.url=A.string();break}case 6:{c.isLive=A.bool();break}case 7:{c.accuracyInMeters=A.uint32();break}case 8:{c.speedInMps=A.float();break}case 9:{c.degreesClockwiseFromMagneticNorth=A.uint32();break}case 11:{c.comment=A.string();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.LocationMessage)return A;var t=new E.proto.Message.LocationMessage;if(A.degreesLatitude!=null&&(t.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(t.degreesLongitude=Number(A.degreesLongitude)),A.name!=null&&(t.name=String(A.name)),A.address!=null&&(t.address=String(A.address)),A.url!=null&&(t.url=String(A.url)),A.isLive!=null&&(t.isLive=!!A.isLive),A.accuracyInMeters!=null&&(t.accuracyInMeters=A.accuracyInMeters>>>0),A.speedInMps!=null&&(t.speedInMps=Number(A.speedInMps)),A.degreesClockwiseFromMagneticNorth!=null&&(t.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth>>>0),A.comment!=null&&(t.comment=String(A.comment)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.LocationMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=t.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,t.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=t.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,t.oneofs&&(s._degreesLongitude="degreesLongitude")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.address!=null&&A.hasOwnProperty("address")&&(s.address=A.address,t.oneofs&&(s._address="address")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.isLive!=null&&A.hasOwnProperty("isLive")&&(s.isLive=A.isLive,t.oneofs&&(s._isLive="isLive")),A.accuracyInMeters!=null&&A.hasOwnProperty("accuracyInMeters")&&(s.accuracyInMeters=A.accuracyInMeters,t.oneofs&&(s._accuracyInMeters="accuracyInMeters")),A.speedInMps!=null&&A.hasOwnProperty("speedInMps")&&(s.speedInMps=t.json&&!isFinite(A.speedInMps)?String(A.speedInMps):A.speedInMps,t.oneofs&&(s._speedInMps="speedInMps")),A.degreesClockwiseFromMagneticNorth!=null&&A.hasOwnProperty("degreesClockwiseFromMagneticNorth")&&(s.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth,t.oneofs&&(s._degreesClockwiseFromMagneticNorth="degreesClockwiseFromMagneticNorth")),A.comment!=null&&A.hasOwnProperty("comment")&&(s.comment=A.comment,t.oneofs&&(s._comment="comment")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LocationMessage"},i})(),r.MMSThumbnailMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.thumbnailDirectPath=A.string();break}case 2:{c.thumbnailSha256=A.bytes();break}case 3:{c.thumbnailEncSha256=A.bytes();break}case 4:{c.mediaKey=A.bytes();break}case 5:{c.mediaKeyTimestamp=A.int64();break}case 6:{c.thumbnailHeight=A.uint32();break}case 7:{c.thumbnailWidth=A.uint32();break}case 8:{c.mediaKeyDomain=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.MMSThumbnailMetadata)return A;var t=new E.proto.Message.MMSThumbnailMetadata;switch(A.thumbnailDirectPath!=null&&(t.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?I.base64.decode(A.thumbnailSha256,t.thumbnailSha256=I.newBuffer(I.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(t.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?I.base64.decode(A.thumbnailEncSha256,t.thumbnailEncSha256=I.newBuffer(I.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(t.thumbnailEncSha256=A.thumbnailEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.thumbnailHeight!=null&&(t.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(t.thumbnailWidth=A.thumbnailWidth>>>0),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){t.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:t.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:t.mediaKeyDomain=1;break;case"STATUS":case 2:t.mediaKeyDomain=2;break;case"CAPI":case 3:t.mediaKeyDomain=3;break;case"BOT":case 4:t.mediaKeyDomain=4;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.thumbnailDirectPath!=null&&A.hasOwnProperty("thumbnailDirectPath")&&(s.thumbnailDirectPath=A.thumbnailDirectPath,t.oneofs&&(s._thumbnailDirectPath="thumbnailDirectPath")),A.thumbnailSha256!=null&&A.hasOwnProperty("thumbnailSha256")&&(s.thumbnailSha256=t.bytes===String?I.base64.encode(A.thumbnailSha256,0,A.thumbnailSha256.length):t.bytes===Array?Array.prototype.slice.call(A.thumbnailSha256):A.thumbnailSha256,t.oneofs&&(s._thumbnailSha256="thumbnailSha256")),A.thumbnailEncSha256!=null&&A.hasOwnProperty("thumbnailEncSha256")&&(s.thumbnailEncSha256=t.bytes===String?I.base64.encode(A.thumbnailEncSha256,0,A.thumbnailEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.thumbnailEncSha256):A.thumbnailEncSha256,t.oneofs&&(s._thumbnailEncSha256="thumbnailEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=t.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=t.longs===String?re(A.mediaKeyTimestamp):t.longs===Number?ae(A.mediaKeyTimestamp):A.mediaKeyTimestamp,t.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.thumbnailHeight!=null&&A.hasOwnProperty("thumbnailHeight")&&(s.thumbnailHeight=A.thumbnailHeight,t.oneofs&&(s._thumbnailHeight="thumbnailHeight")),A.thumbnailWidth!=null&&A.hasOwnProperty("thumbnailWidth")&&(s.thumbnailWidth=A.thumbnailWidth,t.oneofs&&(s._thumbnailWidth="thumbnailWidth")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=t.enums===String?E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,t.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MMSThumbnailMetadata"},i})(),r.MediaKeyDomain=(function(){let i={},e=Object.create(i);return e[i[0]="UNSET"]=0,e[i[1]="E2EE_CHAT"]=1,e[i[2]="STATUS"]=2,e[i[3]="CAPI"]=3,e[i[4]="BOT"]=4,e})(),r.MessageHistoryBundle=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.mimetype=A.string();break}case 2:{c.fileSha256=A.bytes();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}case 6:{c.mediaKeyTimestamp=A.int64();break}case 7:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.messageHistoryMetadata=E.proto.Message.MessageHistoryMetadata.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.MessageHistoryBundle)return A;var t=new E.proto.Message.MessageHistoryBundle;if(A.mimetype!=null&&(t.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(t.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.MessageHistoryBundle.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageHistoryMetadata!=null){if(typeof A.messageHistoryMetadata!="object")throw TypeError(".proto.Message.MessageHistoryBundle.messageHistoryMetadata: object expected");t.messageHistoryMetadata=E.proto.Message.MessageHistoryMetadata.fromObject(A.messageHistoryMetadata)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,t.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=t.bytes===String?I.base64.encode(A.fileSha256,0,A.fileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,t.oneofs&&(s._fileSha256="fileSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,t.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=t.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=t.longs===String?re(A.mediaKeyTimestamp):t.longs===Number?ae(A.mediaKeyTimestamp):A.mediaKeyTimestamp,t.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.messageHistoryMetadata!=null&&A.hasOwnProperty("messageHistoryMetadata")&&(s.messageHistoryMetadata=E.proto.Message.MessageHistoryMetadata.toObject(A.messageHistoryMetadata,t),t.oneofs&&(s._messageHistoryMetadata="messageHistoryMetadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MessageHistoryBundle"},i})(),r.MessageHistoryMetadata=(function(){function i(a){if(this.historyReceivers=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.historyReceivers&&c.historyReceivers.length||(c.historyReceivers=[]),c.historyReceivers.push(A.string());break}case 2:{c.oldestMessageTimestamp=A.int64();break}case 3:{c.messageCount=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.MessageHistoryMetadata)return A;var t=new E.proto.Message.MessageHistoryMetadata;if(A.historyReceivers){if(!Array.isArray(A.historyReceivers))throw TypeError(".proto.Message.MessageHistoryMetadata.historyReceivers: array expected");t.historyReceivers=[];for(var s=0;s>>0,A.oldestMessageTimestamp.high>>>0).toNumber())),A.messageCount!=null&&(I.Long?(t.messageCount=I.Long.fromValue(A.messageCount)).unsigned=!1:typeof A.messageCount=="string"?t.messageCount=parseInt(A.messageCount,10):typeof A.messageCount=="number"?t.messageCount=A.messageCount:typeof A.messageCount=="object"&&(t.messageCount=new I.LongBits(A.messageCount.low>>>0,A.messageCount.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.historyReceivers=[]),A.historyReceivers&&A.historyReceivers.length){s.historyReceivers=[];for(var g=0;g>>3){case 1:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.messageHistoryMetadata=E.proto.Message.MessageHistoryMetadata.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.MessageHistoryNotice)return A;var t=new E.proto.Message.MessageHistoryNotice;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.MessageHistoryNotice.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageHistoryMetadata!=null){if(typeof A.messageHistoryMetadata!="object")throw TypeError(".proto.Message.MessageHistoryNotice.messageHistoryMetadata: object expected");t.messageHistoryMetadata=E.proto.Message.MessageHistoryMetadata.fromObject(A.messageHistoryMetadata)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.messageHistoryMetadata!=null&&A.hasOwnProperty("messageHistoryMetadata")&&(s.messageHistoryMetadata=E.proto.Message.MessageHistoryMetadata.toObject(A.messageHistoryMetadata,t),t.oneofs&&(s._messageHistoryMetadata="messageHistoryMetadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MessageHistoryNotice"},i})(),r.NewsletterAdminInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.newsletterName=A.string();break}case 3:{c.jpegThumbnail=A.bytes();break}case 4:{c.caption=A.string();break}case 5:{c.inviteExpiration=A.int64();break}case 6:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.NewsletterAdminInviteMessage)return A;var t=new E.proto.Message.NewsletterAdminInviteMessage;if(A.newsletterJid!=null&&(t.newsletterJid=String(A.newsletterJid)),A.newsletterName!=null&&(t.newsletterName=String(A.newsletterName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(t.caption=String(A.caption)),A.inviteExpiration!=null&&(I.Long?(t.inviteExpiration=I.Long.fromValue(A.inviteExpiration)).unsigned=!1:typeof A.inviteExpiration=="string"?t.inviteExpiration=parseInt(A.inviteExpiration,10):typeof A.inviteExpiration=="number"?t.inviteExpiration=A.inviteExpiration:typeof A.inviteExpiration=="object"&&(t.inviteExpiration=new I.LongBits(A.inviteExpiration.low>>>0,A.inviteExpiration.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.NewsletterAdminInviteMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,t.oneofs&&(s._newsletterJid="newsletterJid")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,t.oneofs&&(s._newsletterName="newsletterName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),A.inviteExpiration!=null&&A.hasOwnProperty("inviteExpiration")&&(typeof A.inviteExpiration=="number"?s.inviteExpiration=t.longs===String?String(A.inviteExpiration):A.inviteExpiration:s.inviteExpiration=t.longs===String?re(A.inviteExpiration):t.longs===Number?ae(A.inviteExpiration):A.inviteExpiration,t.oneofs&&(s._inviteExpiration="inviteExpiration")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.NewsletterAdminInviteMessage"},i})(),r.NewsletterFollowerInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.newsletterName=A.string();break}case 3:{c.jpegThumbnail=A.bytes();break}case 4:{c.caption=A.string();break}case 5:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.NewsletterFollowerInviteMessage)return A;var t=new E.proto.Message.NewsletterFollowerInviteMessage;if(A.newsletterJid!=null&&(t.newsletterJid=String(A.newsletterJid)),A.newsletterName!=null&&(t.newsletterName=String(A.newsletterName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(t.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.NewsletterFollowerInviteMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,t.oneofs&&(s._newsletterJid="newsletterJid")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,t.oneofs&&(s._newsletterName="newsletterName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.NewsletterFollowerInviteMessage"},i})(),r.OrderMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.orderId=A.string();break}case 2:{c.thumbnail=A.bytes();break}case 3:{c.itemCount=A.int32();break}case 4:{c.status=A.int32();break}case 5:{c.surface=A.int32();break}case 6:{c.message=A.string();break}case 7:{c.orderTitle=A.string();break}case 8:{c.sellerJid=A.string();break}case 9:{c.token=A.string();break}case 10:{c.totalAmount1000=A.int64();break}case 11:{c.totalCurrencyCode=A.string();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 12:{c.messageVersion=A.int32();break}case 13:{c.orderRequestMessageId=E.proto.MessageKey.decode(A,A.uint32());break}case 15:{c.catalogType=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.OrderMessage)return A;var t=new E.proto.Message.OrderMessage;switch(A.orderId!=null&&(t.orderId=String(A.orderId)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?I.base64.decode(A.thumbnail,t.thumbnail=I.newBuffer(I.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(t.thumbnail=A.thumbnail)),A.itemCount!=null&&(t.itemCount=A.itemCount|0),A.status){default:if(typeof A.status=="number"){t.status=A.status;break}break;case"INQUIRY":case 1:t.status=1;break;case"ACCEPTED":case 2:t.status=2;break;case"DECLINED":case 3:t.status=3;break}switch(A.surface){default:if(typeof A.surface=="number"){t.surface=A.surface;break}break;case"CATALOG":case 1:t.surface=1;break}if(A.message!=null&&(t.message=String(A.message)),A.orderTitle!=null&&(t.orderTitle=String(A.orderTitle)),A.sellerJid!=null&&(t.sellerJid=String(A.sellerJid)),A.token!=null&&(t.token=String(A.token)),A.totalAmount1000!=null&&(I.Long?(t.totalAmount1000=I.Long.fromValue(A.totalAmount1000)).unsigned=!1:typeof A.totalAmount1000=="string"?t.totalAmount1000=parseInt(A.totalAmount1000,10):typeof A.totalAmount1000=="number"?t.totalAmount1000=A.totalAmount1000:typeof A.totalAmount1000=="object"&&(t.totalAmount1000=new I.LongBits(A.totalAmount1000.low>>>0,A.totalAmount1000.high>>>0).toNumber())),A.totalCurrencyCode!=null&&(t.totalCurrencyCode=String(A.totalCurrencyCode)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.OrderMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageVersion!=null&&(t.messageVersion=A.messageVersion|0),A.orderRequestMessageId!=null){if(typeof A.orderRequestMessageId!="object")throw TypeError(".proto.Message.OrderMessage.orderRequestMessageId: object expected");t.orderRequestMessageId=E.proto.MessageKey.fromObject(A.orderRequestMessageId)}return A.catalogType!=null&&(t.catalogType=String(A.catalogType)),t},i.toObject=function(A,t){t||(t={});var s={};return A.orderId!=null&&A.hasOwnProperty("orderId")&&(s.orderId=A.orderId,t.oneofs&&(s._orderId="orderId")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=t.bytes===String?I.base64.encode(A.thumbnail,0,A.thumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,t.oneofs&&(s._thumbnail="thumbnail")),A.itemCount!=null&&A.hasOwnProperty("itemCount")&&(s.itemCount=A.itemCount,t.oneofs&&(s._itemCount="itemCount")),A.status!=null&&A.hasOwnProperty("status")&&(s.status=t.enums===String?E.proto.Message.OrderMessage.OrderStatus[A.status]===void 0?A.status:E.proto.Message.OrderMessage.OrderStatus[A.status]:A.status,t.oneofs&&(s._status="status")),A.surface!=null&&A.hasOwnProperty("surface")&&(s.surface=t.enums===String?E.proto.Message.OrderMessage.OrderSurface[A.surface]===void 0?A.surface:E.proto.Message.OrderMessage.OrderSurface[A.surface]:A.surface,t.oneofs&&(s._surface="surface")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=A.message,t.oneofs&&(s._message="message")),A.orderTitle!=null&&A.hasOwnProperty("orderTitle")&&(s.orderTitle=A.orderTitle,t.oneofs&&(s._orderTitle="orderTitle")),A.sellerJid!=null&&A.hasOwnProperty("sellerJid")&&(s.sellerJid=A.sellerJid,t.oneofs&&(s._sellerJid="sellerJid")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=A.token,t.oneofs&&(s._token="token")),A.totalAmount1000!=null&&A.hasOwnProperty("totalAmount1000")&&(typeof A.totalAmount1000=="number"?s.totalAmount1000=t.longs===String?String(A.totalAmount1000):A.totalAmount1000:s.totalAmount1000=t.longs===String?re(A.totalAmount1000):t.longs===Number?ae(A.totalAmount1000):A.totalAmount1000,t.oneofs&&(s._totalAmount1000="totalAmount1000")),A.totalCurrencyCode!=null&&A.hasOwnProperty("totalCurrencyCode")&&(s.totalCurrencyCode=A.totalCurrencyCode,t.oneofs&&(s._totalCurrencyCode="totalCurrencyCode")),A.messageVersion!=null&&A.hasOwnProperty("messageVersion")&&(s.messageVersion=A.messageVersion,t.oneofs&&(s._messageVersion="messageVersion")),A.orderRequestMessageId!=null&&A.hasOwnProperty("orderRequestMessageId")&&(s.orderRequestMessageId=E.proto.MessageKey.toObject(A.orderRequestMessageId,t),t.oneofs&&(s._orderRequestMessageId="orderRequestMessageId")),A.catalogType!=null&&A.hasOwnProperty("catalogType")&&(s.catalogType=A.catalogType,t.oneofs&&(s._catalogType="catalogType")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.OrderMessage"},i.OrderStatus=(function(){let a={},A=Object.create(a);return A[a[1]="INQUIRY"]=1,A[a[2]="ACCEPTED"]=2,A[a[3]="DECLINED"]=3,A})(),i.OrderSurface=(function(){let a={},A=Object.create(a);return A[a[1]="CATALOG"]=1,A})(),i})(),r.PaymentExtendedMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.type=A.uint32();break}case 2:{c.platform=A.string();break}case 3:{c.messageParamsJson=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PaymentExtendedMetadata)return A;var t=new E.proto.Message.PaymentExtendedMetadata;return A.type!=null&&(t.type=A.type>>>0),A.platform!=null&&(t.platform=String(A.platform)),A.messageParamsJson!=null&&(t.messageParamsJson=String(A.messageParamsJson)),t},i.toObject=function(A,t){t||(t={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=A.type,t.oneofs&&(s._type="type")),A.platform!=null&&A.hasOwnProperty("platform")&&(s.platform=A.platform,t.oneofs&&(s._platform="platform")),A.messageParamsJson!=null&&A.hasOwnProperty("messageParamsJson")&&(s.messageParamsJson=A.messageParamsJson,t.oneofs&&(s._messageParamsJson="messageParamsJson")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentExtendedMetadata"},i})(),r.PaymentInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.serviceType=A.int32();break}case 2:{c.expiryTimestamp=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PaymentInviteMessage)return A;var t=new E.proto.Message.PaymentInviteMessage;switch(A.serviceType){default:if(typeof A.serviceType=="number"){t.serviceType=A.serviceType;break}break;case"UNKNOWN":case 0:t.serviceType=0;break;case"FBPAY":case 1:t.serviceType=1;break;case"NOVI":case 2:t.serviceType=2;break;case"UPI":case 3:t.serviceType=3;break}return A.expiryTimestamp!=null&&(I.Long?(t.expiryTimestamp=I.Long.fromValue(A.expiryTimestamp)).unsigned=!1:typeof A.expiryTimestamp=="string"?t.expiryTimestamp=parseInt(A.expiryTimestamp,10):typeof A.expiryTimestamp=="number"?t.expiryTimestamp=A.expiryTimestamp:typeof A.expiryTimestamp=="object"&&(t.expiryTimestamp=new I.LongBits(A.expiryTimestamp.low>>>0,A.expiryTimestamp.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.serviceType!=null&&A.hasOwnProperty("serviceType")&&(s.serviceType=t.enums===String?E.proto.Message.PaymentInviteMessage.ServiceType[A.serviceType]===void 0?A.serviceType:E.proto.Message.PaymentInviteMessage.ServiceType[A.serviceType]:A.serviceType,t.oneofs&&(s._serviceType="serviceType")),A.expiryTimestamp!=null&&A.hasOwnProperty("expiryTimestamp")&&(typeof A.expiryTimestamp=="number"?s.expiryTimestamp=t.longs===String?String(A.expiryTimestamp):A.expiryTimestamp:s.expiryTimestamp=t.longs===String?re(A.expiryTimestamp):t.longs===Number?ae(A.expiryTimestamp):A.expiryTimestamp,t.oneofs&&(s._expiryTimestamp="expiryTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentInviteMessage"},i.ServiceType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="FBPAY"]=1,A[a[2]="NOVI"]=2,A[a[3]="UPI"]=3,A})(),i})(),r.PaymentLinkMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.button=E.proto.Message.PaymentLinkMetadata.PaymentLinkButton.decode(A,A.uint32());break}case 2:{c.header=E.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.decode(A,A.uint32());break}case 3:{c.provider=E.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PaymentLinkMetadata)return A;var t=new E.proto.Message.PaymentLinkMetadata;if(A.button!=null){if(typeof A.button!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.button: object expected");t.button=E.proto.Message.PaymentLinkMetadata.PaymentLinkButton.fromObject(A.button)}if(A.header!=null){if(typeof A.header!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.header: object expected");t.header=E.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.fromObject(A.header)}if(A.provider!=null){if(typeof A.provider!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.provider: object expected");t.provider=E.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.fromObject(A.provider)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.button!=null&&A.hasOwnProperty("button")&&(s.button=E.proto.Message.PaymentLinkMetadata.PaymentLinkButton.toObject(A.button,t),t.oneofs&&(s._button="button")),A.header!=null&&A.hasOwnProperty("header")&&(s.header=E.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.toObject(A.header,t),t.oneofs&&(s._header="header")),A.provider!=null&&A.hasOwnProperty("provider")&&(s.provider=E.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.toObject(A.provider,t),t.oneofs&&(s._provider="provider")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentLinkMetadata"},i.PaymentLinkButton=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.displayText=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PaymentLinkMetadata.PaymentLinkButton)return s;var g=new E.proto.Message.PaymentLinkMetadata.PaymentLinkButton;return s.displayText!=null&&(g.displayText=String(s.displayText)),g},a.toObject=function(s,g){g||(g={});var c={};return s.displayText!=null&&s.hasOwnProperty("displayText")&&(c.displayText=s.displayText,g.oneofs&&(c._displayText="displayText")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkButton"},a})(),i.PaymentLinkHeader=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.headerType=s.int32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PaymentLinkMetadata.PaymentLinkHeader)return s;var g=new E.proto.Message.PaymentLinkMetadata.PaymentLinkHeader;switch(s.headerType){default:if(typeof s.headerType=="number"){g.headerType=s.headerType;break}break;case"LINK_PREVIEW":case 0:g.headerType=0;break;case"ORDER":case 1:g.headerType=1;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.headerType!=null&&s.hasOwnProperty("headerType")&&(c.headerType=g.enums===String?E.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.PaymentLinkHeaderType[s.headerType]===void 0?s.headerType:E.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.PaymentLinkHeaderType[s.headerType]:s.headerType,g.oneofs&&(c._headerType="headerType")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkHeader"},a.PaymentLinkHeaderType=(function(){let t={},s=Object.create(t);return s[t[0]="LINK_PREVIEW"]=0,s[t[1]="ORDER"]=1,s})(),a})(),i.PaymentLinkProvider=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.paramsJson=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PaymentLinkMetadata.PaymentLinkProvider)return s;var g=new E.proto.Message.PaymentLinkMetadata.PaymentLinkProvider;return s.paramsJson!=null&&(g.paramsJson=String(s.paramsJson)),g},a.toObject=function(s,g){g||(g={});var c={};return s.paramsJson!=null&&s.hasOwnProperty("paramsJson")&&(c.paramsJson=s.paramsJson,g.oneofs&&(c._paramsJson="paramsJson")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkProvider"},a})(),i})(),r.PeerDataOperationRequestMessage=(function(){function i(a){if(this.requestStickerReupload=[],this.requestUrlPreview=[],this.placeholderMessageResendRequest=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.peerDataOperationRequestType=A.int32();break}case 2:{c.requestStickerReupload&&c.requestStickerReupload.length||(c.requestStickerReupload=[]),c.requestStickerReupload.push(E.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload.decode(A,A.uint32()));break}case 3:{c.requestUrlPreview&&c.requestUrlPreview.length||(c.requestUrlPreview=[]),c.requestUrlPreview.push(E.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview.decode(A,A.uint32()));break}case 4:{c.historySyncOnDemandRequest=E.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest.decode(A,A.uint32());break}case 5:{c.placeholderMessageResendRequest&&c.placeholderMessageResendRequest.length||(c.placeholderMessageResendRequest=[]),c.placeholderMessageResendRequest.push(E.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest.decode(A,A.uint32()));break}case 6:{c.fullHistorySyncOnDemandRequest=E.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.decode(A,A.uint32());break}case 7:{c.syncdCollectionFatalRecoveryRequest=E.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest.decode(A,A.uint32());break}case 8:{c.historySyncChunkRetryRequest=E.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest.decode(A,A.uint32());break}case 9:{c.galaxyFlowAction=E.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PeerDataOperationRequestMessage)return A;var t=new E.proto.Message.PeerDataOperationRequestMessage;switch(A.peerDataOperationRequestType){default:if(typeof A.peerDataOperationRequestType=="number"){t.peerDataOperationRequestType=A.peerDataOperationRequestType;break}break;case"UPLOAD_STICKER":case 0:t.peerDataOperationRequestType=0;break;case"SEND_RECENT_STICKER_BOOTSTRAP":case 1:t.peerDataOperationRequestType=1;break;case"GENERATE_LINK_PREVIEW":case 2:t.peerDataOperationRequestType=2;break;case"HISTORY_SYNC_ON_DEMAND":case 3:t.peerDataOperationRequestType=3;break;case"PLACEHOLDER_MESSAGE_RESEND":case 4:t.peerDataOperationRequestType=4;break;case"WAFFLE_LINKING_NONCE_FETCH":case 5:t.peerDataOperationRequestType=5;break;case"FULL_HISTORY_SYNC_ON_DEMAND":case 6:t.peerDataOperationRequestType=6;break;case"COMPANION_META_NONCE_FETCH":case 7:t.peerDataOperationRequestType=7;break;case"COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY":case 8:t.peerDataOperationRequestType=8;break;case"COMPANION_CANONICAL_USER_NONCE_FETCH":case 9:t.peerDataOperationRequestType=9;break;case"HISTORY_SYNC_CHUNK_RETRY":case 10:t.peerDataOperationRequestType=10;break;case"GALAXY_FLOW_ACTION":case 11:t.peerDataOperationRequestType=11;break}if(A.requestStickerReupload){if(!Array.isArray(A.requestStickerReupload))throw TypeError(".proto.Message.PeerDataOperationRequestMessage.requestStickerReupload: array expected");t.requestStickerReupload=[];for(var s=0;s>>3){case 1:{p.requestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(s,s.uint32());break}case 2:{p.historySyncConfig=E.proto.DeviceProps.HistorySyncConfig.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest;if(s.requestMetadata!=null){if(typeof s.requestMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.requestMetadata: object expected");g.requestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(s.requestMetadata)}if(s.historySyncConfig!=null){if(typeof s.historySyncConfig!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.historySyncConfig: object expected");g.historySyncConfig=E.proto.DeviceProps.HistorySyncConfig.fromObject(s.historySyncConfig)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.requestMetadata!=null&&s.hasOwnProperty("requestMetadata")&&(c.requestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(s.requestMetadata,g),g.oneofs&&(c._requestMetadata="requestMetadata")),s.historySyncConfig!=null&&s.hasOwnProperty("historySyncConfig")&&(c.historySyncConfig=E.proto.DeviceProps.HistorySyncConfig.toObject(s.historySyncConfig,g),g.oneofs&&(c._historySyncConfig="historySyncConfig")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest"},a})(),i.GalaxyFlowAction=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.type=s.int32();break}case 2:{p.flowId=s.string();break}case 3:{p.stanzaId=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction;switch(s.type){default:if(typeof s.type=="number"){g.type=s.type;break}break;case"NOTIFY_LAUNCH":case 1:g.type=1;break}return s.flowId!=null&&(g.flowId=String(s.flowId)),s.stanzaId!=null&&(g.stanzaId=String(s.stanzaId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.type!=null&&s.hasOwnProperty("type")&&(c.type=g.enums===String?E.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.GalaxyFlowActionType[s.type]===void 0?s.type:E.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.GalaxyFlowActionType[s.type]:s.type,g.oneofs&&(c._type="type")),s.flowId!=null&&s.hasOwnProperty("flowId")&&(c.flowId=s.flowId,g.oneofs&&(c._flowId="flowId")),s.stanzaId!=null&&s.hasOwnProperty("stanzaId")&&(c.stanzaId=s.stanzaId,g.oneofs&&(c._stanzaId="stanzaId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction"},a.GalaxyFlowActionType=(function(){let t={},s=Object.create(t);return s[t[1]="NOTIFY_LAUNCH"]=1,s})(),a})(),i.HistorySyncChunkRetryRequest=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.syncType=s.int32();break}case 2:{p.chunkOrder=s.uint32();break}case 3:{p.chunkNotificationId=s.string();break}case 4:{p.regenerateChunk=s.bool();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest;switch(s.syncType){default:if(typeof s.syncType=="number"){g.syncType=s.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:g.syncType=0;break;case"INITIAL_STATUS_V3":case 1:g.syncType=1;break;case"FULL":case 2:g.syncType=2;break;case"RECENT":case 3:g.syncType=3;break;case"PUSH_NAME":case 4:g.syncType=4;break;case"NON_BLOCKING_DATA":case 5:g.syncType=5;break;case"ON_DEMAND":case 6:g.syncType=6;break;case"NO_HISTORY":case 7:g.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:g.syncType=8;break}return s.chunkOrder!=null&&(g.chunkOrder=s.chunkOrder>>>0),s.chunkNotificationId!=null&&(g.chunkNotificationId=String(s.chunkNotificationId)),s.regenerateChunk!=null&&(g.regenerateChunk=!!s.regenerateChunk),g},a.toObject=function(s,g){g||(g={});var c={};return s.syncType!=null&&s.hasOwnProperty("syncType")&&(c.syncType=g.enums===String?E.proto.Message.HistorySyncType[s.syncType]===void 0?s.syncType:E.proto.Message.HistorySyncType[s.syncType]:s.syncType,g.oneofs&&(c._syncType="syncType")),s.chunkOrder!=null&&s.hasOwnProperty("chunkOrder")&&(c.chunkOrder=s.chunkOrder,g.oneofs&&(c._chunkOrder="chunkOrder")),s.chunkNotificationId!=null&&s.hasOwnProperty("chunkNotificationId")&&(c.chunkNotificationId=s.chunkNotificationId,g.oneofs&&(c._chunkNotificationId="chunkNotificationId")),s.regenerateChunk!=null&&s.hasOwnProperty("regenerateChunk")&&(c.regenerateChunk=s.regenerateChunk,g.oneofs&&(c._regenerateChunk="regenerateChunk")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest"},a})(),i.HistorySyncOnDemandRequest=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.chatJid=s.string();break}case 2:{p.oldestMsgId=s.string();break}case 3:{p.oldestMsgFromMe=s.bool();break}case 4:{p.onDemandMsgCount=s.int32();break}case 5:{p.oldestMsgTimestampMs=s.int64();break}case 6:{p.accountLid=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest;return s.chatJid!=null&&(g.chatJid=String(s.chatJid)),s.oldestMsgId!=null&&(g.oldestMsgId=String(s.oldestMsgId)),s.oldestMsgFromMe!=null&&(g.oldestMsgFromMe=!!s.oldestMsgFromMe),s.onDemandMsgCount!=null&&(g.onDemandMsgCount=s.onDemandMsgCount|0),s.oldestMsgTimestampMs!=null&&(I.Long?(g.oldestMsgTimestampMs=I.Long.fromValue(s.oldestMsgTimestampMs)).unsigned=!1:typeof s.oldestMsgTimestampMs=="string"?g.oldestMsgTimestampMs=parseInt(s.oldestMsgTimestampMs,10):typeof s.oldestMsgTimestampMs=="number"?g.oldestMsgTimestampMs=s.oldestMsgTimestampMs:typeof s.oldestMsgTimestampMs=="object"&&(g.oldestMsgTimestampMs=new I.LongBits(s.oldestMsgTimestampMs.low>>>0,s.oldestMsgTimestampMs.high>>>0).toNumber())),s.accountLid!=null&&(g.accountLid=String(s.accountLid)),g},a.toObject=function(s,g){g||(g={});var c={};return s.chatJid!=null&&s.hasOwnProperty("chatJid")&&(c.chatJid=s.chatJid,g.oneofs&&(c._chatJid="chatJid")),s.oldestMsgId!=null&&s.hasOwnProperty("oldestMsgId")&&(c.oldestMsgId=s.oldestMsgId,g.oneofs&&(c._oldestMsgId="oldestMsgId")),s.oldestMsgFromMe!=null&&s.hasOwnProperty("oldestMsgFromMe")&&(c.oldestMsgFromMe=s.oldestMsgFromMe,g.oneofs&&(c._oldestMsgFromMe="oldestMsgFromMe")),s.onDemandMsgCount!=null&&s.hasOwnProperty("onDemandMsgCount")&&(c.onDemandMsgCount=s.onDemandMsgCount,g.oneofs&&(c._onDemandMsgCount="onDemandMsgCount")),s.oldestMsgTimestampMs!=null&&s.hasOwnProperty("oldestMsgTimestampMs")&&(typeof s.oldestMsgTimestampMs=="number"?c.oldestMsgTimestampMs=g.longs===String?String(s.oldestMsgTimestampMs):s.oldestMsgTimestampMs:c.oldestMsgTimestampMs=g.longs===String?re(s.oldestMsgTimestampMs):g.longs===Number?ae(s.oldestMsgTimestampMs):s.oldestMsgTimestampMs,g.oneofs&&(c._oldestMsgTimestampMs="oldestMsgTimestampMs")),s.accountLid!=null&&s.hasOwnProperty("accountLid")&&(c.accountLid=s.accountLid,g.oneofs&&(c._accountLid="accountLid")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest"},a})(),i.PlaceholderMessageResendRequest=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.messageKey=E.proto.MessageKey.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest;if(s.messageKey!=null){if(typeof s.messageKey!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest.messageKey: object expected");g.messageKey=E.proto.MessageKey.fromObject(s.messageKey)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.messageKey!=null&&s.hasOwnProperty("messageKey")&&(c.messageKey=E.proto.MessageKey.toObject(s.messageKey,g),g.oneofs&&(c._messageKey="messageKey")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest"},a})(),i.RequestStickerReupload=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.fileSha256=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload;return s.fileSha256!=null&&(g.fileSha256=String(s.fileSha256)),g},a.toObject=function(s,g){g||(g={});var c={};return s.fileSha256!=null&&s.hasOwnProperty("fileSha256")&&(c.fileSha256=s.fileSha256,g.oneofs&&(c._fileSha256="fileSha256")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload"},a})(),i.RequestUrlPreview=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.url=s.string();break}case 2:{p.includeHqThumbnail=s.bool();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview;return s.url!=null&&(g.url=String(s.url)),s.includeHqThumbnail!=null&&(g.includeHqThumbnail=!!s.includeHqThumbnail),g},a.toObject=function(s,g){g||(g={});var c={};return s.url!=null&&s.hasOwnProperty("url")&&(c.url=s.url,g.oneofs&&(c._url="url")),s.includeHqThumbnail!=null&&s.hasOwnProperty("includeHqThumbnail")&&(c.includeHqThumbnail=s.includeHqThumbnail,g.oneofs&&(c._includeHqThumbnail="includeHqThumbnail")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview"},a})(),i.SyncDCollectionFatalRecoveryRequest=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.collectionName=s.string();break}case 2:{p.timestamp=s.int64();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest)return s;var g=new E.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest;return s.collectionName!=null&&(g.collectionName=String(s.collectionName)),s.timestamp!=null&&(I.Long?(g.timestamp=I.Long.fromValue(s.timestamp)).unsigned=!1:typeof s.timestamp=="string"?g.timestamp=parseInt(s.timestamp,10):typeof s.timestamp=="number"?g.timestamp=s.timestamp:typeof s.timestamp=="object"&&(g.timestamp=new I.LongBits(s.timestamp.low>>>0,s.timestamp.high>>>0).toNumber())),g},a.toObject=function(s,g){g||(g={});var c={};return s.collectionName!=null&&s.hasOwnProperty("collectionName")&&(c.collectionName=s.collectionName,g.oneofs&&(c._collectionName="collectionName")),s.timestamp!=null&&s.hasOwnProperty("timestamp")&&(typeof s.timestamp=="number"?c.timestamp=g.longs===String?String(s.timestamp):s.timestamp:c.timestamp=g.longs===String?re(s.timestamp):g.longs===Number?ae(s.timestamp):s.timestamp,g.oneofs&&(c._timestamp="timestamp")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest"},a})(),i})(),r.PeerDataOperationRequestResponseMessage=(function(){function i(a){if(this.peerDataOperationResult=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.peerDataOperationRequestType=A.int32();break}case 2:{c.stanzaId=A.string();break}case 3:{c.peerDataOperationResult&&c.peerDataOperationResult.length||(c.peerDataOperationResult=[]),c.peerDataOperationResult.push(E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.decode(A,A.uint32()));break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PeerDataOperationRequestResponseMessage)return A;var t=new E.proto.Message.PeerDataOperationRequestResponseMessage;switch(A.peerDataOperationRequestType){default:if(typeof A.peerDataOperationRequestType=="number"){t.peerDataOperationRequestType=A.peerDataOperationRequestType;break}break;case"UPLOAD_STICKER":case 0:t.peerDataOperationRequestType=0;break;case"SEND_RECENT_STICKER_BOOTSTRAP":case 1:t.peerDataOperationRequestType=1;break;case"GENERATE_LINK_PREVIEW":case 2:t.peerDataOperationRequestType=2;break;case"HISTORY_SYNC_ON_DEMAND":case 3:t.peerDataOperationRequestType=3;break;case"PLACEHOLDER_MESSAGE_RESEND":case 4:t.peerDataOperationRequestType=4;break;case"WAFFLE_LINKING_NONCE_FETCH":case 5:t.peerDataOperationRequestType=5;break;case"FULL_HISTORY_SYNC_ON_DEMAND":case 6:t.peerDataOperationRequestType=6;break;case"COMPANION_META_NONCE_FETCH":case 7:t.peerDataOperationRequestType=7;break;case"COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY":case 8:t.peerDataOperationRequestType=8;break;case"COMPANION_CANONICAL_USER_NONCE_FETCH":case 9:t.peerDataOperationRequestType=9;break;case"HISTORY_SYNC_CHUNK_RETRY":case 10:t.peerDataOperationRequestType=10;break;case"GALAXY_FLOW_ACTION":case 11:t.peerDataOperationRequestType=11;break}if(A.stanzaId!=null&&(t.stanzaId=String(A.stanzaId)),A.peerDataOperationResult){if(!Array.isArray(A.peerDataOperationResult))throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.peerDataOperationResult: array expected");t.peerDataOperationResult=[];for(var s=0;s>>3){case 1:{p.mediaUploadResult=s.int32();break}case 2:{p.stickerMessage=E.proto.Message.StickerMessage.decode(s,s.uint32());break}case 3:{p.linkPreviewResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.decode(s,s.uint32());break}case 4:{p.placeholderMessageResendResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.decode(s,s.uint32());break}case 5:{p.waffleNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.decode(s,s.uint32());break}case 6:{p.fullHistorySyncOnDemandRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.decode(s,s.uint32());break}case 7:{p.companionMetaNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.decode(s,s.uint32());break}case 8:{p.syncdSnapshotFatalRecoveryResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.decode(s,s.uint32());break}case 9:{p.companionCanonicalUserNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.decode(s,s.uint32());break}case 10:{p.historySyncChunkRetryResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult)return s;var g=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult;switch(s.mediaUploadResult){default:if(typeof s.mediaUploadResult=="number"){g.mediaUploadResult=s.mediaUploadResult;break}break;case"GENERAL_ERROR":case 0:g.mediaUploadResult=0;break;case"SUCCESS":case 1:g.mediaUploadResult=1;break;case"NOT_FOUND":case 2:g.mediaUploadResult=2;break;case"DECRYPTION_ERROR":case 3:g.mediaUploadResult=3;break}if(s.stickerMessage!=null){if(typeof s.stickerMessage!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.stickerMessage: object expected");g.stickerMessage=E.proto.Message.StickerMessage.fromObject(s.stickerMessage)}if(s.linkPreviewResponse!=null){if(typeof s.linkPreviewResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.linkPreviewResponse: object expected");g.linkPreviewResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.fromObject(s.linkPreviewResponse)}if(s.placeholderMessageResendResponse!=null){if(typeof s.placeholderMessageResendResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.placeholderMessageResendResponse: object expected");g.placeholderMessageResendResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.fromObject(s.placeholderMessageResendResponse)}if(s.waffleNonceFetchRequestResponse!=null){if(typeof s.waffleNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.waffleNonceFetchRequestResponse: object expected");g.waffleNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.fromObject(s.waffleNonceFetchRequestResponse)}if(s.fullHistorySyncOnDemandRequestResponse!=null){if(typeof s.fullHistorySyncOnDemandRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.fullHistorySyncOnDemandRequestResponse: object expected");g.fullHistorySyncOnDemandRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.fromObject(s.fullHistorySyncOnDemandRequestResponse)}if(s.companionMetaNonceFetchRequestResponse!=null){if(typeof s.companionMetaNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.companionMetaNonceFetchRequestResponse: object expected");g.companionMetaNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.fromObject(s.companionMetaNonceFetchRequestResponse)}if(s.syncdSnapshotFatalRecoveryResponse!=null){if(typeof s.syncdSnapshotFatalRecoveryResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.syncdSnapshotFatalRecoveryResponse: object expected");g.syncdSnapshotFatalRecoveryResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.fromObject(s.syncdSnapshotFatalRecoveryResponse)}if(s.companionCanonicalUserNonceFetchRequestResponse!=null){if(typeof s.companionCanonicalUserNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.companionCanonicalUserNonceFetchRequestResponse: object expected");g.companionCanonicalUserNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.fromObject(s.companionCanonicalUserNonceFetchRequestResponse)}if(s.historySyncChunkRetryResponse!=null){if(typeof s.historySyncChunkRetryResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.historySyncChunkRetryResponse: object expected");g.historySyncChunkRetryResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.fromObject(s.historySyncChunkRetryResponse)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.mediaUploadResult!=null&&s.hasOwnProperty("mediaUploadResult")&&(c.mediaUploadResult=g.enums===String?E.proto.MediaRetryNotification.ResultType[s.mediaUploadResult]===void 0?s.mediaUploadResult:E.proto.MediaRetryNotification.ResultType[s.mediaUploadResult]:s.mediaUploadResult,g.oneofs&&(c._mediaUploadResult="mediaUploadResult")),s.stickerMessage!=null&&s.hasOwnProperty("stickerMessage")&&(c.stickerMessage=E.proto.Message.StickerMessage.toObject(s.stickerMessage,g),g.oneofs&&(c._stickerMessage="stickerMessage")),s.linkPreviewResponse!=null&&s.hasOwnProperty("linkPreviewResponse")&&(c.linkPreviewResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.toObject(s.linkPreviewResponse,g),g.oneofs&&(c._linkPreviewResponse="linkPreviewResponse")),s.placeholderMessageResendResponse!=null&&s.hasOwnProperty("placeholderMessageResendResponse")&&(c.placeholderMessageResendResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.toObject(s.placeholderMessageResendResponse,g),g.oneofs&&(c._placeholderMessageResendResponse="placeholderMessageResendResponse")),s.waffleNonceFetchRequestResponse!=null&&s.hasOwnProperty("waffleNonceFetchRequestResponse")&&(c.waffleNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.toObject(s.waffleNonceFetchRequestResponse,g),g.oneofs&&(c._waffleNonceFetchRequestResponse="waffleNonceFetchRequestResponse")),s.fullHistorySyncOnDemandRequestResponse!=null&&s.hasOwnProperty("fullHistorySyncOnDemandRequestResponse")&&(c.fullHistorySyncOnDemandRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.toObject(s.fullHistorySyncOnDemandRequestResponse,g),g.oneofs&&(c._fullHistorySyncOnDemandRequestResponse="fullHistorySyncOnDemandRequestResponse")),s.companionMetaNonceFetchRequestResponse!=null&&s.hasOwnProperty("companionMetaNonceFetchRequestResponse")&&(c.companionMetaNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.toObject(s.companionMetaNonceFetchRequestResponse,g),g.oneofs&&(c._companionMetaNonceFetchRequestResponse="companionMetaNonceFetchRequestResponse")),s.syncdSnapshotFatalRecoveryResponse!=null&&s.hasOwnProperty("syncdSnapshotFatalRecoveryResponse")&&(c.syncdSnapshotFatalRecoveryResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.toObject(s.syncdSnapshotFatalRecoveryResponse,g),g.oneofs&&(c._syncdSnapshotFatalRecoveryResponse="syncdSnapshotFatalRecoveryResponse")),s.companionCanonicalUserNonceFetchRequestResponse!=null&&s.hasOwnProperty("companionCanonicalUserNonceFetchRequestResponse")&&(c.companionCanonicalUserNonceFetchRequestResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.toObject(s.companionCanonicalUserNonceFetchRequestResponse,g),g.oneofs&&(c._companionCanonicalUserNonceFetchRequestResponse="companionCanonicalUserNonceFetchRequestResponse")),s.historySyncChunkRetryResponse!=null&&s.hasOwnProperty("historySyncChunkRetryResponse")&&(c.historySyncChunkRetryResponse=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.toObject(s.historySyncChunkRetryResponse,g),g.oneofs&&(c._historySyncChunkRetryResponse="historySyncChunkRetryResponse")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult"},a.CompanionCanonicalUserNonceFetchResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.nonce=c.string();break}case 2:{Q.waFbid=c.string();break}case 3:{Q.forceRefresh=c.bool();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse;return c.nonce!=null&&(l.nonce=String(c.nonce)),c.waFbid!=null&&(l.waFbid=String(c.waFbid)),c.forceRefresh!=null&&(l.forceRefresh=!!c.forceRefresh),l},t.toObject=function(c,l){l||(l={});var p={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(p.nonce=c.nonce,l.oneofs&&(p._nonce="nonce")),c.waFbid!=null&&c.hasOwnProperty("waFbid")&&(p.waFbid=c.waFbid,l.oneofs&&(p._waFbid="waFbid")),c.forceRefresh!=null&&c.hasOwnProperty("forceRefresh")&&(p.forceRefresh=c.forceRefresh,l.oneofs&&(p._forceRefresh="forceRefresh")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse"},t})(),a.CompanionMetaNonceFetchResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.nonce=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse;return c.nonce!=null&&(l.nonce=String(c.nonce)),l},t.toObject=function(c,l){l||(l={});var p={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(p.nonce=c.nonce,l.oneofs&&(p._nonce="nonce")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse"},t})(),a.FullHistorySyncOnDemandRequestResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.requestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(c,c.uint32());break}case 2:{Q.responseCode=c.int32();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse;if(c.requestMetadata!=null){if(typeof c.requestMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.requestMetadata: object expected");l.requestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(c.requestMetadata)}switch(c.responseCode){default:if(typeof c.responseCode=="number"){l.responseCode=c.responseCode;break}break;case"REQUEST_SUCCESS":case 0:l.responseCode=0;break;case"REQUEST_TIME_EXPIRED":case 1:l.responseCode=1;break;case"DECLINED_SHARING_HISTORY":case 2:l.responseCode=2;break;case"GENERIC_ERROR":case 3:l.responseCode=3;break;case"ERROR_REQUEST_ON_NON_SMB_PRIMARY":case 4:l.responseCode=4;break;case"ERROR_HOSTED_DEVICE_NOT_CONNECTED":case 5:l.responseCode=5;break;case"ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET":case 6:l.responseCode=6;break}return l},t.toObject=function(c,l){l||(l={});var p={};return c.requestMetadata!=null&&c.hasOwnProperty("requestMetadata")&&(p.requestMetadata=E.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(c.requestMetadata,l),l.oneofs&&(p._requestMetadata="requestMetadata")),c.responseCode!=null&&c.hasOwnProperty("responseCode")&&(p.responseCode=l.enums===String?E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandResponseCode[c.responseCode]===void 0?c.responseCode:E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandResponseCode[c.responseCode]:c.responseCode,l.oneofs&&(p._responseCode="responseCode")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse"},t})(),a.FullHistorySyncOnDemandResponseCode=(function(){let t={},s=Object.create(t);return s[t[0]="REQUEST_SUCCESS"]=0,s[t[1]="REQUEST_TIME_EXPIRED"]=1,s[t[2]="DECLINED_SHARING_HISTORY"]=2,s[t[3]="GENERIC_ERROR"]=3,s[t[4]="ERROR_REQUEST_ON_NON_SMB_PRIMARY"]=4,s[t[5]="ERROR_HOSTED_DEVICE_NOT_CONNECTED"]=5,s[t[6]="ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET"]=6,s})(),a.HistorySyncChunkRetryResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.syncType=c.int32();break}case 2:{Q.chunkOrder=c.uint32();break}case 3:{Q.requestId=c.string();break}case 4:{Q.responseCode=c.int32();break}case 5:{Q.canRecover=c.bool();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse;switch(c.syncType){default:if(typeof c.syncType=="number"){l.syncType=c.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:l.syncType=0;break;case"INITIAL_STATUS_V3":case 1:l.syncType=1;break;case"FULL":case 2:l.syncType=2;break;case"RECENT":case 3:l.syncType=3;break;case"PUSH_NAME":case 4:l.syncType=4;break;case"NON_BLOCKING_DATA":case 5:l.syncType=5;break;case"ON_DEMAND":case 6:l.syncType=6;break;case"NO_HISTORY":case 7:l.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:l.syncType=8;break}switch(c.chunkOrder!=null&&(l.chunkOrder=c.chunkOrder>>>0),c.requestId!=null&&(l.requestId=String(c.requestId)),c.responseCode){default:if(typeof c.responseCode=="number"){l.responseCode=c.responseCode;break}break;case"GENERATION_ERROR":case 1:l.responseCode=1;break;case"CHUNK_CONSUMED":case 2:l.responseCode=2;break;case"TIMEOUT":case 3:l.responseCode=3;break;case"SESSION_EXHAUSTED":case 4:l.responseCode=4;break;case"CHUNK_EXHAUSTED":case 5:l.responseCode=5;break;case"DUPLICATED_REQUEST":case 6:l.responseCode=6;break}return c.canRecover!=null&&(l.canRecover=!!c.canRecover),l},t.toObject=function(c,l){l||(l={});var p={};return c.syncType!=null&&c.hasOwnProperty("syncType")&&(p.syncType=l.enums===String?E.proto.Message.HistorySyncType[c.syncType]===void 0?c.syncType:E.proto.Message.HistorySyncType[c.syncType]:c.syncType,l.oneofs&&(p._syncType="syncType")),c.chunkOrder!=null&&c.hasOwnProperty("chunkOrder")&&(p.chunkOrder=c.chunkOrder,l.oneofs&&(p._chunkOrder="chunkOrder")),c.requestId!=null&&c.hasOwnProperty("requestId")&&(p.requestId=c.requestId,l.oneofs&&(p._requestId="requestId")),c.responseCode!=null&&c.hasOwnProperty("responseCode")&&(p.responseCode=l.enums===String?E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponseCode[c.responseCode]===void 0?c.responseCode:E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponseCode[c.responseCode]:c.responseCode,l.oneofs&&(p._responseCode="responseCode")),c.canRecover!=null&&c.hasOwnProperty("canRecover")&&(p.canRecover=c.canRecover,l.oneofs&&(p._canRecover="canRecover")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse"},t})(),a.HistorySyncChunkRetryResponseCode=(function(){let t={},s=Object.create(t);return s[t[1]="GENERATION_ERROR"]=1,s[t[2]="CHUNK_CONSUMED"]=2,s[t[3]="TIMEOUT"]=3,s[t[4]="SESSION_EXHAUSTED"]=4,s[t[5]="CHUNK_EXHAUSTED"]=5,s[t[6]="DUPLICATED_REQUEST"]=6,s})(),a.LinkPreviewResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.url=c.string();break}case 2:{Q.title=c.string();break}case 3:{Q.description=c.string();break}case 4:{Q.thumbData=c.bytes();break}case 6:{Q.matchText=c.string();break}case 7:{Q.previewType=c.string();break}case 8:{Q.hqThumbnail=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.decode(c,c.uint32());break}case 9:{Q.previewMetadata=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.decode(c,c.uint32());break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse;if(c.url!=null&&(l.url=String(c.url)),c.title!=null&&(l.title=String(c.title)),c.description!=null&&(l.description=String(c.description)),c.thumbData!=null&&(typeof c.thumbData=="string"?I.base64.decode(c.thumbData,l.thumbData=I.newBuffer(I.base64.length(c.thumbData)),0):c.thumbData.length>=0&&(l.thumbData=c.thumbData)),c.matchText!=null&&(l.matchText=String(c.matchText)),c.previewType!=null&&(l.previewType=String(c.previewType)),c.hqThumbnail!=null){if(typeof c.hqThumbnail!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.hqThumbnail: object expected");l.hqThumbnail=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.fromObject(c.hqThumbnail)}if(c.previewMetadata!=null){if(typeof c.previewMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.previewMetadata: object expected");l.previewMetadata=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.fromObject(c.previewMetadata)}return l},t.toObject=function(c,l){l||(l={});var p={};return c.url!=null&&c.hasOwnProperty("url")&&(p.url=c.url,l.oneofs&&(p._url="url")),c.title!=null&&c.hasOwnProperty("title")&&(p.title=c.title,l.oneofs&&(p._title="title")),c.description!=null&&c.hasOwnProperty("description")&&(p.description=c.description,l.oneofs&&(p._description="description")),c.thumbData!=null&&c.hasOwnProperty("thumbData")&&(p.thumbData=l.bytes===String?I.base64.encode(c.thumbData,0,c.thumbData.length):l.bytes===Array?Array.prototype.slice.call(c.thumbData):c.thumbData,l.oneofs&&(p._thumbData="thumbData")),c.matchText!=null&&c.hasOwnProperty("matchText")&&(p.matchText=c.matchText,l.oneofs&&(p._matchText="matchText")),c.previewType!=null&&c.hasOwnProperty("previewType")&&(p.previewType=c.previewType,l.oneofs&&(p._previewType="previewType")),c.hqThumbnail!=null&&c.hasOwnProperty("hqThumbnail")&&(p.hqThumbnail=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.toObject(c.hqThumbnail,l),l.oneofs&&(p._hqThumbnail="hqThumbnail")),c.previewMetadata!=null&&c.hasOwnProperty("previewMetadata")&&(p.previewMetadata=E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.toObject(c.previewMetadata,l),l.oneofs&&(p._previewMetadata="previewMetadata")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse"},t.LinkPreviewHighQualityThumbnail=(function(){function g(l){if(l)for(var p=Object.keys(l),B=0;B>>3){case 1:{y.directPath=p.string();break}case 2:{y.thumbHash=p.string();break}case 3:{y.encThumbHash=p.string();break}case 4:{y.mediaKey=p.bytes();break}case 5:{y.mediaKeyTimestampMs=p.int64();break}case 6:{y.thumbWidth=p.int32();break}case 7:{y.thumbHeight=p.int32();break}default:p.skipType(m&7);break}}return y},g.fromObject=function(p){if(p instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail)return p;var B=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail;return p.directPath!=null&&(B.directPath=String(p.directPath)),p.thumbHash!=null&&(B.thumbHash=String(p.thumbHash)),p.encThumbHash!=null&&(B.encThumbHash=String(p.encThumbHash)),p.mediaKey!=null&&(typeof p.mediaKey=="string"?I.base64.decode(p.mediaKey,B.mediaKey=I.newBuffer(I.base64.length(p.mediaKey)),0):p.mediaKey.length>=0&&(B.mediaKey=p.mediaKey)),p.mediaKeyTimestampMs!=null&&(I.Long?(B.mediaKeyTimestampMs=I.Long.fromValue(p.mediaKeyTimestampMs)).unsigned=!1:typeof p.mediaKeyTimestampMs=="string"?B.mediaKeyTimestampMs=parseInt(p.mediaKeyTimestampMs,10):typeof p.mediaKeyTimestampMs=="number"?B.mediaKeyTimestampMs=p.mediaKeyTimestampMs:typeof p.mediaKeyTimestampMs=="object"&&(B.mediaKeyTimestampMs=new I.LongBits(p.mediaKeyTimestampMs.low>>>0,p.mediaKeyTimestampMs.high>>>0).toNumber())),p.thumbWidth!=null&&(B.thumbWidth=p.thumbWidth|0),p.thumbHeight!=null&&(B.thumbHeight=p.thumbHeight|0),B},g.toObject=function(p,B){B||(B={});var Q={};return p.directPath!=null&&p.hasOwnProperty("directPath")&&(Q.directPath=p.directPath,B.oneofs&&(Q._directPath="directPath")),p.thumbHash!=null&&p.hasOwnProperty("thumbHash")&&(Q.thumbHash=p.thumbHash,B.oneofs&&(Q._thumbHash="thumbHash")),p.encThumbHash!=null&&p.hasOwnProperty("encThumbHash")&&(Q.encThumbHash=p.encThumbHash,B.oneofs&&(Q._encThumbHash="encThumbHash")),p.mediaKey!=null&&p.hasOwnProperty("mediaKey")&&(Q.mediaKey=B.bytes===String?I.base64.encode(p.mediaKey,0,p.mediaKey.length):B.bytes===Array?Array.prototype.slice.call(p.mediaKey):p.mediaKey,B.oneofs&&(Q._mediaKey="mediaKey")),p.mediaKeyTimestampMs!=null&&p.hasOwnProperty("mediaKeyTimestampMs")&&(typeof p.mediaKeyTimestampMs=="number"?Q.mediaKeyTimestampMs=B.longs===String?String(p.mediaKeyTimestampMs):p.mediaKeyTimestampMs:Q.mediaKeyTimestampMs=B.longs===String?re(p.mediaKeyTimestampMs):B.longs===Number?ae(p.mediaKeyTimestampMs):p.mediaKeyTimestampMs,B.oneofs&&(Q._mediaKeyTimestampMs="mediaKeyTimestampMs")),p.thumbWidth!=null&&p.hasOwnProperty("thumbWidth")&&(Q.thumbWidth=p.thumbWidth,B.oneofs&&(Q._thumbWidth="thumbWidth")),p.thumbHeight!=null&&p.hasOwnProperty("thumbHeight")&&(Q.thumbHeight=p.thumbHeight,B.oneofs&&(Q._thumbHeight="thumbHeight")),Q},g.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},g.getTypeUrl=function(p){return p===void 0&&(p="type.googleapis.com"),p+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail"},g})(),t.PaymentLinkPreviewMetadata=(function(){function g(l){if(l)for(var p=Object.keys(l),B=0;B>>3){case 1:{y.isBusinessVerified=p.bool();break}case 2:{y.providerName=p.string();break}default:p.skipType(m&7);break}}return y},g.fromObject=function(p){if(p instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata)return p;var B=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata;return p.isBusinessVerified!=null&&(B.isBusinessVerified=!!p.isBusinessVerified),p.providerName!=null&&(B.providerName=String(p.providerName)),B},g.toObject=function(p,B){B||(B={});var Q={};return p.isBusinessVerified!=null&&p.hasOwnProperty("isBusinessVerified")&&(Q.isBusinessVerified=p.isBusinessVerified,B.oneofs&&(Q._isBusinessVerified="isBusinessVerified")),p.providerName!=null&&p.hasOwnProperty("providerName")&&(Q.providerName=p.providerName,B.oneofs&&(Q._providerName="providerName")),Q},g.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},g.getTypeUrl=function(p){return p===void 0&&(p="type.googleapis.com"),p+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata"},g})(),t})(),a.PlaceholderMessageResendResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.webMessageInfoBytes=c.bytes();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse;return c.webMessageInfoBytes!=null&&(typeof c.webMessageInfoBytes=="string"?I.base64.decode(c.webMessageInfoBytes,l.webMessageInfoBytes=I.newBuffer(I.base64.length(c.webMessageInfoBytes)),0):c.webMessageInfoBytes.length>=0&&(l.webMessageInfoBytes=c.webMessageInfoBytes)),l},t.toObject=function(c,l){l||(l={});var p={};return c.webMessageInfoBytes!=null&&c.hasOwnProperty("webMessageInfoBytes")&&(p.webMessageInfoBytes=l.bytes===String?I.base64.encode(c.webMessageInfoBytes,0,c.webMessageInfoBytes.length):l.bytes===Array?Array.prototype.slice.call(c.webMessageInfoBytes):c.webMessageInfoBytes,l.oneofs&&(p._webMessageInfoBytes="webMessageInfoBytes")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse"},t})(),a.SyncDSnapshotFatalRecoveryResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.collectionSnapshot=c.bytes();break}case 2:{Q.isCompressed=c.bool();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse;return c.collectionSnapshot!=null&&(typeof c.collectionSnapshot=="string"?I.base64.decode(c.collectionSnapshot,l.collectionSnapshot=I.newBuffer(I.base64.length(c.collectionSnapshot)),0):c.collectionSnapshot.length>=0&&(l.collectionSnapshot=c.collectionSnapshot)),c.isCompressed!=null&&(l.isCompressed=!!c.isCompressed),l},t.toObject=function(c,l){l||(l={});var p={};return c.collectionSnapshot!=null&&c.hasOwnProperty("collectionSnapshot")&&(p.collectionSnapshot=l.bytes===String?I.base64.encode(c.collectionSnapshot,0,c.collectionSnapshot.length):l.bytes===Array?Array.prototype.slice.call(c.collectionSnapshot):c.collectionSnapshot,l.oneofs&&(p._collectionSnapshot="collectionSnapshot")),c.isCompressed!=null&&c.hasOwnProperty("isCompressed")&&(p.isCompressed=c.isCompressed,l.oneofs&&(p._isCompressed="isCompressed")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse"},t})(),a.WaffleNonceFetchResponse=(function(){function t(g){if(g)for(var c=Object.keys(g),l=0;l>>3){case 1:{Q.nonce=c.string();break}case 2:{Q.waEntFbid=c.string();break}default:c.skipType(f&7);break}}return Q},t.fromObject=function(c){if(c instanceof E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse)return c;var l=new E.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse;return c.nonce!=null&&(l.nonce=String(c.nonce)),c.waEntFbid!=null&&(l.waEntFbid=String(c.waEntFbid)),l},t.toObject=function(c,l){l||(l={});var p={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(p.nonce=c.nonce,l.oneofs&&(p._nonce="nonce")),c.waEntFbid!=null&&c.hasOwnProperty("waEntFbid")&&(p.waEntFbid=c.waEntFbid,l.oneofs&&(p._waEntFbid="waEntFbid")),p},t.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},t.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse"},t})(),a})(),i})(),r.PeerDataOperationRequestType=(function(){let i={},e=Object.create(i);return e[i[0]="UPLOAD_STICKER"]=0,e[i[1]="SEND_RECENT_STICKER_BOOTSTRAP"]=1,e[i[2]="GENERATE_LINK_PREVIEW"]=2,e[i[3]="HISTORY_SYNC_ON_DEMAND"]=3,e[i[4]="PLACEHOLDER_MESSAGE_RESEND"]=4,e[i[5]="WAFFLE_LINKING_NONCE_FETCH"]=5,e[i[6]="FULL_HISTORY_SYNC_ON_DEMAND"]=6,e[i[7]="COMPANION_META_NONCE_FETCH"]=7,e[i[8]="COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY"]=8,e[i[9]="COMPANION_CANONICAL_USER_NONCE_FETCH"]=9,e[i[10]="HISTORY_SYNC_CHUNK_RETRY"]=10,e[i[11]="GALAXY_FLOW_ACTION"]=11,e})(),r.PinInChatMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.type=A.int32();break}case 3:{c.senderTimestampMs=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PinInChatMessage)return A;var t=new E.proto.Message.PinInChatMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.PinInChatMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"UNKNOWN_TYPE":case 0:t.type=0;break;case"PIN_FOR_ALL":case 1:t.type=1;break;case"UNPIN_FOR_ALL":case 2:t.type=2;break}return A.senderTimestampMs!=null&&(I.Long?(t.senderTimestampMs=I.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?t.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?t.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(t.senderTimestampMs=new I.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.Message.PinInChatMessage.Type[A.type]===void 0?A.type:E.proto.Message.PinInChatMessage.Type[A.type]:A.type,t.oneofs&&(s._type="type")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=t.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=t.longs===String?re(A.senderTimestampMs):t.longs===Number?ae(A.senderTimestampMs):A.senderTimestampMs,t.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PinInChatMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN_TYPE"]=0,A[a[1]="PIN_FOR_ALL"]=1,A[a[2]="UNPIN_FOR_ALL"]=2,A})(),i})(),r.PlaceholderMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.type=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PlaceholderMessage)return A;var t=new E.proto.Message.PlaceholderMessage;switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"MASK_LINKED_DEVICES":case 0:t.type=0;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.Message.PlaceholderMessage.PlaceholderType[A.type]===void 0?A.type:E.proto.Message.PlaceholderMessage.PlaceholderType[A.type]:A.type,t.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PlaceholderMessage"},i.PlaceholderType=(function(){let a={},A=Object.create(a);return A[a[0]="MASK_LINKED_DEVICES"]=0,A})(),i})(),r.PollContentType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="TEXT"]=1,e[i[2]="IMAGE"]=2,e})(),r.PollCreationMessage=(function(){function i(a){if(this.options=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.encKey=A.bytes();break}case 2:{c.name=A.string();break}case 3:{c.options&&c.options.length||(c.options=[]),c.options.push(E.proto.Message.PollCreationMessage.Option.decode(A,A.uint32()));break}case 4:{c.selectableOptionsCount=A.uint32();break}case 5:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 6:{c.pollContentType=A.int32();break}case 7:{c.pollType=A.int32();break}case 8:{c.correctAnswer=E.proto.Message.PollCreationMessage.Option.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PollCreationMessage)return A;var t=new E.proto.Message.PollCreationMessage;if(A.encKey!=null&&(typeof A.encKey=="string"?I.base64.decode(A.encKey,t.encKey=I.newBuffer(I.base64.length(A.encKey)),0):A.encKey.length>=0&&(t.encKey=A.encKey)),A.name!=null&&(t.name=String(A.name)),A.options){if(!Array.isArray(A.options))throw TypeError(".proto.Message.PollCreationMessage.options: array expected");t.options=[];for(var s=0;s>>0),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.PollCreationMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.pollContentType){default:if(typeof A.pollContentType=="number"){t.pollContentType=A.pollContentType;break}break;case"UNKNOWN":case 0:t.pollContentType=0;break;case"TEXT":case 1:t.pollContentType=1;break;case"IMAGE":case 2:t.pollContentType=2;break}switch(A.pollType){default:if(typeof A.pollType=="number"){t.pollType=A.pollType;break}break;case"POLL":case 0:t.pollType=0;break;case"QUIZ":case 1:t.pollType=1;break}if(A.correctAnswer!=null){if(typeof A.correctAnswer!="object")throw TypeError(".proto.Message.PollCreationMessage.correctAnswer: object expected");t.correctAnswer=E.proto.Message.PollCreationMessage.Option.fromObject(A.correctAnswer)}return t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.options=[]),A.encKey!=null&&A.hasOwnProperty("encKey")&&(s.encKey=t.bytes===String?I.base64.encode(A.encKey,0,A.encKey.length):t.bytes===Array?Array.prototype.slice.call(A.encKey):A.encKey,t.oneofs&&(s._encKey="encKey")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.options&&A.options.length){s.options=[];for(var g=0;g>>3){case 1:{p.optionName=s.string();break}case 2:{p.optionHash=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PollCreationMessage.Option)return s;var g=new E.proto.Message.PollCreationMessage.Option;return s.optionName!=null&&(g.optionName=String(s.optionName)),s.optionHash!=null&&(g.optionHash=String(s.optionHash)),g},a.toObject=function(s,g){g||(g={});var c={};return s.optionName!=null&&s.hasOwnProperty("optionName")&&(c.optionName=s.optionName,g.oneofs&&(c._optionName="optionName")),s.optionHash!=null&&s.hasOwnProperty("optionHash")&&(c.optionHash=s.optionHash,g.oneofs&&(c._optionHash="optionHash")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PollCreationMessage.Option"},a})(),i})(),r.PollEncValue=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.encPayload=A.bytes();break}case 2:{c.encIv=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PollEncValue)return A;var t=new E.proto.Message.PollEncValue;return A.encPayload!=null&&(typeof A.encPayload=="string"?I.base64.decode(A.encPayload,t.encPayload=I.newBuffer(I.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(t.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?I.base64.decode(A.encIv,t.encIv=I.newBuffer(I.base64.length(A.encIv)),0):A.encIv.length>=0&&(t.encIv=A.encIv)),t},i.toObject=function(A,t){t||(t={});var s={};return A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=t.bytes===String?I.base64.encode(A.encPayload,0,A.encPayload.length):t.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,t.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=t.bytes===String?I.base64.encode(A.encIv,0,A.encIv.length):t.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,t.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PollEncValue"},i})(),r.PollResultSnapshotMessage=(function(){function i(a){if(this.pollVotes=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.name=A.string();break}case 2:{c.pollVotes&&c.pollVotes.length||(c.pollVotes=[]),c.pollVotes.push(E.proto.Message.PollResultSnapshotMessage.PollVote.decode(A,A.uint32()));break}case 3:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.pollType=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PollResultSnapshotMessage)return A;var t=new E.proto.Message.PollResultSnapshotMessage;if(A.name!=null&&(t.name=String(A.name)),A.pollVotes){if(!Array.isArray(A.pollVotes))throw TypeError(".proto.Message.PollResultSnapshotMessage.pollVotes: array expected");t.pollVotes=[];for(var s=0;s>>3){case 1:{p.optionName=s.string();break}case 2:{p.optionVoteCount=s.int64();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.PollResultSnapshotMessage.PollVote)return s;var g=new E.proto.Message.PollResultSnapshotMessage.PollVote;return s.optionName!=null&&(g.optionName=String(s.optionName)),s.optionVoteCount!=null&&(I.Long?(g.optionVoteCount=I.Long.fromValue(s.optionVoteCount)).unsigned=!1:typeof s.optionVoteCount=="string"?g.optionVoteCount=parseInt(s.optionVoteCount,10):typeof s.optionVoteCount=="number"?g.optionVoteCount=s.optionVoteCount:typeof s.optionVoteCount=="object"&&(g.optionVoteCount=new I.LongBits(s.optionVoteCount.low>>>0,s.optionVoteCount.high>>>0).toNumber())),g},a.toObject=function(s,g){g||(g={});var c={};return s.optionName!=null&&s.hasOwnProperty("optionName")&&(c.optionName=s.optionName,g.oneofs&&(c._optionName="optionName")),s.optionVoteCount!=null&&s.hasOwnProperty("optionVoteCount")&&(typeof s.optionVoteCount=="number"?c.optionVoteCount=g.longs===String?String(s.optionVoteCount):s.optionVoteCount:c.optionVoteCount=g.longs===String?re(s.optionVoteCount):g.longs===Number?ae(s.optionVoteCount):s.optionVoteCount,g.oneofs&&(c._optionVoteCount="optionVoteCount")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PollResultSnapshotMessage.PollVote"},a})(),i})(),r.PollType=(function(){let i={},e=Object.create(i);return e[i[0]="POLL"]=0,e[i[1]="QUIZ"]=1,e})(),r.PollUpdateMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.pollCreationMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.vote=E.proto.Message.PollEncValue.decode(A,A.uint32());break}case 3:{c.metadata=E.proto.Message.PollUpdateMessageMetadata.decode(A,A.uint32());break}case 4:{c.senderTimestampMs=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.PollUpdateMessage)return A;var t=new E.proto.Message.PollUpdateMessage;if(A.pollCreationMessageKey!=null){if(typeof A.pollCreationMessageKey!="object")throw TypeError(".proto.Message.PollUpdateMessage.pollCreationMessageKey: object expected");t.pollCreationMessageKey=E.proto.MessageKey.fromObject(A.pollCreationMessageKey)}if(A.vote!=null){if(typeof A.vote!="object")throw TypeError(".proto.Message.PollUpdateMessage.vote: object expected");t.vote=E.proto.Message.PollEncValue.fromObject(A.vote)}if(A.metadata!=null){if(typeof A.metadata!="object")throw TypeError(".proto.Message.PollUpdateMessage.metadata: object expected");t.metadata=E.proto.Message.PollUpdateMessageMetadata.fromObject(A.metadata)}return A.senderTimestampMs!=null&&(I.Long?(t.senderTimestampMs=I.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?t.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?t.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(t.senderTimestampMs=new I.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.pollCreationMessageKey!=null&&A.hasOwnProperty("pollCreationMessageKey")&&(s.pollCreationMessageKey=E.proto.MessageKey.toObject(A.pollCreationMessageKey,t),t.oneofs&&(s._pollCreationMessageKey="pollCreationMessageKey")),A.vote!=null&&A.hasOwnProperty("vote")&&(s.vote=E.proto.Message.PollEncValue.toObject(A.vote,t),t.oneofs&&(s._vote="vote")),A.metadata!=null&&A.hasOwnProperty("metadata")&&(s.metadata=E.proto.Message.PollUpdateMessageMetadata.toObject(A.metadata,t),t.oneofs&&(s._metadata="metadata")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=t.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=t.longs===String?re(A.senderTimestampMs):t.longs===Number?ae(A.senderTimestampMs):A.senderTimestampMs,t.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PollUpdateMessage"},i})(),r.PollUpdateMessageMetadata=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){default:a.skipType(c&7);break}}return g},i.fromObject=function(a){return a instanceof E.proto.Message.PollUpdateMessageMetadata?a:new E.proto.Message.PollUpdateMessageMetadata},i.toObject=function(){return{}},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Message.PollUpdateMessageMetadata"},i})(),r.PollVoteMessage=(function(){function i(e){if(this.selectedOptions=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.selectedOptions&&g.selectedOptions.length||(g.selectedOptions=[]),g.selectedOptions.push(a.bytes());break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.Message.PollVoteMessage)return a;var A=new E.proto.Message.PollVoteMessage;if(a.selectedOptions){if(!Array.isArray(a.selectedOptions))throw TypeError(".proto.Message.PollVoteMessage.selectedOptions: array expected");A.selectedOptions=[];for(var t=0;t=0&&(A.selectedOptions[t]=a.selectedOptions[t])}return A},i.toObject=function(a,A){A||(A={});var t={};if((A.arrays||A.defaults)&&(t.selectedOptions=[]),a.selectedOptions&&a.selectedOptions.length){t.selectedOptions=[];for(var s=0;s>>3){case 1:{c.product=E.proto.Message.ProductMessage.ProductSnapshot.decode(A,A.uint32());break}case 2:{c.businessOwnerJid=A.string();break}case 4:{c.catalog=E.proto.Message.ProductMessage.CatalogSnapshot.decode(A,A.uint32());break}case 5:{c.body=A.string();break}case 6:{c.footer=A.string();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ProductMessage)return A;var t=new E.proto.Message.ProductMessage;if(A.product!=null){if(typeof A.product!="object")throw TypeError(".proto.Message.ProductMessage.product: object expected");t.product=E.proto.Message.ProductMessage.ProductSnapshot.fromObject(A.product)}if(A.businessOwnerJid!=null&&(t.businessOwnerJid=String(A.businessOwnerJid)),A.catalog!=null){if(typeof A.catalog!="object")throw TypeError(".proto.Message.ProductMessage.catalog: object expected");t.catalog=E.proto.Message.ProductMessage.CatalogSnapshot.fromObject(A.catalog)}if(A.body!=null&&(t.body=String(A.body)),A.footer!=null&&(t.footer=String(A.footer)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ProductMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.product!=null&&A.hasOwnProperty("product")&&(s.product=E.proto.Message.ProductMessage.ProductSnapshot.toObject(A.product,t),t.oneofs&&(s._product="product")),A.businessOwnerJid!=null&&A.hasOwnProperty("businessOwnerJid")&&(s.businessOwnerJid=A.businessOwnerJid,t.oneofs&&(s._businessOwnerJid="businessOwnerJid")),A.catalog!=null&&A.hasOwnProperty("catalog")&&(s.catalog=E.proto.Message.ProductMessage.CatalogSnapshot.toObject(A.catalog,t),t.oneofs&&(s._catalog="catalog")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,t.oneofs&&(s._body="body")),A.footer!=null&&A.hasOwnProperty("footer")&&(s.footer=A.footer,t.oneofs&&(s._footer="footer")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ProductMessage"},i.CatalogSnapshot=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.catalogImage=E.proto.Message.ImageMessage.decode(s,s.uint32());break}case 2:{p.title=s.string();break}case 3:{p.description=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ProductMessage.CatalogSnapshot)return s;var g=new E.proto.Message.ProductMessage.CatalogSnapshot;if(s.catalogImage!=null){if(typeof s.catalogImage!="object")throw TypeError(".proto.Message.ProductMessage.CatalogSnapshot.catalogImage: object expected");g.catalogImage=E.proto.Message.ImageMessage.fromObject(s.catalogImage)}return s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),g},a.toObject=function(s,g){g||(g={});var c={};return s.catalogImage!=null&&s.hasOwnProperty("catalogImage")&&(c.catalogImage=E.proto.Message.ImageMessage.toObject(s.catalogImage,g),g.oneofs&&(c._catalogImage="catalogImage")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ProductMessage.CatalogSnapshot"},a})(),i.ProductSnapshot=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.productImage=E.proto.Message.ImageMessage.decode(s,s.uint32());break}case 2:{p.productId=s.string();break}case 3:{p.title=s.string();break}case 4:{p.description=s.string();break}case 5:{p.currencyCode=s.string();break}case 6:{p.priceAmount1000=s.int64();break}case 7:{p.retailerId=s.string();break}case 8:{p.url=s.string();break}case 9:{p.productImageCount=s.uint32();break}case 11:{p.firstImageId=s.string();break}case 12:{p.salePriceAmount1000=s.int64();break}case 13:{p.signedUrl=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.ProductMessage.ProductSnapshot)return s;var g=new E.proto.Message.ProductMessage.ProductSnapshot;if(s.productImage!=null){if(typeof s.productImage!="object")throw TypeError(".proto.Message.ProductMessage.ProductSnapshot.productImage: object expected");g.productImage=E.proto.Message.ImageMessage.fromObject(s.productImage)}return s.productId!=null&&(g.productId=String(s.productId)),s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.currencyCode!=null&&(g.currencyCode=String(s.currencyCode)),s.priceAmount1000!=null&&(I.Long?(g.priceAmount1000=I.Long.fromValue(s.priceAmount1000)).unsigned=!1:typeof s.priceAmount1000=="string"?g.priceAmount1000=parseInt(s.priceAmount1000,10):typeof s.priceAmount1000=="number"?g.priceAmount1000=s.priceAmount1000:typeof s.priceAmount1000=="object"&&(g.priceAmount1000=new I.LongBits(s.priceAmount1000.low>>>0,s.priceAmount1000.high>>>0).toNumber())),s.retailerId!=null&&(g.retailerId=String(s.retailerId)),s.url!=null&&(g.url=String(s.url)),s.productImageCount!=null&&(g.productImageCount=s.productImageCount>>>0),s.firstImageId!=null&&(g.firstImageId=String(s.firstImageId)),s.salePriceAmount1000!=null&&(I.Long?(g.salePriceAmount1000=I.Long.fromValue(s.salePriceAmount1000)).unsigned=!1:typeof s.salePriceAmount1000=="string"?g.salePriceAmount1000=parseInt(s.salePriceAmount1000,10):typeof s.salePriceAmount1000=="number"?g.salePriceAmount1000=s.salePriceAmount1000:typeof s.salePriceAmount1000=="object"&&(g.salePriceAmount1000=new I.LongBits(s.salePriceAmount1000.low>>>0,s.salePriceAmount1000.high>>>0).toNumber())),s.signedUrl!=null&&(g.signedUrl=String(s.signedUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productImage!=null&&s.hasOwnProperty("productImage")&&(c.productImage=E.proto.Message.ImageMessage.toObject(s.productImage,g),g.oneofs&&(c._productImage="productImage")),s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.currencyCode!=null&&s.hasOwnProperty("currencyCode")&&(c.currencyCode=s.currencyCode,g.oneofs&&(c._currencyCode="currencyCode")),s.priceAmount1000!=null&&s.hasOwnProperty("priceAmount1000")&&(typeof s.priceAmount1000=="number"?c.priceAmount1000=g.longs===String?String(s.priceAmount1000):s.priceAmount1000:c.priceAmount1000=g.longs===String?re(s.priceAmount1000):g.longs===Number?ae(s.priceAmount1000):s.priceAmount1000,g.oneofs&&(c._priceAmount1000="priceAmount1000")),s.retailerId!=null&&s.hasOwnProperty("retailerId")&&(c.retailerId=s.retailerId,g.oneofs&&(c._retailerId="retailerId")),s.url!=null&&s.hasOwnProperty("url")&&(c.url=s.url,g.oneofs&&(c._url="url")),s.productImageCount!=null&&s.hasOwnProperty("productImageCount")&&(c.productImageCount=s.productImageCount,g.oneofs&&(c._productImageCount="productImageCount")),s.firstImageId!=null&&s.hasOwnProperty("firstImageId")&&(c.firstImageId=s.firstImageId,g.oneofs&&(c._firstImageId="firstImageId")),s.salePriceAmount1000!=null&&s.hasOwnProperty("salePriceAmount1000")&&(typeof s.salePriceAmount1000=="number"?c.salePriceAmount1000=g.longs===String?String(s.salePriceAmount1000):s.salePriceAmount1000:c.salePriceAmount1000=g.longs===String?re(s.salePriceAmount1000):g.longs===Number?ae(s.salePriceAmount1000):s.salePriceAmount1000,g.oneofs&&(c._salePriceAmount1000="salePriceAmount1000")),s.signedUrl!=null&&s.hasOwnProperty("signedUrl")&&(c.signedUrl=s.signedUrl,g.oneofs&&(c._signedUrl="signedUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ProductMessage.ProductSnapshot"},a})(),i})(),r.ProtocolMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.type=A.int32();break}case 4:{c.ephemeralExpiration=A.uint32();break}case 5:{c.ephemeralSettingTimestamp=A.int64();break}case 6:{c.historySyncNotification=E.proto.Message.HistorySyncNotification.decode(A,A.uint32());break}case 7:{c.appStateSyncKeyShare=E.proto.Message.AppStateSyncKeyShare.decode(A,A.uint32());break}case 8:{c.appStateSyncKeyRequest=E.proto.Message.AppStateSyncKeyRequest.decode(A,A.uint32());break}case 9:{c.initialSecurityNotificationSettingSync=E.proto.Message.InitialSecurityNotificationSettingSync.decode(A,A.uint32());break}case 10:{c.appStateFatalExceptionNotification=E.proto.Message.AppStateFatalExceptionNotification.decode(A,A.uint32());break}case 11:{c.disappearingMode=E.proto.DisappearingMode.decode(A,A.uint32());break}case 14:{c.editedMessage=E.proto.Message.decode(A,A.uint32());break}case 15:{c.timestampMs=A.int64();break}case 16:{c.peerDataOperationRequestMessage=E.proto.Message.PeerDataOperationRequestMessage.decode(A,A.uint32());break}case 17:{c.peerDataOperationRequestResponseMessage=E.proto.Message.PeerDataOperationRequestResponseMessage.decode(A,A.uint32());break}case 18:{c.botFeedbackMessage=E.proto.BotFeedbackMessage.decode(A,A.uint32());break}case 19:{c.invokerJid=A.string();break}case 20:{c.requestWelcomeMessageMetadata=E.proto.Message.RequestWelcomeMessageMetadata.decode(A,A.uint32());break}case 21:{c.mediaNotifyMessage=E.proto.MediaNotifyMessage.decode(A,A.uint32());break}case 22:{c.cloudApiThreadControlNotification=E.proto.Message.CloudAPIThreadControlNotification.decode(A,A.uint32());break}case 23:{c.lidMigrationMappingSyncMessage=E.proto.LIDMigrationMappingSyncMessage.decode(A,A.uint32());break}case 24:{c.limitSharing=E.proto.LimitSharing.decode(A,A.uint32());break}case 25:{c.aiPsiMetadata=A.bytes();break}case 26:{c.aiQueryFanout=E.proto.AIQueryFanout.decode(A,A.uint32());break}case 27:{c.memberLabel=E.proto.MemberLabel.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ProtocolMessage)return A;var t=new E.proto.Message.ProtocolMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ProtocolMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"REVOKE":case 0:t.type=0;break;case"EPHEMERAL_SETTING":case 3:t.type=3;break;case"EPHEMERAL_SYNC_RESPONSE":case 4:t.type=4;break;case"HISTORY_SYNC_NOTIFICATION":case 5:t.type=5;break;case"APP_STATE_SYNC_KEY_SHARE":case 6:t.type=6;break;case"APP_STATE_SYNC_KEY_REQUEST":case 7:t.type=7;break;case"MSG_FANOUT_BACKFILL_REQUEST":case 8:t.type=8;break;case"INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC":case 9:t.type=9;break;case"APP_STATE_FATAL_EXCEPTION_NOTIFICATION":case 10:t.type=10;break;case"SHARE_PHONE_NUMBER":case 11:t.type=11;break;case"MESSAGE_EDIT":case 14:t.type=14;break;case"PEER_DATA_OPERATION_REQUEST_MESSAGE":case 16:t.type=16;break;case"PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE":case 17:t.type=17;break;case"REQUEST_WELCOME_MESSAGE":case 18:t.type=18;break;case"BOT_FEEDBACK_MESSAGE":case 19:t.type=19;break;case"MEDIA_NOTIFY_MESSAGE":case 20:t.type=20;break;case"CLOUD_API_THREAD_CONTROL_NOTIFICATION":case 21:t.type=21;break;case"LID_MIGRATION_MAPPING_SYNC":case 22:t.type=22;break;case"REMINDER_MESSAGE":case 23:t.type=23;break;case"BOT_MEMU_ONBOARDING_MESSAGE":case 24:t.type=24;break;case"STATUS_MENTION_MESSAGE":case 25:t.type=25;break;case"STOP_GENERATION_MESSAGE":case 26:t.type=26;break;case"LIMIT_SHARING":case 27:t.type=27;break;case"AI_PSI_METADATA":case 28:t.type=28;break;case"AI_QUERY_FANOUT":case 29:t.type=29;break;case"GROUP_MEMBER_LABEL_CHANGE":case 30:t.type=30;break}if(A.ephemeralExpiration!=null&&(t.ephemeralExpiration=A.ephemeralExpiration>>>0),A.ephemeralSettingTimestamp!=null&&(I.Long?(t.ephemeralSettingTimestamp=I.Long.fromValue(A.ephemeralSettingTimestamp)).unsigned=!1:typeof A.ephemeralSettingTimestamp=="string"?t.ephemeralSettingTimestamp=parseInt(A.ephemeralSettingTimestamp,10):typeof A.ephemeralSettingTimestamp=="number"?t.ephemeralSettingTimestamp=A.ephemeralSettingTimestamp:typeof A.ephemeralSettingTimestamp=="object"&&(t.ephemeralSettingTimestamp=new I.LongBits(A.ephemeralSettingTimestamp.low>>>0,A.ephemeralSettingTimestamp.high>>>0).toNumber())),A.historySyncNotification!=null){if(typeof A.historySyncNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.historySyncNotification: object expected");t.historySyncNotification=E.proto.Message.HistorySyncNotification.fromObject(A.historySyncNotification)}if(A.appStateSyncKeyShare!=null){if(typeof A.appStateSyncKeyShare!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateSyncKeyShare: object expected");t.appStateSyncKeyShare=E.proto.Message.AppStateSyncKeyShare.fromObject(A.appStateSyncKeyShare)}if(A.appStateSyncKeyRequest!=null){if(typeof A.appStateSyncKeyRequest!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateSyncKeyRequest: object expected");t.appStateSyncKeyRequest=E.proto.Message.AppStateSyncKeyRequest.fromObject(A.appStateSyncKeyRequest)}if(A.initialSecurityNotificationSettingSync!=null){if(typeof A.initialSecurityNotificationSettingSync!="object")throw TypeError(".proto.Message.ProtocolMessage.initialSecurityNotificationSettingSync: object expected");t.initialSecurityNotificationSettingSync=E.proto.Message.InitialSecurityNotificationSettingSync.fromObject(A.initialSecurityNotificationSettingSync)}if(A.appStateFatalExceptionNotification!=null){if(typeof A.appStateFatalExceptionNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateFatalExceptionNotification: object expected");t.appStateFatalExceptionNotification=E.proto.Message.AppStateFatalExceptionNotification.fromObject(A.appStateFatalExceptionNotification)}if(A.disappearingMode!=null){if(typeof A.disappearingMode!="object")throw TypeError(".proto.Message.ProtocolMessage.disappearingMode: object expected");t.disappearingMode=E.proto.DisappearingMode.fromObject(A.disappearingMode)}if(A.editedMessage!=null){if(typeof A.editedMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.editedMessage: object expected");t.editedMessage=E.proto.Message.fromObject(A.editedMessage)}if(A.timestampMs!=null&&(I.Long?(t.timestampMs=I.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?t.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?t.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(t.timestampMs=new I.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),A.peerDataOperationRequestMessage!=null){if(typeof A.peerDataOperationRequestMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.peerDataOperationRequestMessage: object expected");t.peerDataOperationRequestMessage=E.proto.Message.PeerDataOperationRequestMessage.fromObject(A.peerDataOperationRequestMessage)}if(A.peerDataOperationRequestResponseMessage!=null){if(typeof A.peerDataOperationRequestResponseMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.peerDataOperationRequestResponseMessage: object expected");t.peerDataOperationRequestResponseMessage=E.proto.Message.PeerDataOperationRequestResponseMessage.fromObject(A.peerDataOperationRequestResponseMessage)}if(A.botFeedbackMessage!=null){if(typeof A.botFeedbackMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.botFeedbackMessage: object expected");t.botFeedbackMessage=E.proto.BotFeedbackMessage.fromObject(A.botFeedbackMessage)}if(A.invokerJid!=null&&(t.invokerJid=String(A.invokerJid)),A.requestWelcomeMessageMetadata!=null){if(typeof A.requestWelcomeMessageMetadata!="object")throw TypeError(".proto.Message.ProtocolMessage.requestWelcomeMessageMetadata: object expected");t.requestWelcomeMessageMetadata=E.proto.Message.RequestWelcomeMessageMetadata.fromObject(A.requestWelcomeMessageMetadata)}if(A.mediaNotifyMessage!=null){if(typeof A.mediaNotifyMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.mediaNotifyMessage: object expected");t.mediaNotifyMessage=E.proto.MediaNotifyMessage.fromObject(A.mediaNotifyMessage)}if(A.cloudApiThreadControlNotification!=null){if(typeof A.cloudApiThreadControlNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.cloudApiThreadControlNotification: object expected");t.cloudApiThreadControlNotification=E.proto.Message.CloudAPIThreadControlNotification.fromObject(A.cloudApiThreadControlNotification)}if(A.lidMigrationMappingSyncMessage!=null){if(typeof A.lidMigrationMappingSyncMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.lidMigrationMappingSyncMessage: object expected");t.lidMigrationMappingSyncMessage=E.proto.LIDMigrationMappingSyncMessage.fromObject(A.lidMigrationMappingSyncMessage)}if(A.limitSharing!=null){if(typeof A.limitSharing!="object")throw TypeError(".proto.Message.ProtocolMessage.limitSharing: object expected");t.limitSharing=E.proto.LimitSharing.fromObject(A.limitSharing)}if(A.aiPsiMetadata!=null&&(typeof A.aiPsiMetadata=="string"?I.base64.decode(A.aiPsiMetadata,t.aiPsiMetadata=I.newBuffer(I.base64.length(A.aiPsiMetadata)),0):A.aiPsiMetadata.length>=0&&(t.aiPsiMetadata=A.aiPsiMetadata)),A.aiQueryFanout!=null){if(typeof A.aiQueryFanout!="object")throw TypeError(".proto.Message.ProtocolMessage.aiQueryFanout: object expected");t.aiQueryFanout=E.proto.AIQueryFanout.fromObject(A.aiQueryFanout)}if(A.memberLabel!=null){if(typeof A.memberLabel!="object")throw TypeError(".proto.Message.ProtocolMessage.memberLabel: object expected");t.memberLabel=E.proto.MemberLabel.fromObject(A.memberLabel)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.Message.ProtocolMessage.Type[A.type]===void 0?A.type:E.proto.Message.ProtocolMessage.Type[A.type]:A.type,t.oneofs&&(s._type="type")),A.ephemeralExpiration!=null&&A.hasOwnProperty("ephemeralExpiration")&&(s.ephemeralExpiration=A.ephemeralExpiration,t.oneofs&&(s._ephemeralExpiration="ephemeralExpiration")),A.ephemeralSettingTimestamp!=null&&A.hasOwnProperty("ephemeralSettingTimestamp")&&(typeof A.ephemeralSettingTimestamp=="number"?s.ephemeralSettingTimestamp=t.longs===String?String(A.ephemeralSettingTimestamp):A.ephemeralSettingTimestamp:s.ephemeralSettingTimestamp=t.longs===String?re(A.ephemeralSettingTimestamp):t.longs===Number?ae(A.ephemeralSettingTimestamp):A.ephemeralSettingTimestamp,t.oneofs&&(s._ephemeralSettingTimestamp="ephemeralSettingTimestamp")),A.historySyncNotification!=null&&A.hasOwnProperty("historySyncNotification")&&(s.historySyncNotification=E.proto.Message.HistorySyncNotification.toObject(A.historySyncNotification,t),t.oneofs&&(s._historySyncNotification="historySyncNotification")),A.appStateSyncKeyShare!=null&&A.hasOwnProperty("appStateSyncKeyShare")&&(s.appStateSyncKeyShare=E.proto.Message.AppStateSyncKeyShare.toObject(A.appStateSyncKeyShare,t),t.oneofs&&(s._appStateSyncKeyShare="appStateSyncKeyShare")),A.appStateSyncKeyRequest!=null&&A.hasOwnProperty("appStateSyncKeyRequest")&&(s.appStateSyncKeyRequest=E.proto.Message.AppStateSyncKeyRequest.toObject(A.appStateSyncKeyRequest,t),t.oneofs&&(s._appStateSyncKeyRequest="appStateSyncKeyRequest")),A.initialSecurityNotificationSettingSync!=null&&A.hasOwnProperty("initialSecurityNotificationSettingSync")&&(s.initialSecurityNotificationSettingSync=E.proto.Message.InitialSecurityNotificationSettingSync.toObject(A.initialSecurityNotificationSettingSync,t),t.oneofs&&(s._initialSecurityNotificationSettingSync="initialSecurityNotificationSettingSync")),A.appStateFatalExceptionNotification!=null&&A.hasOwnProperty("appStateFatalExceptionNotification")&&(s.appStateFatalExceptionNotification=E.proto.Message.AppStateFatalExceptionNotification.toObject(A.appStateFatalExceptionNotification,t),t.oneofs&&(s._appStateFatalExceptionNotification="appStateFatalExceptionNotification")),A.disappearingMode!=null&&A.hasOwnProperty("disappearingMode")&&(s.disappearingMode=E.proto.DisappearingMode.toObject(A.disappearingMode,t),t.oneofs&&(s._disappearingMode="disappearingMode")),A.editedMessage!=null&&A.hasOwnProperty("editedMessage")&&(s.editedMessage=E.proto.Message.toObject(A.editedMessage,t),t.oneofs&&(s._editedMessage="editedMessage")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=t.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=t.longs===String?re(A.timestampMs):t.longs===Number?ae(A.timestampMs):A.timestampMs,t.oneofs&&(s._timestampMs="timestampMs")),A.peerDataOperationRequestMessage!=null&&A.hasOwnProperty("peerDataOperationRequestMessage")&&(s.peerDataOperationRequestMessage=E.proto.Message.PeerDataOperationRequestMessage.toObject(A.peerDataOperationRequestMessage,t),t.oneofs&&(s._peerDataOperationRequestMessage="peerDataOperationRequestMessage")),A.peerDataOperationRequestResponseMessage!=null&&A.hasOwnProperty("peerDataOperationRequestResponseMessage")&&(s.peerDataOperationRequestResponseMessage=E.proto.Message.PeerDataOperationRequestResponseMessage.toObject(A.peerDataOperationRequestResponseMessage,t),t.oneofs&&(s._peerDataOperationRequestResponseMessage="peerDataOperationRequestResponseMessage")),A.botFeedbackMessage!=null&&A.hasOwnProperty("botFeedbackMessage")&&(s.botFeedbackMessage=E.proto.BotFeedbackMessage.toObject(A.botFeedbackMessage,t),t.oneofs&&(s._botFeedbackMessage="botFeedbackMessage")),A.invokerJid!=null&&A.hasOwnProperty("invokerJid")&&(s.invokerJid=A.invokerJid,t.oneofs&&(s._invokerJid="invokerJid")),A.requestWelcomeMessageMetadata!=null&&A.hasOwnProperty("requestWelcomeMessageMetadata")&&(s.requestWelcomeMessageMetadata=E.proto.Message.RequestWelcomeMessageMetadata.toObject(A.requestWelcomeMessageMetadata,t),t.oneofs&&(s._requestWelcomeMessageMetadata="requestWelcomeMessageMetadata")),A.mediaNotifyMessage!=null&&A.hasOwnProperty("mediaNotifyMessage")&&(s.mediaNotifyMessage=E.proto.MediaNotifyMessage.toObject(A.mediaNotifyMessage,t),t.oneofs&&(s._mediaNotifyMessage="mediaNotifyMessage")),A.cloudApiThreadControlNotification!=null&&A.hasOwnProperty("cloudApiThreadControlNotification")&&(s.cloudApiThreadControlNotification=E.proto.Message.CloudAPIThreadControlNotification.toObject(A.cloudApiThreadControlNotification,t),t.oneofs&&(s._cloudApiThreadControlNotification="cloudApiThreadControlNotification")),A.lidMigrationMappingSyncMessage!=null&&A.hasOwnProperty("lidMigrationMappingSyncMessage")&&(s.lidMigrationMappingSyncMessage=E.proto.LIDMigrationMappingSyncMessage.toObject(A.lidMigrationMappingSyncMessage,t),t.oneofs&&(s._lidMigrationMappingSyncMessage="lidMigrationMappingSyncMessage")),A.limitSharing!=null&&A.hasOwnProperty("limitSharing")&&(s.limitSharing=E.proto.LimitSharing.toObject(A.limitSharing,t),t.oneofs&&(s._limitSharing="limitSharing")),A.aiPsiMetadata!=null&&A.hasOwnProperty("aiPsiMetadata")&&(s.aiPsiMetadata=t.bytes===String?I.base64.encode(A.aiPsiMetadata,0,A.aiPsiMetadata.length):t.bytes===Array?Array.prototype.slice.call(A.aiPsiMetadata):A.aiPsiMetadata,t.oneofs&&(s._aiPsiMetadata="aiPsiMetadata")),A.aiQueryFanout!=null&&A.hasOwnProperty("aiQueryFanout")&&(s.aiQueryFanout=E.proto.AIQueryFanout.toObject(A.aiQueryFanout,t),t.oneofs&&(s._aiQueryFanout="aiQueryFanout")),A.memberLabel!=null&&A.hasOwnProperty("memberLabel")&&(s.memberLabel=E.proto.MemberLabel.toObject(A.memberLabel,t),t.oneofs&&(s._memberLabel="memberLabel")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ProtocolMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="REVOKE"]=0,A[a[3]="EPHEMERAL_SETTING"]=3,A[a[4]="EPHEMERAL_SYNC_RESPONSE"]=4,A[a[5]="HISTORY_SYNC_NOTIFICATION"]=5,A[a[6]="APP_STATE_SYNC_KEY_SHARE"]=6,A[a[7]="APP_STATE_SYNC_KEY_REQUEST"]=7,A[a[8]="MSG_FANOUT_BACKFILL_REQUEST"]=8,A[a[9]="INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC"]=9,A[a[10]="APP_STATE_FATAL_EXCEPTION_NOTIFICATION"]=10,A[a[11]="SHARE_PHONE_NUMBER"]=11,A[a[14]="MESSAGE_EDIT"]=14,A[a[16]="PEER_DATA_OPERATION_REQUEST_MESSAGE"]=16,A[a[17]="PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]=17,A[a[18]="REQUEST_WELCOME_MESSAGE"]=18,A[a[19]="BOT_FEEDBACK_MESSAGE"]=19,A[a[20]="MEDIA_NOTIFY_MESSAGE"]=20,A[a[21]="CLOUD_API_THREAD_CONTROL_NOTIFICATION"]=21,A[a[22]="LID_MIGRATION_MAPPING_SYNC"]=22,A[a[23]="REMINDER_MESSAGE"]=23,A[a[24]="BOT_MEMU_ONBOARDING_MESSAGE"]=24,A[a[25]="STATUS_MENTION_MESSAGE"]=25,A[a[26]="STOP_GENERATION_MESSAGE"]=26,A[a[27]="LIMIT_SHARING"]=27,A[a[28]="AI_PSI_METADATA"]=28,A[a[29]="AI_QUERY_FANOUT"]=29,A[a[30]="GROUP_MEMBER_LABEL_CHANGE"]=30,A})(),i})(),r.QuestionResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.QuestionResponseMessage)return A;var t=new E.proto.Message.QuestionResponseMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.QuestionResponseMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(t.text=String(A.text)),t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,t.oneofs&&(s._text="text")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.QuestionResponseMessage"},i})(),r.ReactionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}case 3:{c.groupingKey=A.string();break}case 4:{c.senderTimestampMs=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ReactionMessage)return A;var t=new E.proto.Message.ReactionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ReactionMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(t.text=String(A.text)),A.groupingKey!=null&&(t.groupingKey=String(A.groupingKey)),A.senderTimestampMs!=null&&(I.Long?(t.senderTimestampMs=I.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?t.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?t.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(t.senderTimestampMs=new I.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,t.oneofs&&(s._text="text")),A.groupingKey!=null&&A.hasOwnProperty("groupingKey")&&(s.groupingKey=A.groupingKey,t.oneofs&&(s._groupingKey="groupingKey")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=t.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=t.longs===String?re(A.senderTimestampMs):t.longs===Number?ae(A.senderTimestampMs):A.senderTimestampMs,t.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ReactionMessage"},i})(),r.RequestPaymentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 4:{c.noteMessage=E.proto.Message.decode(A,A.uint32());break}case 1:{c.currencyCodeIso4217=A.string();break}case 2:{c.amount1000=A.uint64();break}case 3:{c.requestFrom=A.string();break}case 5:{c.expiryTimestamp=A.int64();break}case 6:{c.amount=E.proto.Money.decode(A,A.uint32());break}case 7:{c.background=E.proto.PaymentBackground.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.RequestPaymentMessage)return A;var t=new E.proto.Message.RequestPaymentMessage;if(A.noteMessage!=null){if(typeof A.noteMessage!="object")throw TypeError(".proto.Message.RequestPaymentMessage.noteMessage: object expected");t.noteMessage=E.proto.Message.fromObject(A.noteMessage)}if(A.currencyCodeIso4217!=null&&(t.currencyCodeIso4217=String(A.currencyCodeIso4217)),A.amount1000!=null&&(I.Long?(t.amount1000=I.Long.fromValue(A.amount1000)).unsigned=!0:typeof A.amount1000=="string"?t.amount1000=parseInt(A.amount1000,10):typeof A.amount1000=="number"?t.amount1000=A.amount1000:typeof A.amount1000=="object"&&(t.amount1000=new I.LongBits(A.amount1000.low>>>0,A.amount1000.high>>>0).toNumber(!0))),A.requestFrom!=null&&(t.requestFrom=String(A.requestFrom)),A.expiryTimestamp!=null&&(I.Long?(t.expiryTimestamp=I.Long.fromValue(A.expiryTimestamp)).unsigned=!1:typeof A.expiryTimestamp=="string"?t.expiryTimestamp=parseInt(A.expiryTimestamp,10):typeof A.expiryTimestamp=="number"?t.expiryTimestamp=A.expiryTimestamp:typeof A.expiryTimestamp=="object"&&(t.expiryTimestamp=new I.LongBits(A.expiryTimestamp.low>>>0,A.expiryTimestamp.high>>>0).toNumber())),A.amount!=null){if(typeof A.amount!="object")throw TypeError(".proto.Message.RequestPaymentMessage.amount: object expected");t.amount=E.proto.Money.fromObject(A.amount)}if(A.background!=null){if(typeof A.background!="object")throw TypeError(".proto.Message.RequestPaymentMessage.background: object expected");t.background=E.proto.PaymentBackground.fromObject(A.background)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.currencyCodeIso4217!=null&&A.hasOwnProperty("currencyCodeIso4217")&&(s.currencyCodeIso4217=A.currencyCodeIso4217,t.oneofs&&(s._currencyCodeIso4217="currencyCodeIso4217")),A.amount1000!=null&&A.hasOwnProperty("amount1000")&&(typeof A.amount1000=="number"?s.amount1000=t.longs===String?String(A.amount1000):A.amount1000:s.amount1000=t.longs===String?re(A.amount1000,!0):t.longs===Number?ae(A.amount1000,!0):A.amount1000,t.oneofs&&(s._amount1000="amount1000")),A.requestFrom!=null&&A.hasOwnProperty("requestFrom")&&(s.requestFrom=A.requestFrom,t.oneofs&&(s._requestFrom="requestFrom")),A.noteMessage!=null&&A.hasOwnProperty("noteMessage")&&(s.noteMessage=E.proto.Message.toObject(A.noteMessage,t),t.oneofs&&(s._noteMessage="noteMessage")),A.expiryTimestamp!=null&&A.hasOwnProperty("expiryTimestamp")&&(typeof A.expiryTimestamp=="number"?s.expiryTimestamp=t.longs===String?String(A.expiryTimestamp):A.expiryTimestamp:s.expiryTimestamp=t.longs===String?re(A.expiryTimestamp):t.longs===Number?ae(A.expiryTimestamp):A.expiryTimestamp,t.oneofs&&(s._expiryTimestamp="expiryTimestamp")),A.amount!=null&&A.hasOwnProperty("amount")&&(s.amount=E.proto.Money.toObject(A.amount,t),t.oneofs&&(s._amount="amount")),A.background!=null&&A.hasOwnProperty("background")&&(s.background=E.proto.PaymentBackground.toObject(A.background,t),t.oneofs&&(s._background="background")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestPaymentMessage"},i})(),r.RequestPhoneNumberMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.RequestPhoneNumberMessage)return A;var t=new E.proto.Message.RequestPhoneNumberMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.RequestPhoneNumberMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestPhoneNumberMessage"},i})(),r.RequestWelcomeMessageMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.localChatState=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.RequestWelcomeMessageMetadata)return A;var t=new E.proto.Message.RequestWelcomeMessageMetadata;switch(A.localChatState){default:if(typeof A.localChatState=="number"){t.localChatState=A.localChatState;break}break;case"EMPTY":case 0:t.localChatState=0;break;case"NON_EMPTY":case 1:t.localChatState=1;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.localChatState!=null&&A.hasOwnProperty("localChatState")&&(s.localChatState=t.enums===String?E.proto.Message.RequestWelcomeMessageMetadata.LocalChatState[A.localChatState]===void 0?A.localChatState:E.proto.Message.RequestWelcomeMessageMetadata.LocalChatState[A.localChatState]:A.localChatState,t.oneofs&&(s._localChatState="localChatState")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestWelcomeMessageMetadata"},i.LocalChatState=(function(){let a={},A=Object.create(a);return A[a[0]="EMPTY"]=0,A[a[1]="NON_EMPTY"]=1,A})(),i})(),r.ScheduledCallCreationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.scheduledTimestampMs=A.int64();break}case 2:{c.callType=A.int32();break}case 3:{c.title=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ScheduledCallCreationMessage)return A;var t=new E.proto.Message.ScheduledCallCreationMessage;switch(A.scheduledTimestampMs!=null&&(I.Long?(t.scheduledTimestampMs=I.Long.fromValue(A.scheduledTimestampMs)).unsigned=!1:typeof A.scheduledTimestampMs=="string"?t.scheduledTimestampMs=parseInt(A.scheduledTimestampMs,10):typeof A.scheduledTimestampMs=="number"?t.scheduledTimestampMs=A.scheduledTimestampMs:typeof A.scheduledTimestampMs=="object"&&(t.scheduledTimestampMs=new I.LongBits(A.scheduledTimestampMs.low>>>0,A.scheduledTimestampMs.high>>>0).toNumber())),A.callType){default:if(typeof A.callType=="number"){t.callType=A.callType;break}break;case"UNKNOWN":case 0:t.callType=0;break;case"VOICE":case 1:t.callType=1;break;case"VIDEO":case 2:t.callType=2;break}return A.title!=null&&(t.title=String(A.title)),t},i.toObject=function(A,t){t||(t={});var s={};return A.scheduledTimestampMs!=null&&A.hasOwnProperty("scheduledTimestampMs")&&(typeof A.scheduledTimestampMs=="number"?s.scheduledTimestampMs=t.longs===String?String(A.scheduledTimestampMs):A.scheduledTimestampMs:s.scheduledTimestampMs=t.longs===String?re(A.scheduledTimestampMs):t.longs===Number?ae(A.scheduledTimestampMs):A.scheduledTimestampMs,t.oneofs&&(s._scheduledTimestampMs="scheduledTimestampMs")),A.callType!=null&&A.hasOwnProperty("callType")&&(s.callType=t.enums===String?E.proto.Message.ScheduledCallCreationMessage.CallType[A.callType]===void 0?A.callType:E.proto.Message.ScheduledCallCreationMessage.CallType[A.callType]:A.callType,t.oneofs&&(s._callType="callType")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ScheduledCallCreationMessage"},i.CallType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="VOICE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),r.ScheduledCallEditMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.editType=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.ScheduledCallEditMessage)return A;var t=new E.proto.Message.ScheduledCallEditMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ScheduledCallEditMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}switch(A.editType){default:if(typeof A.editType=="number"){t.editType=A.editType;break}break;case"UNKNOWN":case 0:t.editType=0;break;case"CANCEL":case 1:t.editType=1;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.editType!=null&&A.hasOwnProperty("editType")&&(s.editType=t.enums===String?E.proto.Message.ScheduledCallEditMessage.EditType[A.editType]===void 0?A.editType:E.proto.Message.ScheduledCallEditMessage.EditType[A.editType]:A.editType,t.oneofs&&(s._editType="editType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ScheduledCallEditMessage"},i.EditType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CANCEL"]=1,A})(),i})(),r.SecretEncryptedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.targetMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}case 4:{c.secretEncType=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.SecretEncryptedMessage)return A;var t=new E.proto.Message.SecretEncryptedMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.SecretEncryptedMessage.targetMessageKey: object expected");t.targetMessageKey=E.proto.MessageKey.fromObject(A.targetMessageKey)}switch(A.encPayload!=null&&(typeof A.encPayload=="string"?I.base64.decode(A.encPayload,t.encPayload=I.newBuffer(I.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(t.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?I.base64.decode(A.encIv,t.encIv=I.newBuffer(I.base64.length(A.encIv)),0):A.encIv.length>=0&&(t.encIv=A.encIv)),A.secretEncType){default:if(typeof A.secretEncType=="number"){t.secretEncType=A.secretEncType;break}break;case"UNKNOWN":case 0:t.secretEncType=0;break;case"EVENT_EDIT":case 1:t.secretEncType=1;break;case"MESSAGE_EDIT":case 2:t.secretEncType=2;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=E.proto.MessageKey.toObject(A.targetMessageKey,t),t.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=t.bytes===String?I.base64.encode(A.encPayload,0,A.encPayload.length):t.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,t.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=t.bytes===String?I.base64.encode(A.encIv,0,A.encIv.length):t.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,t.oneofs&&(s._encIv="encIv")),A.secretEncType!=null&&A.hasOwnProperty("secretEncType")&&(s.secretEncType=t.enums===String?E.proto.Message.SecretEncryptedMessage.SecretEncType[A.secretEncType]===void 0?A.secretEncType:E.proto.Message.SecretEncryptedMessage.SecretEncType[A.secretEncType]:A.secretEncType,t.oneofs&&(s._secretEncType="secretEncType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SecretEncryptedMessage"},i.SecretEncType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="EVENT_EDIT"]=1,A[a[2]="MESSAGE_EDIT"]=2,A})(),i})(),r.SendPaymentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 2:{c.noteMessage=E.proto.Message.decode(A,A.uint32());break}case 3:{c.requestMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 4:{c.background=E.proto.PaymentBackground.decode(A,A.uint32());break}case 5:{c.transactionData=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.SendPaymentMessage)return A;var t=new E.proto.Message.SendPaymentMessage;if(A.noteMessage!=null){if(typeof A.noteMessage!="object")throw TypeError(".proto.Message.SendPaymentMessage.noteMessage: object expected");t.noteMessage=E.proto.Message.fromObject(A.noteMessage)}if(A.requestMessageKey!=null){if(typeof A.requestMessageKey!="object")throw TypeError(".proto.Message.SendPaymentMessage.requestMessageKey: object expected");t.requestMessageKey=E.proto.MessageKey.fromObject(A.requestMessageKey)}if(A.background!=null){if(typeof A.background!="object")throw TypeError(".proto.Message.SendPaymentMessage.background: object expected");t.background=E.proto.PaymentBackground.fromObject(A.background)}return A.transactionData!=null&&(t.transactionData=String(A.transactionData)),t},i.toObject=function(A,t){t||(t={});var s={};return A.noteMessage!=null&&A.hasOwnProperty("noteMessage")&&(s.noteMessage=E.proto.Message.toObject(A.noteMessage,t),t.oneofs&&(s._noteMessage="noteMessage")),A.requestMessageKey!=null&&A.hasOwnProperty("requestMessageKey")&&(s.requestMessageKey=E.proto.MessageKey.toObject(A.requestMessageKey,t),t.oneofs&&(s._requestMessageKey="requestMessageKey")),A.background!=null&&A.hasOwnProperty("background")&&(s.background=E.proto.PaymentBackground.toObject(A.background,t),t.oneofs&&(s._background="background")),A.transactionData!=null&&A.hasOwnProperty("transactionData")&&(s.transactionData=A.transactionData,t.oneofs&&(s._transactionData="transactionData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SendPaymentMessage"},i})(),r.SenderKeyDistributionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.groupId=A.string();break}case 2:{c.axolotlSenderKeyDistributionMessage=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.SenderKeyDistributionMessage)return A;var t=new E.proto.Message.SenderKeyDistributionMessage;return A.groupId!=null&&(t.groupId=String(A.groupId)),A.axolotlSenderKeyDistributionMessage!=null&&(typeof A.axolotlSenderKeyDistributionMessage=="string"?I.base64.decode(A.axolotlSenderKeyDistributionMessage,t.axolotlSenderKeyDistributionMessage=I.newBuffer(I.base64.length(A.axolotlSenderKeyDistributionMessage)),0):A.axolotlSenderKeyDistributionMessage.length>=0&&(t.axolotlSenderKeyDistributionMessage=A.axolotlSenderKeyDistributionMessage)),t},i.toObject=function(A,t){t||(t={});var s={};return A.groupId!=null&&A.hasOwnProperty("groupId")&&(s.groupId=A.groupId,t.oneofs&&(s._groupId="groupId")),A.axolotlSenderKeyDistributionMessage!=null&&A.hasOwnProperty("axolotlSenderKeyDistributionMessage")&&(s.axolotlSenderKeyDistributionMessage=t.bytes===String?I.base64.encode(A.axolotlSenderKeyDistributionMessage,0,A.axolotlSenderKeyDistributionMessage.length):t.bytes===Array?Array.prototype.slice.call(A.axolotlSenderKeyDistributionMessage):A.axolotlSenderKeyDistributionMessage,t.oneofs&&(s._axolotlSenderKeyDistributionMessage="axolotlSenderKeyDistributionMessage")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SenderKeyDistributionMessage"},i})(),r.StatusNotificationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.responseMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.originalMessageKey=E.proto.MessageKey.decode(A,A.uint32());break}case 3:{c.type=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.StatusNotificationMessage)return A;var t=new E.proto.Message.StatusNotificationMessage;if(A.responseMessageKey!=null){if(typeof A.responseMessageKey!="object")throw TypeError(".proto.Message.StatusNotificationMessage.responseMessageKey: object expected");t.responseMessageKey=E.proto.MessageKey.fromObject(A.responseMessageKey)}if(A.originalMessageKey!=null){if(typeof A.originalMessageKey!="object")throw TypeError(".proto.Message.StatusNotificationMessage.originalMessageKey: object expected");t.originalMessageKey=E.proto.MessageKey.fromObject(A.originalMessageKey)}switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"UNKNOWN":case 0:t.type=0;break;case"STATUS_ADD_YOURS":case 1:t.type=1;break;case"STATUS_RESHARE":case 2:t.type=2;break;case"STATUS_QUESTION_ANSWER_RESHARE":case 3:t.type=3;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.responseMessageKey!=null&&A.hasOwnProperty("responseMessageKey")&&(s.responseMessageKey=E.proto.MessageKey.toObject(A.responseMessageKey,t),t.oneofs&&(s._responseMessageKey="responseMessageKey")),A.originalMessageKey!=null&&A.hasOwnProperty("originalMessageKey")&&(s.originalMessageKey=E.proto.MessageKey.toObject(A.originalMessageKey,t),t.oneofs&&(s._originalMessageKey="originalMessageKey")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.Message.StatusNotificationMessage.StatusNotificationType[A.type]===void 0?A.type:E.proto.Message.StatusNotificationMessage.StatusNotificationType[A.type]:A.type,t.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusNotificationMessage"},i.StatusNotificationType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="STATUS_ADD_YOURS"]=1,A[a[2]="STATUS_RESHARE"]=2,A[a[3]="STATUS_QUESTION_ANSWER_RESHARE"]=3,A})(),i})(),r.StatusQuestionAnswerMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.StatusQuestionAnswerMessage)return A;var t=new E.proto.Message.StatusQuestionAnswerMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.StatusQuestionAnswerMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(t.text=String(A.text)),t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,t.oneofs&&(s._text="text")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusQuestionAnswerMessage"},i})(),r.StatusQuotedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.type=A.int32();break}case 2:{c.text=A.string();break}case 3:{c.thumbnail=A.bytes();break}case 4:{c.originalStatusId=E.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.StatusQuotedMessage)return A;var t=new E.proto.Message.StatusQuotedMessage;switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"QUESTION_ANSWER":case 1:t.type=1;break}if(A.text!=null&&(t.text=String(A.text)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?I.base64.decode(A.thumbnail,t.thumbnail=I.newBuffer(I.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(t.thumbnail=A.thumbnail)),A.originalStatusId!=null){if(typeof A.originalStatusId!="object")throw TypeError(".proto.Message.StatusQuotedMessage.originalStatusId: object expected");t.originalStatusId=E.proto.MessageKey.fromObject(A.originalStatusId)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.Message.StatusQuotedMessage.StatusQuotedMessageType[A.type]===void 0?A.type:E.proto.Message.StatusQuotedMessage.StatusQuotedMessageType[A.type]:A.type,t.oneofs&&(s._type="type")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,t.oneofs&&(s._text="text")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=t.bytes===String?I.base64.encode(A.thumbnail,0,A.thumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,t.oneofs&&(s._thumbnail="thumbnail")),A.originalStatusId!=null&&A.hasOwnProperty("originalStatusId")&&(s.originalStatusId=E.proto.MessageKey.toObject(A.originalStatusId,t),t.oneofs&&(s._originalStatusId="originalStatusId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusQuotedMessage"},i.StatusQuotedMessageType=(function(){let a={},A=Object.create(a);return A[a[1]="QUESTION_ANSWER"]=1,A})(),i})(),r.StatusStickerInteractionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.stickerKey=A.string();break}case 3:{c.type=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.StatusStickerInteractionMessage)return A;var t=new E.proto.Message.StatusStickerInteractionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.StatusStickerInteractionMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}switch(A.stickerKey!=null&&(t.stickerKey=String(A.stickerKey)),A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"UNKNOWN":case 0:t.type=0;break;case"REACTION":case 1:t.type=1;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.stickerKey!=null&&A.hasOwnProperty("stickerKey")&&(s.stickerKey=A.stickerKey,t.oneofs&&(s._stickerKey="stickerKey")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.Message.StatusStickerInteractionMessage.StatusStickerType[A.type]===void 0?A.type:E.proto.Message.StatusStickerInteractionMessage.StatusStickerType[A.type]:A.type,t.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusStickerInteractionMessage"},i.StatusStickerType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="REACTION"]=1,A})(),i})(),r.StickerMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.url=A.string();break}case 2:{c.fileSha256=A.bytes();break}case 3:{c.fileEncSha256=A.bytes();break}case 4:{c.mediaKey=A.bytes();break}case 5:{c.mimetype=A.string();break}case 6:{c.height=A.uint32();break}case 7:{c.width=A.uint32();break}case 8:{c.directPath=A.string();break}case 9:{c.fileLength=A.uint64();break}case 10:{c.mediaKeyTimestamp=A.int64();break}case 11:{c.firstFrameLength=A.uint32();break}case 12:{c.firstFrameSidecar=A.bytes();break}case 13:{c.isAnimated=A.bool();break}case 16:{c.pngThumbnail=A.bytes();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.stickerSentTs=A.int64();break}case 19:{c.isAvatar=A.bool();break}case 20:{c.isAiSticker=A.bool();break}case 21:{c.isLottie=A.bool();break}case 22:{c.accessibilityLabel=A.string();break}case 23:{c.mediaKeyDomain=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.StickerMessage)return A;var t=new E.proto.Message.StickerMessage;if(A.url!=null&&(t.url=String(A.url)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.mimetype!=null&&(t.mimetype=String(A.mimetype)),A.height!=null&&(t.height=A.height>>>0),A.width!=null&&(t.width=A.width>>>0),A.directPath!=null&&(t.directPath=String(A.directPath)),A.fileLength!=null&&(I.Long?(t.fileLength=I.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?t.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?t.fileLength=A.fileLength:typeof A.fileLength=="object"&&(t.fileLength=new I.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.firstFrameLength!=null&&(t.firstFrameLength=A.firstFrameLength>>>0),A.firstFrameSidecar!=null&&(typeof A.firstFrameSidecar=="string"?I.base64.decode(A.firstFrameSidecar,t.firstFrameSidecar=I.newBuffer(I.base64.length(A.firstFrameSidecar)),0):A.firstFrameSidecar.length>=0&&(t.firstFrameSidecar=A.firstFrameSidecar)),A.isAnimated!=null&&(t.isAnimated=!!A.isAnimated),A.pngThumbnail!=null&&(typeof A.pngThumbnail=="string"?I.base64.decode(A.pngThumbnail,t.pngThumbnail=I.newBuffer(I.base64.length(A.pngThumbnail)),0):A.pngThumbnail.length>=0&&(t.pngThumbnail=A.pngThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.StickerMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.stickerSentTs!=null&&(I.Long?(t.stickerSentTs=I.Long.fromValue(A.stickerSentTs)).unsigned=!1:typeof A.stickerSentTs=="string"?t.stickerSentTs=parseInt(A.stickerSentTs,10):typeof A.stickerSentTs=="number"?t.stickerSentTs=A.stickerSentTs:typeof A.stickerSentTs=="object"&&(t.stickerSentTs=new I.LongBits(A.stickerSentTs.low>>>0,A.stickerSentTs.high>>>0).toNumber())),A.isAvatar!=null&&(t.isAvatar=!!A.isAvatar),A.isAiSticker!=null&&(t.isAiSticker=!!A.isAiSticker),A.isLottie!=null&&(t.isLottie=!!A.isLottie),A.accessibilityLabel!=null&&(t.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){t.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:t.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:t.mediaKeyDomain=1;break;case"STATUS":case 2:t.mediaKeyDomain=2;break;case"CAPI":case 3:t.mediaKeyDomain=3;break;case"BOT":case 4:t.mediaKeyDomain=4;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=t.bytes===String?I.base64.encode(A.fileSha256,0,A.fileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,t.oneofs&&(s._fileSha256="fileSha256")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,t.oneofs&&(s._mimetype="mimetype")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,t.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,t.oneofs&&(s._width="width")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,t.oneofs&&(s._directPath="directPath")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=t.longs===String?String(A.fileLength):A.fileLength:s.fileLength=t.longs===String?re(A.fileLength,!0):t.longs===Number?ae(A.fileLength,!0):A.fileLength,t.oneofs&&(s._fileLength="fileLength")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=t.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=t.longs===String?re(A.mediaKeyTimestamp):t.longs===Number?ae(A.mediaKeyTimestamp):A.mediaKeyTimestamp,t.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.firstFrameLength!=null&&A.hasOwnProperty("firstFrameLength")&&(s.firstFrameLength=A.firstFrameLength,t.oneofs&&(s._firstFrameLength="firstFrameLength")),A.firstFrameSidecar!=null&&A.hasOwnProperty("firstFrameSidecar")&&(s.firstFrameSidecar=t.bytes===String?I.base64.encode(A.firstFrameSidecar,0,A.firstFrameSidecar.length):t.bytes===Array?Array.prototype.slice.call(A.firstFrameSidecar):A.firstFrameSidecar,t.oneofs&&(s._firstFrameSidecar="firstFrameSidecar")),A.isAnimated!=null&&A.hasOwnProperty("isAnimated")&&(s.isAnimated=A.isAnimated,t.oneofs&&(s._isAnimated="isAnimated")),A.pngThumbnail!=null&&A.hasOwnProperty("pngThumbnail")&&(s.pngThumbnail=t.bytes===String?I.base64.encode(A.pngThumbnail,0,A.pngThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.pngThumbnail):A.pngThumbnail,t.oneofs&&(s._pngThumbnail="pngThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.stickerSentTs!=null&&A.hasOwnProperty("stickerSentTs")&&(typeof A.stickerSentTs=="number"?s.stickerSentTs=t.longs===String?String(A.stickerSentTs):A.stickerSentTs:s.stickerSentTs=t.longs===String?re(A.stickerSentTs):t.longs===Number?ae(A.stickerSentTs):A.stickerSentTs,t.oneofs&&(s._stickerSentTs="stickerSentTs")),A.isAvatar!=null&&A.hasOwnProperty("isAvatar")&&(s.isAvatar=A.isAvatar,t.oneofs&&(s._isAvatar="isAvatar")),A.isAiSticker!=null&&A.hasOwnProperty("isAiSticker")&&(s.isAiSticker=A.isAiSticker,t.oneofs&&(s._isAiSticker="isAiSticker")),A.isLottie!=null&&A.hasOwnProperty("isLottie")&&(s.isLottie=A.isLottie,t.oneofs&&(s._isLottie="isLottie")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,t.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=t.enums===String?E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:E.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,t.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StickerMessage"},i})(),r.StickerPackMessage=(function(){function i(a){if(this.stickers=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.stickerPackId=A.string();break}case 2:{c.name=A.string();break}case 3:{c.publisher=A.string();break}case 4:{c.stickers&&c.stickers.length||(c.stickers=[]),c.stickers.push(E.proto.Message.StickerPackMessage.Sticker.decode(A,A.uint32()));break}case 5:{c.fileLength=A.uint64();break}case 6:{c.fileSha256=A.bytes();break}case 7:{c.fileEncSha256=A.bytes();break}case 8:{c.mediaKey=A.bytes();break}case 9:{c.directPath=A.string();break}case 10:{c.caption=A.string();break}case 11:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 12:{c.packDescription=A.string();break}case 13:{c.mediaKeyTimestamp=A.int64();break}case 14:{c.trayIconFileName=A.string();break}case 15:{c.thumbnailDirectPath=A.string();break}case 16:{c.thumbnailSha256=A.bytes();break}case 17:{c.thumbnailEncSha256=A.bytes();break}case 18:{c.thumbnailHeight=A.uint32();break}case 19:{c.thumbnailWidth=A.uint32();break}case 20:{c.imageDataHash=A.string();break}case 21:{c.stickerPackSize=A.uint64();break}case 22:{c.stickerPackOrigin=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.StickerPackMessage)return A;var t=new E.proto.Message.StickerPackMessage;if(A.stickerPackId!=null&&(t.stickerPackId=String(A.stickerPackId)),A.name!=null&&(t.name=String(A.name)),A.publisher!=null&&(t.publisher=String(A.publisher)),A.stickers){if(!Array.isArray(A.stickers))throw TypeError(".proto.Message.StickerPackMessage.stickers: array expected");t.stickers=[];for(var s=0;s>>0,A.fileLength.high>>>0).toNumber(!0))),A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.directPath!=null&&(t.directPath=String(A.directPath)),A.caption!=null&&(t.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.StickerPackMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.packDescription!=null&&(t.packDescription=String(A.packDescription)),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.trayIconFileName!=null&&(t.trayIconFileName=String(A.trayIconFileName)),A.thumbnailDirectPath!=null&&(t.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?I.base64.decode(A.thumbnailSha256,t.thumbnailSha256=I.newBuffer(I.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(t.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?I.base64.decode(A.thumbnailEncSha256,t.thumbnailEncSha256=I.newBuffer(I.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(t.thumbnailEncSha256=A.thumbnailEncSha256)),A.thumbnailHeight!=null&&(t.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(t.thumbnailWidth=A.thumbnailWidth>>>0),A.imageDataHash!=null&&(t.imageDataHash=String(A.imageDataHash)),A.stickerPackSize!=null&&(I.Long?(t.stickerPackSize=I.Long.fromValue(A.stickerPackSize)).unsigned=!0:typeof A.stickerPackSize=="string"?t.stickerPackSize=parseInt(A.stickerPackSize,10):typeof A.stickerPackSize=="number"?t.stickerPackSize=A.stickerPackSize:typeof A.stickerPackSize=="object"&&(t.stickerPackSize=new I.LongBits(A.stickerPackSize.low>>>0,A.stickerPackSize.high>>>0).toNumber(!0))),A.stickerPackOrigin){default:if(typeof A.stickerPackOrigin=="number"){t.stickerPackOrigin=A.stickerPackOrigin;break}break;case"FIRST_PARTY":case 0:t.stickerPackOrigin=0;break;case"THIRD_PARTY":case 1:t.stickerPackOrigin=1;break;case"USER_CREATED":case 2:t.stickerPackOrigin=2;break}return t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.stickers=[]),A.stickerPackId!=null&&A.hasOwnProperty("stickerPackId")&&(s.stickerPackId=A.stickerPackId,t.oneofs&&(s._stickerPackId="stickerPackId")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.publisher!=null&&A.hasOwnProperty("publisher")&&(s.publisher=A.publisher,t.oneofs&&(s._publisher="publisher")),A.stickers&&A.stickers.length){s.stickers=[];for(var g=0;g>>3){case 1:{p.fileName=s.string();break}case 2:{p.isAnimated=s.bool();break}case 3:{p.emojis&&p.emojis.length||(p.emojis=[]),p.emojis.push(s.string());break}case 4:{p.accessibilityLabel=s.string();break}case 5:{p.isLottie=s.bool();break}case 6:{p.mimetype=s.string();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.StickerPackMessage.Sticker)return s;var g=new E.proto.Message.StickerPackMessage.Sticker;if(s.fileName!=null&&(g.fileName=String(s.fileName)),s.isAnimated!=null&&(g.isAnimated=!!s.isAnimated),s.emojis){if(!Array.isArray(s.emojis))throw TypeError(".proto.Message.StickerPackMessage.Sticker.emojis: array expected");g.emojis=[];for(var c=0;c>>3){case 1:{c.filehash&&c.filehash.length||(c.filehash=[]),c.filehash.push(A.string());break}case 2:{c.rmrSource=A.string();break}case 3:{c.requestTimestamp=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.StickerSyncRMRMessage)return A;var t=new E.proto.Message.StickerSyncRMRMessage;if(A.filehash){if(!Array.isArray(A.filehash))throw TypeError(".proto.Message.StickerSyncRMRMessage.filehash: array expected");t.filehash=[];for(var s=0;s>>0,A.requestTimestamp.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.filehash=[]),A.filehash&&A.filehash.length){s.filehash=[];for(var g=0;g>>3){case 1:{c.selectedId=A.string();break}case 2:{c.selectedDisplayText=A.string();break}case 3:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.selectedIndex=A.uint32();break}case 5:{c.selectedCarouselCardIndex=A.uint32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.TemplateButtonReplyMessage)return A;var t=new E.proto.Message.TemplateButtonReplyMessage;if(A.selectedId!=null&&(t.selectedId=String(A.selectedId)),A.selectedDisplayText!=null&&(t.selectedDisplayText=String(A.selectedDisplayText)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.TemplateButtonReplyMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}return A.selectedIndex!=null&&(t.selectedIndex=A.selectedIndex>>>0),A.selectedCarouselCardIndex!=null&&(t.selectedCarouselCardIndex=A.selectedCarouselCardIndex>>>0),t},i.toObject=function(A,t){t||(t={});var s={};return A.selectedId!=null&&A.hasOwnProperty("selectedId")&&(s.selectedId=A.selectedId,t.oneofs&&(s._selectedId="selectedId")),A.selectedDisplayText!=null&&A.hasOwnProperty("selectedDisplayText")&&(s.selectedDisplayText=A.selectedDisplayText,t.oneofs&&(s._selectedDisplayText="selectedDisplayText")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.selectedIndex!=null&&A.hasOwnProperty("selectedIndex")&&(s.selectedIndex=A.selectedIndex,t.oneofs&&(s._selectedIndex="selectedIndex")),A.selectedCarouselCardIndex!=null&&A.hasOwnProperty("selectedCarouselCardIndex")&&(s.selectedCarouselCardIndex=A.selectedCarouselCardIndex,t.oneofs&&(s._selectedCarouselCardIndex="selectedCarouselCardIndex")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.TemplateButtonReplyMessage"},i})(),r.TemplateMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 3:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.hydratedTemplate=E.proto.Message.TemplateMessage.HydratedFourRowTemplate.decode(A,A.uint32());break}case 9:{c.templateId=A.string();break}case 1:{c.fourRowTemplate=E.proto.Message.TemplateMessage.FourRowTemplate.decode(A,A.uint32());break}case 2:{c.hydratedFourRowTemplate=E.proto.Message.TemplateMessage.HydratedFourRowTemplate.decode(A,A.uint32());break}case 5:{c.interactiveMessageTemplate=E.proto.Message.InteractiveMessage.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.TemplateMessage)return A;var t=new E.proto.Message.TemplateMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.TemplateMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}if(A.hydratedTemplate!=null){if(typeof A.hydratedTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.hydratedTemplate: object expected");t.hydratedTemplate=E.proto.Message.TemplateMessage.HydratedFourRowTemplate.fromObject(A.hydratedTemplate)}if(A.templateId!=null&&(t.templateId=String(A.templateId)),A.fourRowTemplate!=null){if(typeof A.fourRowTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.fourRowTemplate: object expected");t.fourRowTemplate=E.proto.Message.TemplateMessage.FourRowTemplate.fromObject(A.fourRowTemplate)}if(A.hydratedFourRowTemplate!=null){if(typeof A.hydratedFourRowTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.hydratedFourRowTemplate: object expected");t.hydratedFourRowTemplate=E.proto.Message.TemplateMessage.HydratedFourRowTemplate.fromObject(A.hydratedFourRowTemplate)}if(A.interactiveMessageTemplate!=null){if(typeof A.interactiveMessageTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.interactiveMessageTemplate: object expected");t.interactiveMessageTemplate=E.proto.Message.InteractiveMessage.fromObject(A.interactiveMessageTemplate)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.fourRowTemplate!=null&&A.hasOwnProperty("fourRowTemplate")&&(s.fourRowTemplate=E.proto.Message.TemplateMessage.FourRowTemplate.toObject(A.fourRowTemplate,t),t.oneofs&&(s.format="fourRowTemplate")),A.hydratedFourRowTemplate!=null&&A.hasOwnProperty("hydratedFourRowTemplate")&&(s.hydratedFourRowTemplate=E.proto.Message.TemplateMessage.HydratedFourRowTemplate.toObject(A.hydratedFourRowTemplate,t),t.oneofs&&(s.format="hydratedFourRowTemplate")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=E.proto.ContextInfo.toObject(A.contextInfo,t),t.oneofs&&(s._contextInfo="contextInfo")),A.hydratedTemplate!=null&&A.hasOwnProperty("hydratedTemplate")&&(s.hydratedTemplate=E.proto.Message.TemplateMessage.HydratedFourRowTemplate.toObject(A.hydratedTemplate,t),t.oneofs&&(s._hydratedTemplate="hydratedTemplate")),A.interactiveMessageTemplate!=null&&A.hasOwnProperty("interactiveMessageTemplate")&&(s.interactiveMessageTemplate=E.proto.Message.InteractiveMessage.toObject(A.interactiveMessageTemplate,t),t.oneofs&&(s.format="interactiveMessageTemplate")),A.templateId!=null&&A.hasOwnProperty("templateId")&&(s.templateId=A.templateId,t.oneofs&&(s._templateId="templateId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.TemplateMessage"},i.FourRowTemplate=(function(){function a(t){if(this.buttons=[],t)for(var s=Object.keys(t),g=0;g>>3){case 6:{p.content=E.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 7:{p.footer=E.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 8:{p.buttons&&p.buttons.length||(p.buttons=[]),p.buttons.push(E.proto.TemplateButton.decode(s,s.uint32()));break}case 1:{p.documentMessage=E.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 2:{p.highlyStructuredMessage=E.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 3:{p.imageMessage=E.proto.Message.ImageMessage.decode(s,s.uint32());break}case 4:{p.videoMessage=E.proto.Message.VideoMessage.decode(s,s.uint32());break}case 5:{p.locationMessage=E.proto.Message.LocationMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.TemplateMessage.FourRowTemplate)return s;var g=new E.proto.Message.TemplateMessage.FourRowTemplate;if(s.content!=null){if(typeof s.content!="object")throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.content: object expected");g.content=E.proto.Message.HighlyStructuredMessage.fromObject(s.content)}if(s.footer!=null){if(typeof s.footer!="object")throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.footer: object expected");g.footer=E.proto.Message.HighlyStructuredMessage.fromObject(s.footer)}if(s.buttons){if(!Array.isArray(s.buttons))throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.buttons: array expected");g.buttons=[];for(var c=0;c>>3){case 6:{p.hydratedContentText=s.string();break}case 7:{p.hydratedFooterText=s.string();break}case 8:{p.hydratedButtons&&p.hydratedButtons.length||(p.hydratedButtons=[]),p.hydratedButtons.push(E.proto.HydratedTemplateButton.decode(s,s.uint32()));break}case 9:{p.templateId=s.string();break}case 10:{p.maskLinkedDevices=s.bool();break}case 1:{p.documentMessage=E.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 2:{p.hydratedTitleText=s.string();break}case 3:{p.imageMessage=E.proto.Message.ImageMessage.decode(s,s.uint32());break}case 4:{p.videoMessage=E.proto.Message.VideoMessage.decode(s,s.uint32());break}case 5:{p.locationMessage=E.proto.Message.LocationMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.Message.TemplateMessage.HydratedFourRowTemplate)return s;var g=new E.proto.Message.TemplateMessage.HydratedFourRowTemplate;if(s.hydratedContentText!=null&&(g.hydratedContentText=String(s.hydratedContentText)),s.hydratedFooterText!=null&&(g.hydratedFooterText=String(s.hydratedFooterText)),s.hydratedButtons){if(!Array.isArray(s.hydratedButtons))throw TypeError(".proto.Message.TemplateMessage.HydratedFourRowTemplate.hydratedButtons: array expected");g.hydratedButtons=[];for(var c=0;c>>3){case 1:{c.fbExperimentId=A.uint32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.URLMetadata)return A;var t=new E.proto.Message.URLMetadata;return A.fbExperimentId!=null&&(t.fbExperimentId=A.fbExperimentId>>>0),t},i.toObject=function(A,t){t||(t={});var s={};return A.fbExperimentId!=null&&A.hasOwnProperty("fbExperimentId")&&(s.fbExperimentId=A.fbExperimentId,t.oneofs&&(s._fbExperimentId="fbExperimentId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.URLMetadata"},i})(),r.VideoEndCard=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.username=a.string();break}case 2:{g.caption=a.string();break}case 3:{g.thumbnailImageUrl=a.string();break}case 4:{g.profilePictureUrl=a.string();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.Message.VideoEndCard)return a;var A=new E.proto.Message.VideoEndCard;return a.username!=null&&(A.username=String(a.username)),a.caption!=null&&(A.caption=String(a.caption)),a.thumbnailImageUrl!=null&&(A.thumbnailImageUrl=String(a.thumbnailImageUrl)),a.profilePictureUrl!=null&&(A.profilePictureUrl=String(a.profilePictureUrl)),A},i.toObject=function(a,A){A||(A={});var t={};return A.defaults&&(t.username="",t.caption="",t.thumbnailImageUrl="",t.profilePictureUrl=""),a.username!=null&&a.hasOwnProperty("username")&&(t.username=a.username),a.caption!=null&&a.hasOwnProperty("caption")&&(t.caption=a.caption),a.thumbnailImageUrl!=null&&a.hasOwnProperty("thumbnailImageUrl")&&(t.thumbnailImageUrl=a.thumbnailImageUrl),a.profilePictureUrl!=null&&a.hasOwnProperty("profilePictureUrl")&&(t.profilePictureUrl=a.profilePictureUrl),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Message.VideoEndCard"},i})(),r.VideoMessage=(function(){function i(a){if(this.interactiveAnnotations=[],this.annotations=[],this.processedVideos=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileLength=A.uint64();break}case 5:{c.seconds=A.uint32();break}case 6:{c.mediaKey=A.bytes();break}case 7:{c.caption=A.string();break}case 8:{c.gifPlayback=A.bool();break}case 9:{c.height=A.uint32();break}case 10:{c.width=A.uint32();break}case 11:{c.fileEncSha256=A.bytes();break}case 12:{c.interactiveAnnotations&&c.interactiveAnnotations.length||(c.interactiveAnnotations=[]),c.interactiveAnnotations.push(E.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 13:{c.directPath=A.string();break}case 14:{c.mediaKeyTimestamp=A.int64();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=E.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.streamingSidecar=A.bytes();break}case 19:{c.gifAttribution=A.int32();break}case 20:{c.viewOnce=A.bool();break}case 21:{c.thumbnailDirectPath=A.string();break}case 22:{c.thumbnailSha256=A.bytes();break}case 23:{c.thumbnailEncSha256=A.bytes();break}case 24:{c.staticUrl=A.string();break}case 25:{c.annotations&&c.annotations.length||(c.annotations=[]),c.annotations.push(E.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 26:{c.accessibilityLabel=A.string();break}case 27:{c.processedVideos&&c.processedVideos.length||(c.processedVideos=[]),c.processedVideos.push(E.proto.ProcessedVideo.decode(A,A.uint32()));break}case 28:{c.externalShareFullVideoDurationInSeconds=A.uint32();break}case 29:{c.motionPhotoPresentationOffsetMs=A.uint64();break}case 30:{c.metadataUrl=A.string();break}case 31:{c.videoSourceType=A.int32();break}case 32:{c.mediaKeyDomain=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.Message.VideoMessage)return A;var t=new E.proto.Message.VideoMessage;if(A.url!=null&&(t.url=String(A.url)),A.mimetype!=null&&(t.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.fileLength!=null&&(I.Long?(t.fileLength=I.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?t.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?t.fileLength=A.fileLength:typeof A.fileLength=="object"&&(t.fileLength=new I.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.seconds!=null&&(t.seconds=A.seconds>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.caption!=null&&(t.caption=String(A.caption)),A.gifPlayback!=null&&(t.gifPlayback=!!A.gifPlayback),A.height!=null&&(t.height=A.height>>>0),A.width!=null&&(t.width=A.width>>>0),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.interactiveAnnotations){if(!Array.isArray(A.interactiveAnnotations))throw TypeError(".proto.Message.VideoMessage.interactiveAnnotations: array expected");t.interactiveAnnotations=[];for(var s=0;s>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.VideoMessage.contextInfo: object expected");t.contextInfo=E.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.streamingSidecar!=null&&(typeof A.streamingSidecar=="string"?I.base64.decode(A.streamingSidecar,t.streamingSidecar=I.newBuffer(I.base64.length(A.streamingSidecar)),0):A.streamingSidecar.length>=0&&(t.streamingSidecar=A.streamingSidecar)),A.gifAttribution){default:if(typeof A.gifAttribution=="number"){t.gifAttribution=A.gifAttribution;break}break;case"NONE":case 0:t.gifAttribution=0;break;case"GIPHY":case 1:t.gifAttribution=1;break;case"TENOR":case 2:t.gifAttribution=2;break;case"KLIPY":case 3:t.gifAttribution=3;break}if(A.viewOnce!=null&&(t.viewOnce=!!A.viewOnce),A.thumbnailDirectPath!=null&&(t.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?I.base64.decode(A.thumbnailSha256,t.thumbnailSha256=I.newBuffer(I.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(t.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?I.base64.decode(A.thumbnailEncSha256,t.thumbnailEncSha256=I.newBuffer(I.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(t.thumbnailEncSha256=A.thumbnailEncSha256)),A.staticUrl!=null&&(t.staticUrl=String(A.staticUrl)),A.annotations){if(!Array.isArray(A.annotations))throw TypeError(".proto.Message.VideoMessage.annotations: array expected");t.annotations=[];for(var s=0;s>>0),A.motionPhotoPresentationOffsetMs!=null&&(I.Long?(t.motionPhotoPresentationOffsetMs=I.Long.fromValue(A.motionPhotoPresentationOffsetMs)).unsigned=!0:typeof A.motionPhotoPresentationOffsetMs=="string"?t.motionPhotoPresentationOffsetMs=parseInt(A.motionPhotoPresentationOffsetMs,10):typeof A.motionPhotoPresentationOffsetMs=="number"?t.motionPhotoPresentationOffsetMs=A.motionPhotoPresentationOffsetMs:typeof A.motionPhotoPresentationOffsetMs=="object"&&(t.motionPhotoPresentationOffsetMs=new I.LongBits(A.motionPhotoPresentationOffsetMs.low>>>0,A.motionPhotoPresentationOffsetMs.high>>>0).toNumber(!0))),A.metadataUrl!=null&&(t.metadataUrl=String(A.metadataUrl)),A.videoSourceType){default:if(typeof A.videoSourceType=="number"){t.videoSourceType=A.videoSourceType;break}break;case"USER_VIDEO":case 0:t.videoSourceType=0;break;case"AI_GENERATED":case 1:t.videoSourceType=1;break}switch(A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){t.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:t.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:t.mediaKeyDomain=1;break;case"STATUS":case 2:t.mediaKeyDomain=2;break;case"CAPI":case 3:t.mediaKeyDomain=3;break;case"BOT":case 4:t.mediaKeyDomain=4;break}return t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.interactiveAnnotations=[],s.annotations=[],s.processedVideos=[]),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,t.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=t.bytes===String?I.base64.encode(A.fileSha256,0,A.fileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,t.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=t.longs===String?String(A.fileLength):A.fileLength:s.fileLength=t.longs===String?re(A.fileLength,!0):t.longs===Number?ae(A.fileLength,!0):A.fileLength,t.oneofs&&(s._fileLength="fileLength")),A.seconds!=null&&A.hasOwnProperty("seconds")&&(s.seconds=A.seconds,t.oneofs&&(s._seconds="seconds")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,t.oneofs&&(s._caption="caption")),A.gifPlayback!=null&&A.hasOwnProperty("gifPlayback")&&(s.gifPlayback=A.gifPlayback,t.oneofs&&(s._gifPlayback="gifPlayback")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,t.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,t.oneofs&&(s._width="width")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.interactiveAnnotations&&A.interactiveAnnotations.length){s.interactiveAnnotations=[];for(var g=0;g>>3){case 1:{s.messageAddOnType=e.int32();break}case 2:{s.messageAddOn=E.proto.Message.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.status=e.int32();break}case 6:{s.addOnContextInfo=E.proto.MessageAddOnContextInfo.decode(e,e.uint32());break}case 7:{s.messageAddOnKey=E.proto.MessageKey.decode(e,e.uint32());break}case 8:{s.legacyMessage=E.proto.LegacyMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MessageAddOn)return e;var a=new E.proto.MessageAddOn;switch(e.messageAddOnType){default:if(typeof e.messageAddOnType=="number"){a.messageAddOnType=e.messageAddOnType;break}break;case"UNDEFINED":case 0:a.messageAddOnType=0;break;case"REACTION":case 1:a.messageAddOnType=1;break;case"EVENT_RESPONSE":case 2:a.messageAddOnType=2;break;case"POLL_UPDATE":case 3:a.messageAddOnType=3;break;case"PIN_IN_CHAT":case 4:a.messageAddOnType=4;break}if(e.messageAddOn!=null){if(typeof e.messageAddOn!="object")throw TypeError(".proto.MessageAddOn.messageAddOn: object expected");a.messageAddOn=E.proto.Message.fromObject(e.messageAddOn)}switch(e.senderTimestampMs!=null&&(I.Long?(a.senderTimestampMs=I.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new I.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(I.Long?(a.serverTimestampMs=I.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new I.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"ERROR":case 0:a.status=0;break;case"PENDING":case 1:a.status=1;break;case"SERVER_ACK":case 2:a.status=2;break;case"DELIVERY_ACK":case 3:a.status=3;break;case"READ":case 4:a.status=4;break;case"PLAYED":case 5:a.status=5;break}if(e.addOnContextInfo!=null){if(typeof e.addOnContextInfo!="object")throw TypeError(".proto.MessageAddOn.addOnContextInfo: object expected");a.addOnContextInfo=E.proto.MessageAddOnContextInfo.fromObject(e.addOnContextInfo)}if(e.messageAddOnKey!=null){if(typeof e.messageAddOnKey!="object")throw TypeError(".proto.MessageAddOn.messageAddOnKey: object expected");a.messageAddOnKey=E.proto.MessageKey.fromObject(e.messageAddOnKey)}if(e.legacyMessage!=null){if(typeof e.legacyMessage!="object")throw TypeError(".proto.MessageAddOn.legacyMessage: object expected");a.legacyMessage=E.proto.LegacyMessage.fromObject(e.legacyMessage)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.messageAddOnType!=null&&e.hasOwnProperty("messageAddOnType")&&(A.messageAddOnType=a.enums===String?E.proto.MessageAddOn.MessageAddOnType[e.messageAddOnType]===void 0?e.messageAddOnType:E.proto.MessageAddOn.MessageAddOnType[e.messageAddOnType]:e.messageAddOnType,a.oneofs&&(A._messageAddOnType="messageAddOnType")),e.messageAddOn!=null&&e.hasOwnProperty("messageAddOn")&&(A.messageAddOn=E.proto.Message.toObject(e.messageAddOn,a),a.oneofs&&(A._messageAddOn="messageAddOn")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?re(e.senderTimestampMs):a.longs===Number?ae(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?re(e.serverTimestampMs):a.longs===Number?ae(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.status!=null&&e.hasOwnProperty("status")&&(A.status=a.enums===String?E.proto.WebMessageInfo.Status[e.status]===void 0?e.status:E.proto.WebMessageInfo.Status[e.status]:e.status,a.oneofs&&(A._status="status")),e.addOnContextInfo!=null&&e.hasOwnProperty("addOnContextInfo")&&(A.addOnContextInfo=E.proto.MessageAddOnContextInfo.toObject(e.addOnContextInfo,a),a.oneofs&&(A._addOnContextInfo="addOnContextInfo")),e.messageAddOnKey!=null&&e.hasOwnProperty("messageAddOnKey")&&(A.messageAddOnKey=E.proto.MessageKey.toObject(e.messageAddOnKey,a),a.oneofs&&(A._messageAddOnKey="messageAddOnKey")),e.legacyMessage!=null&&e.hasOwnProperty("legacyMessage")&&(A.legacyMessage=E.proto.LegacyMessage.toObject(e.legacyMessage,a),a.oneofs&&(A._legacyMessage="legacyMessage")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAddOn"},r.MessageAddOnType=(function(){let i={},e=Object.create(i);return e[i[0]="UNDEFINED"]=0,e[i[1]="REACTION"]=1,e[i[2]="EVENT_RESPONSE"]=2,e[i[3]="POLL_UPDATE"]=3,e[i[4]="PIN_IN_CHAT"]=4,e})(),r})(),n.MessageAddOnContextInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageAddOnDurationInSecs=e.uint32();break}case 2:{s.messageAddOnExpiryType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MessageAddOnContextInfo)return e;var a=new E.proto.MessageAddOnContextInfo;switch(e.messageAddOnDurationInSecs!=null&&(a.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs>>>0),e.messageAddOnExpiryType){default:if(typeof e.messageAddOnExpiryType=="number"){a.messageAddOnExpiryType=e.messageAddOnExpiryType;break}break;case"STATIC":case 1:a.messageAddOnExpiryType=1;break;case"DEPENDENT_ON_PARENT":case 2:a.messageAddOnExpiryType=2;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.messageAddOnDurationInSecs!=null&&e.hasOwnProperty("messageAddOnDurationInSecs")&&(A.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs,a.oneofs&&(A._messageAddOnDurationInSecs="messageAddOnDurationInSecs")),e.messageAddOnExpiryType!=null&&e.hasOwnProperty("messageAddOnExpiryType")&&(A.messageAddOnExpiryType=a.enums===String?E.proto.MessageContextInfo.MessageAddonExpiryType[e.messageAddOnExpiryType]===void 0?e.messageAddOnExpiryType:E.proto.MessageContextInfo.MessageAddonExpiryType[e.messageAddOnExpiryType]:e.messageAddOnExpiryType,a.oneofs&&(A._messageAddOnExpiryType="messageAddOnExpiryType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAddOnContextInfo"},r})(),n.MessageAssociation=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.associationType=e.int32();break}case 2:{s.parentMessageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 3:{s.messageIndex=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MessageAssociation)return e;var a=new E.proto.MessageAssociation;switch(e.associationType){default:if(typeof e.associationType=="number"){a.associationType=e.associationType;break}break;case"UNKNOWN":case 0:a.associationType=0;break;case"MEDIA_ALBUM":case 1:a.associationType=1;break;case"BOT_PLUGIN":case 2:a.associationType=2;break;case"EVENT_COVER_IMAGE":case 3:a.associationType=3;break;case"STATUS_POLL":case 4:a.associationType=4;break;case"HD_VIDEO_DUAL_UPLOAD":case 5:a.associationType=5;break;case"STATUS_EXTERNAL_RESHARE":case 6:a.associationType=6;break;case"MEDIA_POLL":case 7:a.associationType=7;break;case"STATUS_ADD_YOURS":case 8:a.associationType=8;break;case"STATUS_NOTIFICATION":case 9:a.associationType=9;break;case"HD_IMAGE_DUAL_UPLOAD":case 10:a.associationType=10;break;case"STICKER_ANNOTATION":case 11:a.associationType=11;break;case"MOTION_PHOTO":case 12:a.associationType=12;break;case"STATUS_LINK_ACTION":case 13:a.associationType=13;break;case"VIEW_ALL_REPLIES":case 14:a.associationType=14;break;case"STATUS_ADD_YOURS_AI_IMAGINE":case 15:a.associationType=15;break;case"STATUS_QUESTION":case 16:a.associationType=16;break;case"STATUS_ADD_YOURS_DIWALI":case 17:a.associationType=17;break;case"STATUS_REACTION":case 18:a.associationType=18;break;case"HEVC_VIDEO_DUAL_UPLOAD":case 19:a.associationType=19;break}if(e.parentMessageKey!=null){if(typeof e.parentMessageKey!="object")throw TypeError(".proto.MessageAssociation.parentMessageKey: object expected");a.parentMessageKey=E.proto.MessageKey.fromObject(e.parentMessageKey)}return e.messageIndex!=null&&(a.messageIndex=e.messageIndex|0),a},r.toObject=function(e,a){a||(a={});var A={};return e.associationType!=null&&e.hasOwnProperty("associationType")&&(A.associationType=a.enums===String?E.proto.MessageAssociation.AssociationType[e.associationType]===void 0?e.associationType:E.proto.MessageAssociation.AssociationType[e.associationType]:e.associationType,a.oneofs&&(A._associationType="associationType")),e.parentMessageKey!=null&&e.hasOwnProperty("parentMessageKey")&&(A.parentMessageKey=E.proto.MessageKey.toObject(e.parentMessageKey,a),a.oneofs&&(A._parentMessageKey="parentMessageKey")),e.messageIndex!=null&&e.hasOwnProperty("messageIndex")&&(A.messageIndex=e.messageIndex,a.oneofs&&(A._messageIndex="messageIndex")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAssociation"},r.AssociationType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="MEDIA_ALBUM"]=1,e[i[2]="BOT_PLUGIN"]=2,e[i[3]="EVENT_COVER_IMAGE"]=3,e[i[4]="STATUS_POLL"]=4,e[i[5]="HD_VIDEO_DUAL_UPLOAD"]=5,e[i[6]="STATUS_EXTERNAL_RESHARE"]=6,e[i[7]="MEDIA_POLL"]=7,e[i[8]="STATUS_ADD_YOURS"]=8,e[i[9]="STATUS_NOTIFICATION"]=9,e[i[10]="HD_IMAGE_DUAL_UPLOAD"]=10,e[i[11]="STICKER_ANNOTATION"]=11,e[i[12]="MOTION_PHOTO"]=12,e[i[13]="STATUS_LINK_ACTION"]=13,e[i[14]="VIEW_ALL_REPLIES"]=14,e[i[15]="STATUS_ADD_YOURS_AI_IMAGINE"]=15,e[i[16]="STATUS_QUESTION"]=16,e[i[17]="STATUS_ADD_YOURS_DIWALI"]=17,e[i[18]="STATUS_REACTION"]=18,e[i[19]="HEVC_VIDEO_DUAL_UPLOAD"]=19,e})(),r})(),n.MessageContextInfo=(function(){function r(i){if(this.threadId=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.deviceListMetadata=E.proto.DeviceListMetadata.decode(e,e.uint32());break}case 2:{s.deviceListMetadataVersion=e.int32();break}case 3:{s.messageSecret=e.bytes();break}case 4:{s.paddingBytes=e.bytes();break}case 5:{s.messageAddOnDurationInSecs=e.uint32();break}case 6:{s.botMessageSecret=e.bytes();break}case 7:{s.botMetadata=E.proto.BotMetadata.decode(e,e.uint32());break}case 8:{s.reportingTokenVersion=e.int32();break}case 9:{s.messageAddOnExpiryType=e.int32();break}case 10:{s.messageAssociation=E.proto.MessageAssociation.decode(e,e.uint32());break}case 11:{s.capiCreatedGroup=e.bool();break}case 12:{s.supportPayload=e.string();break}case 13:{s.limitSharing=E.proto.LimitSharing.decode(e,e.uint32());break}case 14:{s.limitSharingV2=E.proto.LimitSharing.decode(e,e.uint32());break}case 15:{s.threadId&&s.threadId.length||(s.threadId=[]),s.threadId.push(E.proto.ThreadID.decode(e,e.uint32()));break}case 16:{s.weblinkRenderConfig=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MessageContextInfo)return e;var a=new E.proto.MessageContextInfo;if(e.deviceListMetadata!=null){if(typeof e.deviceListMetadata!="object")throw TypeError(".proto.MessageContextInfo.deviceListMetadata: object expected");a.deviceListMetadata=E.proto.DeviceListMetadata.fromObject(e.deviceListMetadata)}if(e.deviceListMetadataVersion!=null&&(a.deviceListMetadataVersion=e.deviceListMetadataVersion|0),e.messageSecret!=null&&(typeof e.messageSecret=="string"?I.base64.decode(e.messageSecret,a.messageSecret=I.newBuffer(I.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),e.paddingBytes!=null&&(typeof e.paddingBytes=="string"?I.base64.decode(e.paddingBytes,a.paddingBytes=I.newBuffer(I.base64.length(e.paddingBytes)),0):e.paddingBytes.length>=0&&(a.paddingBytes=e.paddingBytes)),e.messageAddOnDurationInSecs!=null&&(a.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs>>>0),e.botMessageSecret!=null&&(typeof e.botMessageSecret=="string"?I.base64.decode(e.botMessageSecret,a.botMessageSecret=I.newBuffer(I.base64.length(e.botMessageSecret)),0):e.botMessageSecret.length>=0&&(a.botMessageSecret=e.botMessageSecret)),e.botMetadata!=null){if(typeof e.botMetadata!="object")throw TypeError(".proto.MessageContextInfo.botMetadata: object expected");a.botMetadata=E.proto.BotMetadata.fromObject(e.botMetadata)}switch(e.reportingTokenVersion!=null&&(a.reportingTokenVersion=e.reportingTokenVersion|0),e.messageAddOnExpiryType){default:if(typeof e.messageAddOnExpiryType=="number"){a.messageAddOnExpiryType=e.messageAddOnExpiryType;break}break;case"STATIC":case 1:a.messageAddOnExpiryType=1;break;case"DEPENDENT_ON_PARENT":case 2:a.messageAddOnExpiryType=2;break}if(e.messageAssociation!=null){if(typeof e.messageAssociation!="object")throw TypeError(".proto.MessageContextInfo.messageAssociation: object expected");a.messageAssociation=E.proto.MessageAssociation.fromObject(e.messageAssociation)}if(e.capiCreatedGroup!=null&&(a.capiCreatedGroup=!!e.capiCreatedGroup),e.supportPayload!=null&&(a.supportPayload=String(e.supportPayload)),e.limitSharing!=null){if(typeof e.limitSharing!="object")throw TypeError(".proto.MessageContextInfo.limitSharing: object expected");a.limitSharing=E.proto.LimitSharing.fromObject(e.limitSharing)}if(e.limitSharingV2!=null){if(typeof e.limitSharingV2!="object")throw TypeError(".proto.MessageContextInfo.limitSharingV2: object expected");a.limitSharingV2=E.proto.LimitSharing.fromObject(e.limitSharingV2)}if(e.threadId){if(!Array.isArray(e.threadId))throw TypeError(".proto.MessageContextInfo.threadId: array expected");a.threadId=[];for(var A=0;A>>3){case 1:{s.remoteJid=e.string();break}case 2:{s.fromMe=e.bool();break}case 3:{s.id=e.string();break}case 4:{s.participant=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MessageKey)return e;var a=new E.proto.MessageKey;return e.remoteJid!=null&&(a.remoteJid=String(e.remoteJid)),e.fromMe!=null&&(a.fromMe=!!e.fromMe),e.id!=null&&(a.id=String(e.id)),e.participant!=null&&(a.participant=String(e.participant)),a},r.toObject=function(e,a){a||(a={});var A={};return e.remoteJid!=null&&e.hasOwnProperty("remoteJid")&&(A.remoteJid=e.remoteJid,a.oneofs&&(A._remoteJid="remoteJid")),e.fromMe!=null&&e.hasOwnProperty("fromMe")&&(A.fromMe=e.fromMe,a.oneofs&&(A._fromMe="fromMe")),e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageKey"},r})(),n.MessageSecretMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=e.sfixed32();break}case 2:{s.encIv=e.bytes();break}case 3:{s.encPayload=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MessageSecretMessage)return e;var a=new E.proto.MessageSecretMessage;return e.version!=null&&(a.version=e.version|0),e.encIv!=null&&(typeof e.encIv=="string"?I.base64.decode(e.encIv,a.encIv=I.newBuffer(I.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),e.encPayload!=null&&(typeof e.encPayload=="string"?I.base64.decode(e.encPayload,a.encPayload=I.newBuffer(I.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),a},r.toObject=function(e,a){a||(a={});var A={};return e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),e.encIv!=null&&e.hasOwnProperty("encIv")&&(A.encIv=a.bytes===String?I.base64.encode(e.encIv,0,e.encIv.length):a.bytes===Array?Array.prototype.slice.call(e.encIv):e.encIv,a.oneofs&&(A._encIv="encIv")),e.encPayload!=null&&e.hasOwnProperty("encPayload")&&(A.encPayload=a.bytes===String?I.base64.encode(e.encPayload,0,e.encPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encPayload):e.encPayload,a.oneofs&&(A._encPayload="encPayload")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageSecretMessage"},r})(),n.Money=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.value=e.int64();break}case 2:{s.offset=e.uint32();break}case 3:{s.currencyCode=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Money)return e;var a=new E.proto.Money;return e.value!=null&&(I.Long?(a.value=I.Long.fromValue(e.value)).unsigned=!1:typeof e.value=="string"?a.value=parseInt(e.value,10):typeof e.value=="number"?a.value=e.value:typeof e.value=="object"&&(a.value=new I.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber())),e.offset!=null&&(a.offset=e.offset>>>0),e.currencyCode!=null&&(a.currencyCode=String(e.currencyCode)),a},r.toObject=function(e,a){a||(a={});var A={};return e.value!=null&&e.hasOwnProperty("value")&&(typeof e.value=="number"?A.value=a.longs===String?String(e.value):e.value:A.value=a.longs===String?re(e.value):a.longs===Number?ae(e.value):e.value,a.oneofs&&(A._value="value")),e.offset!=null&&e.hasOwnProperty("offset")&&(A.offset=e.offset,a.oneofs&&(A._offset="offset")),e.currencyCode!=null&&e.hasOwnProperty("currencyCode")&&(A.currencyCode=e.currencyCode,a.oneofs&&(A._currencyCode="currencyCode")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Money"},r})(),n.MsgOpaqueData=(function(){function r(i){if(this.pollOptions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.body=e.string();break}case 3:{s.caption=e.string();break}case 5:{s.lng=e.double();break}case 6:{s.isLive=e.bool();break}case 7:{s.lat=e.double();break}case 8:{s.paymentAmount1000=e.int32();break}case 9:{s.paymentNoteMsgBody=e.string();break}case 11:{s.matchedText=e.string();break}case 12:{s.title=e.string();break}case 13:{s.description=e.string();break}case 14:{s.futureproofBuffer=e.bytes();break}case 15:{s.clientUrl=e.string();break}case 16:{s.loc=e.string();break}case 17:{s.pollName=e.string();break}case 18:{s.pollOptions&&s.pollOptions.length||(s.pollOptions=[]),s.pollOptions.push(E.proto.MsgOpaqueData.PollOption.decode(e,e.uint32()));break}case 20:{s.pollSelectableOptionsCount=e.uint32();break}case 21:{s.messageSecret=e.bytes();break}case 51:{s.originalSelfAuthor=e.string();break}case 22:{s.senderTimestampMs=e.int64();break}case 23:{s.pollUpdateParentKey=e.string();break}case 24:{s.encPollVote=E.proto.PollEncValue.decode(e,e.uint32());break}case 28:{s.isSentCagPollCreation=e.bool();break}case 42:{s.pollContentType=e.int32();break}case 46:{s.pollType=e.int32();break}case 47:{s.correctOptionIndex=e.int32();break}case 41:{s.pollVotesSnapshot=E.proto.MsgOpaqueData.PollVotesSnapshot.decode(e,e.uint32());break}case 25:{s.encReactionTargetMessageKey=e.string();break}case 26:{s.encReactionEncPayload=e.bytes();break}case 27:{s.encReactionEncIv=e.bytes();break}case 29:{s.botMessageSecret=e.bytes();break}case 30:{s.targetMessageKey=e.string();break}case 31:{s.encPayload=e.bytes();break}case 32:{s.encIv=e.bytes();break}case 33:{s.eventName=e.string();break}case 34:{s.isEventCanceled=e.bool();break}case 35:{s.eventDescription=e.string();break}case 36:{s.eventJoinLink=e.string();break}case 37:{s.eventStartTime=e.int64();break}case 38:{s.eventLocation=E.proto.MsgOpaqueData.EventLocation.decode(e,e.uint32());break}case 40:{s.eventEndTime=e.int64();break}case 44:{s.eventIsScheduledCall=e.bool();break}case 45:{s.eventExtraGuestsAllowed=e.bool();break}case 43:{s.plainProtobufBytes=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MsgOpaqueData)return e;var a=new E.proto.MsgOpaqueData;if(e.body!=null&&(a.body=String(e.body)),e.caption!=null&&(a.caption=String(e.caption)),e.lng!=null&&(a.lng=Number(e.lng)),e.isLive!=null&&(a.isLive=!!e.isLive),e.lat!=null&&(a.lat=Number(e.lat)),e.paymentAmount1000!=null&&(a.paymentAmount1000=e.paymentAmount1000|0),e.paymentNoteMsgBody!=null&&(a.paymentNoteMsgBody=String(e.paymentNoteMsgBody)),e.matchedText!=null&&(a.matchedText=String(e.matchedText)),e.title!=null&&(a.title=String(e.title)),e.description!=null&&(a.description=String(e.description)),e.futureproofBuffer!=null&&(typeof e.futureproofBuffer=="string"?I.base64.decode(e.futureproofBuffer,a.futureproofBuffer=I.newBuffer(I.base64.length(e.futureproofBuffer)),0):e.futureproofBuffer.length>=0&&(a.futureproofBuffer=e.futureproofBuffer)),e.clientUrl!=null&&(a.clientUrl=String(e.clientUrl)),e.loc!=null&&(a.loc=String(e.loc)),e.pollName!=null&&(a.pollName=String(e.pollName)),e.pollOptions){if(!Array.isArray(e.pollOptions))throw TypeError(".proto.MsgOpaqueData.pollOptions: array expected");a.pollOptions=[];for(var A=0;A>>0),e.messageSecret!=null&&(typeof e.messageSecret=="string"?I.base64.decode(e.messageSecret,a.messageSecret=I.newBuffer(I.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),e.originalSelfAuthor!=null&&(a.originalSelfAuthor=String(e.originalSelfAuthor)),e.senderTimestampMs!=null&&(I.Long?(a.senderTimestampMs=I.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new I.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.pollUpdateParentKey!=null&&(a.pollUpdateParentKey=String(e.pollUpdateParentKey)),e.encPollVote!=null){if(typeof e.encPollVote!="object")throw TypeError(".proto.MsgOpaqueData.encPollVote: object expected");a.encPollVote=E.proto.PollEncValue.fromObject(e.encPollVote)}switch(e.isSentCagPollCreation!=null&&(a.isSentCagPollCreation=!!e.isSentCagPollCreation),e.pollContentType){default:if(typeof e.pollContentType=="number"){a.pollContentType=e.pollContentType;break}break;case"UNKNOWN":case 0:a.pollContentType=0;break;case"TEXT":case 1:a.pollContentType=1;break;case"IMAGE":case 2:a.pollContentType=2;break}switch(e.pollType){default:if(typeof e.pollType=="number"){a.pollType=e.pollType;break}break;case"POLL":case 0:a.pollType=0;break;case"QUIZ":case 1:a.pollType=1;break}if(e.correctOptionIndex!=null&&(a.correctOptionIndex=e.correctOptionIndex|0),e.pollVotesSnapshot!=null){if(typeof e.pollVotesSnapshot!="object")throw TypeError(".proto.MsgOpaqueData.pollVotesSnapshot: object expected");a.pollVotesSnapshot=E.proto.MsgOpaqueData.PollVotesSnapshot.fromObject(e.pollVotesSnapshot)}if(e.encReactionTargetMessageKey!=null&&(a.encReactionTargetMessageKey=String(e.encReactionTargetMessageKey)),e.encReactionEncPayload!=null&&(typeof e.encReactionEncPayload=="string"?I.base64.decode(e.encReactionEncPayload,a.encReactionEncPayload=I.newBuffer(I.base64.length(e.encReactionEncPayload)),0):e.encReactionEncPayload.length>=0&&(a.encReactionEncPayload=e.encReactionEncPayload)),e.encReactionEncIv!=null&&(typeof e.encReactionEncIv=="string"?I.base64.decode(e.encReactionEncIv,a.encReactionEncIv=I.newBuffer(I.base64.length(e.encReactionEncIv)),0):e.encReactionEncIv.length>=0&&(a.encReactionEncIv=e.encReactionEncIv)),e.botMessageSecret!=null&&(typeof e.botMessageSecret=="string"?I.base64.decode(e.botMessageSecret,a.botMessageSecret=I.newBuffer(I.base64.length(e.botMessageSecret)),0):e.botMessageSecret.length>=0&&(a.botMessageSecret=e.botMessageSecret)),e.targetMessageKey!=null&&(a.targetMessageKey=String(e.targetMessageKey)),e.encPayload!=null&&(typeof e.encPayload=="string"?I.base64.decode(e.encPayload,a.encPayload=I.newBuffer(I.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),e.encIv!=null&&(typeof e.encIv=="string"?I.base64.decode(e.encIv,a.encIv=I.newBuffer(I.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),e.eventName!=null&&(a.eventName=String(e.eventName)),e.isEventCanceled!=null&&(a.isEventCanceled=!!e.isEventCanceled),e.eventDescription!=null&&(a.eventDescription=String(e.eventDescription)),e.eventJoinLink!=null&&(a.eventJoinLink=String(e.eventJoinLink)),e.eventStartTime!=null&&(I.Long?(a.eventStartTime=I.Long.fromValue(e.eventStartTime)).unsigned=!1:typeof e.eventStartTime=="string"?a.eventStartTime=parseInt(e.eventStartTime,10):typeof e.eventStartTime=="number"?a.eventStartTime=e.eventStartTime:typeof e.eventStartTime=="object"&&(a.eventStartTime=new I.LongBits(e.eventStartTime.low>>>0,e.eventStartTime.high>>>0).toNumber())),e.eventLocation!=null){if(typeof e.eventLocation!="object")throw TypeError(".proto.MsgOpaqueData.eventLocation: object expected");a.eventLocation=E.proto.MsgOpaqueData.EventLocation.fromObject(e.eventLocation)}return e.eventEndTime!=null&&(I.Long?(a.eventEndTime=I.Long.fromValue(e.eventEndTime)).unsigned=!1:typeof e.eventEndTime=="string"?a.eventEndTime=parseInt(e.eventEndTime,10):typeof e.eventEndTime=="number"?a.eventEndTime=e.eventEndTime:typeof e.eventEndTime=="object"&&(a.eventEndTime=new I.LongBits(e.eventEndTime.low>>>0,e.eventEndTime.high>>>0).toNumber())),e.eventIsScheduledCall!=null&&(a.eventIsScheduledCall=!!e.eventIsScheduledCall),e.eventExtraGuestsAllowed!=null&&(a.eventExtraGuestsAllowed=!!e.eventExtraGuestsAllowed),e.plainProtobufBytes!=null&&(typeof e.plainProtobufBytes=="string"?I.base64.decode(e.plainProtobufBytes,a.plainProtobufBytes=I.newBuffer(I.base64.length(e.plainProtobufBytes)),0):e.plainProtobufBytes.length>=0&&(a.plainProtobufBytes=e.plainProtobufBytes)),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.pollOptions=[]),e.body!=null&&e.hasOwnProperty("body")&&(A.body=e.body,a.oneofs&&(A._body="body")),e.caption!=null&&e.hasOwnProperty("caption")&&(A.caption=e.caption,a.oneofs&&(A._caption="caption")),e.lng!=null&&e.hasOwnProperty("lng")&&(A.lng=a.json&&!isFinite(e.lng)?String(e.lng):e.lng,a.oneofs&&(A._lng="lng")),e.isLive!=null&&e.hasOwnProperty("isLive")&&(A.isLive=e.isLive,a.oneofs&&(A._isLive="isLive")),e.lat!=null&&e.hasOwnProperty("lat")&&(A.lat=a.json&&!isFinite(e.lat)?String(e.lat):e.lat,a.oneofs&&(A._lat="lat")),e.paymentAmount1000!=null&&e.hasOwnProperty("paymentAmount1000")&&(A.paymentAmount1000=e.paymentAmount1000,a.oneofs&&(A._paymentAmount1000="paymentAmount1000")),e.paymentNoteMsgBody!=null&&e.hasOwnProperty("paymentNoteMsgBody")&&(A.paymentNoteMsgBody=e.paymentNoteMsgBody,a.oneofs&&(A._paymentNoteMsgBody="paymentNoteMsgBody")),e.matchedText!=null&&e.hasOwnProperty("matchedText")&&(A.matchedText=e.matchedText,a.oneofs&&(A._matchedText="matchedText")),e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.description!=null&&e.hasOwnProperty("description")&&(A.description=e.description,a.oneofs&&(A._description="description")),e.futureproofBuffer!=null&&e.hasOwnProperty("futureproofBuffer")&&(A.futureproofBuffer=a.bytes===String?I.base64.encode(e.futureproofBuffer,0,e.futureproofBuffer.length):a.bytes===Array?Array.prototype.slice.call(e.futureproofBuffer):e.futureproofBuffer,a.oneofs&&(A._futureproofBuffer="futureproofBuffer")),e.clientUrl!=null&&e.hasOwnProperty("clientUrl")&&(A.clientUrl=e.clientUrl,a.oneofs&&(A._clientUrl="clientUrl")),e.loc!=null&&e.hasOwnProperty("loc")&&(A.loc=e.loc,a.oneofs&&(A._loc="loc")),e.pollName!=null&&e.hasOwnProperty("pollName")&&(A.pollName=e.pollName,a.oneofs&&(A._pollName="pollName")),e.pollOptions&&e.pollOptions.length){A.pollOptions=[];for(var t=0;t>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.name=A.string();break}case 4:{c.address=A.string();break}case 5:{c.url=A.string();break}case 6:{c.jpegThumbnail=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.MsgOpaqueData.EventLocation)return A;var t=new E.proto.MsgOpaqueData.EventLocation;return A.degreesLatitude!=null&&(t.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(t.degreesLongitude=Number(A.degreesLongitude)),A.name!=null&&(t.name=String(A.name)),A.address!=null&&(t.address=String(A.address)),A.url!=null&&(t.url=String(A.url)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?I.base64.decode(A.jpegThumbnail,t.jpegThumbnail=I.newBuffer(I.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(t.jpegThumbnail=A.jpegThumbnail)),t},i.toObject=function(A,t){t||(t={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=t.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,t.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=t.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,t.oneofs&&(s._degreesLongitude="degreesLongitude")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.address!=null&&A.hasOwnProperty("address")&&(s.address=A.address,t.oneofs&&(s._address="address")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=t.bytes===String?I.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):t.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,t.oneofs&&(s._jpegThumbnail="jpegThumbnail")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.EventLocation"},i})(),r.PollContentType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="TEXT"]=1,e[i[2]="IMAGE"]=2,e})(),r.PollOption=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.name=A.string();break}case 2:{c.hash=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.MsgOpaqueData.PollOption)return A;var t=new E.proto.MsgOpaqueData.PollOption;return A.name!=null&&(t.name=String(A.name)),A.hash!=null&&(t.hash=String(A.hash)),t},i.toObject=function(A,t){t||(t={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.hash!=null&&A.hasOwnProperty("hash")&&(s.hash=A.hash,t.oneofs&&(s._hash="hash")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.PollOption"},i})(),r.PollType=(function(){let i={},e=Object.create(i);return e[i[0]="POLL"]=0,e[i[1]="QUIZ"]=1,e})(),r.PollVoteSnapshot=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.option=E.proto.MsgOpaqueData.PollOption.decode(A,A.uint32());break}case 2:{c.optionVoteCount=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.MsgOpaqueData.PollVoteSnapshot)return A;var t=new E.proto.MsgOpaqueData.PollVoteSnapshot;if(A.option!=null){if(typeof A.option!="object")throw TypeError(".proto.MsgOpaqueData.PollVoteSnapshot.option: object expected");t.option=E.proto.MsgOpaqueData.PollOption.fromObject(A.option)}return A.optionVoteCount!=null&&(t.optionVoteCount=A.optionVoteCount|0),t},i.toObject=function(A,t){t||(t={});var s={};return A.option!=null&&A.hasOwnProperty("option")&&(s.option=E.proto.MsgOpaqueData.PollOption.toObject(A.option,t),t.oneofs&&(s._option="option")),A.optionVoteCount!=null&&A.hasOwnProperty("optionVoteCount")&&(s.optionVoteCount=A.optionVoteCount,t.oneofs&&(s._optionVoteCount="optionVoteCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.PollVoteSnapshot"},i})(),r.PollVotesSnapshot=(function(){function i(e){if(this.pollVotes=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.pollVotes&&g.pollVotes.length||(g.pollVotes=[]),g.pollVotes.push(E.proto.MsgOpaqueData.PollVoteSnapshot.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.MsgOpaqueData.PollVotesSnapshot)return a;var A=new E.proto.MsgOpaqueData.PollVotesSnapshot;if(a.pollVotes){if(!Array.isArray(a.pollVotes))throw TypeError(".proto.MsgOpaqueData.PollVotesSnapshot.pollVotes: array expected");A.pollVotes=[];for(var t=0;t>>3){case 1:{s.currentMsg=E.proto.MsgOpaqueData.decode(e,e.uint32());break}case 2:{s.quotedMsg=E.proto.MsgOpaqueData.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.MsgRowOpaqueData)return e;var a=new E.proto.MsgRowOpaqueData;if(e.currentMsg!=null){if(typeof e.currentMsg!="object")throw TypeError(".proto.MsgRowOpaqueData.currentMsg: object expected");a.currentMsg=E.proto.MsgOpaqueData.fromObject(e.currentMsg)}if(e.quotedMsg!=null){if(typeof e.quotedMsg!="object")throw TypeError(".proto.MsgRowOpaqueData.quotedMsg: object expected");a.quotedMsg=E.proto.MsgOpaqueData.fromObject(e.quotedMsg)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.currentMsg!=null&&e.hasOwnProperty("currentMsg")&&(A.currentMsg=E.proto.MsgOpaqueData.toObject(e.currentMsg,a),a.oneofs&&(A._currentMsg="currentMsg")),e.quotedMsg!=null&&e.hasOwnProperty("quotedMsg")&&(A.quotedMsg=E.proto.MsgOpaqueData.toObject(e.quotedMsg,a),a.oneofs&&(A._quotedMsg="quotedMsg")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MsgRowOpaqueData"},r})(),n.MutationProps=(function(){let r={},o=Object.create(r);return o[r[2]="STAR_ACTION"]=2,o[r[3]="CONTACT_ACTION"]=3,o[r[4]="MUTE_ACTION"]=4,o[r[5]="PIN_ACTION"]=5,o[r[6]="SECURITY_NOTIFICATION_SETTING"]=6,o[r[7]="PUSH_NAME_SETTING"]=7,o[r[8]="QUICK_REPLY_ACTION"]=8,o[r[11]="RECENT_EMOJI_WEIGHTS_ACTION"]=11,o[r[13]="LABEL_MESSAGE_ACTION"]=13,o[r[14]="LABEL_EDIT_ACTION"]=14,o[r[15]="LABEL_ASSOCIATION_ACTION"]=15,o[r[16]="LOCALE_SETTING"]=16,o[r[17]="ARCHIVE_CHAT_ACTION"]=17,o[r[18]="DELETE_MESSAGE_FOR_ME_ACTION"]=18,o[r[19]="KEY_EXPIRATION"]=19,o[r[20]="MARK_CHAT_AS_READ_ACTION"]=20,o[r[21]="CLEAR_CHAT_ACTION"]=21,o[r[22]="DELETE_CHAT_ACTION"]=22,o[r[23]="UNARCHIVE_CHATS_SETTING"]=23,o[r[24]="PRIMARY_FEATURE"]=24,o[r[26]="ANDROID_UNSUPPORTED_ACTIONS"]=26,o[r[27]="AGENT_ACTION"]=27,o[r[28]="SUBSCRIPTION_ACTION"]=28,o[r[29]="USER_STATUS_MUTE_ACTION"]=29,o[r[30]="TIME_FORMAT_ACTION"]=30,o[r[31]="NUX_ACTION"]=31,o[r[32]="PRIMARY_VERSION_ACTION"]=32,o[r[33]="STICKER_ACTION"]=33,o[r[34]="REMOVE_RECENT_STICKER_ACTION"]=34,o[r[35]="CHAT_ASSIGNMENT"]=35,o[r[36]="CHAT_ASSIGNMENT_OPENED_STATUS"]=36,o[r[37]="PN_FOR_LID_CHAT_ACTION"]=37,o[r[38]="MARKETING_MESSAGE_ACTION"]=38,o[r[39]="MARKETING_MESSAGE_BROADCAST_ACTION"]=39,o[r[40]="EXTERNAL_WEB_BETA_ACTION"]=40,o[r[41]="PRIVACY_SETTING_RELAY_ALL_CALLS"]=41,o[r[42]="CALL_LOG_ACTION"]=42,o[r[43]="UGC_BOT"]=43,o[r[44]="STATUS_PRIVACY"]=44,o[r[45]="BOT_WELCOME_REQUEST_ACTION"]=45,o[r[46]="DELETE_INDIVIDUAL_CALL_LOG"]=46,o[r[47]="LABEL_REORDERING_ACTION"]=47,o[r[48]="PAYMENT_INFO_ACTION"]=48,o[r[49]="CUSTOM_PAYMENT_METHODS_ACTION"]=49,o[r[50]="LOCK_CHAT_ACTION"]=50,o[r[51]="CHAT_LOCK_SETTINGS"]=51,o[r[52]="WAMO_USER_IDENTIFIER_ACTION"]=52,o[r[53]="PRIVACY_SETTING_DISABLE_LINK_PREVIEWS_ACTION"]=53,o[r[54]="DEVICE_CAPABILITIES"]=54,o[r[55]="NOTE_EDIT_ACTION"]=55,o[r[56]="FAVORITES_ACTION"]=56,o[r[57]="MERCHANT_PAYMENT_PARTNER_ACTION"]=57,o[r[58]="WAFFLE_ACCOUNT_LINK_STATE_ACTION"]=58,o[r[59]="USERNAME_CHAT_START_MODE"]=59,o[r[60]="NOTIFICATION_ACTIVITY_SETTING_ACTION"]=60,o[r[61]="LID_CONTACT_ACTION"]=61,o[r[62]="CTWA_PER_CUSTOMER_DATA_SHARING_ACTION"]=62,o[r[63]="PAYMENT_TOS_ACTION"]=63,o[r[64]="PRIVACY_SETTING_CHANNELS_PERSONALISED_RECOMMENDATION_ACTION"]=64,o[r[65]="BUSINESS_BROADCAST_ASSOCIATION_ACTION"]=65,o[r[66]="DETECTED_OUTCOMES_STATUS_ACTION"]=66,o[r[68]="MAIBA_AI_FEATURES_CONTROL_ACTION"]=68,o[r[69]="BUSINESS_BROADCAST_LIST_ACTION"]=69,o[r[70]="MUSIC_USER_ID_ACTION"]=70,o[r[71]="STATUS_POST_OPT_IN_NOTIFICATION_PREFERENCES_ACTION"]=71,o[r[72]="AVATAR_UPDATED_ACTION"]=72,o[r[73]="GALAXY_FLOW_ACTION"]=73,o[r[74]="PRIVATE_PROCESSING_SETTING_ACTION"]=74,o[r[75]="NEWSLETTER_SAVED_INTERESTS_ACTION"]=75,o[r[76]="AI_THREAD_RENAME_ACTION"]=76,o[r[77]="INTERACTIVE_MESSAGE_ACTION"]=77,o[r[10001]="SHARE_OWN_PN"]=10001,o[r[10002]="BUSINESS_BROADCAST_ACTION"]=10002,o})(),n.NoiseCertificate=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.signature=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.NoiseCertificate)return e;var a=new E.proto.NoiseCertificate;return e.details!=null&&(typeof e.details=="string"?I.base64.decode(e.details,a.details=I.newBuffer(I.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.signature!=null&&(typeof e.signature=="string"?I.base64.decode(e.signature,a.signature=I.newBuffer(I.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),a},r.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?I.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?I.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NoiseCertificate"},r.Details=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.serial=A.uint32();break}case 2:{c.issuer=A.string();break}case 3:{c.expires=A.uint64();break}case 4:{c.subject=A.string();break}case 5:{c.key=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.NoiseCertificate.Details)return A;var t=new E.proto.NoiseCertificate.Details;return A.serial!=null&&(t.serial=A.serial>>>0),A.issuer!=null&&(t.issuer=String(A.issuer)),A.expires!=null&&(I.Long?(t.expires=I.Long.fromValue(A.expires)).unsigned=!0:typeof A.expires=="string"?t.expires=parseInt(A.expires,10):typeof A.expires=="number"?t.expires=A.expires:typeof A.expires=="object"&&(t.expires=new I.LongBits(A.expires.low>>>0,A.expires.high>>>0).toNumber(!0))),A.subject!=null&&(t.subject=String(A.subject)),A.key!=null&&(typeof A.key=="string"?I.base64.decode(A.key,t.key=I.newBuffer(I.base64.length(A.key)),0):A.key.length>=0&&(t.key=A.key)),t},i.toObject=function(A,t){t||(t={});var s={};return A.serial!=null&&A.hasOwnProperty("serial")&&(s.serial=A.serial,t.oneofs&&(s._serial="serial")),A.issuer!=null&&A.hasOwnProperty("issuer")&&(s.issuer=A.issuer,t.oneofs&&(s._issuer="issuer")),A.expires!=null&&A.hasOwnProperty("expires")&&(typeof A.expires=="number"?s.expires=t.longs===String?String(A.expires):A.expires:s.expires=t.longs===String?re(A.expires,!0):t.longs===Number?ae(A.expires,!0):A.expires,t.oneofs&&(s._expires="expires")),A.subject!=null&&A.hasOwnProperty("subject")&&(s.subject=A.subject,t.oneofs&&(s._subject="subject")),A.key!=null&&A.hasOwnProperty("key")&&(s.key=t.bytes===String?I.base64.encode(A.key,0,A.key.length):t.bytes===Array?Array.prototype.slice.call(A.key):A.key,t.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.NoiseCertificate.Details"},i})(),r})(),n.NotificationMessageInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=E.proto.Message.decode(e,e.uint32());break}case 3:{s.messageTimestamp=e.uint64();break}case 4:{s.participant=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.NotificationMessageInfo)return e;var a=new E.proto.NotificationMessageInfo;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.NotificationMessageInfo.key: object expected");a.key=E.proto.MessageKey.fromObject(e.key)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.NotificationMessageInfo.message: object expected");a.message=E.proto.Message.fromObject(e.message)}return e.messageTimestamp!=null&&(I.Long?(a.messageTimestamp=I.Long.fromValue(e.messageTimestamp)).unsigned=!0:typeof e.messageTimestamp=="string"?a.messageTimestamp=parseInt(e.messageTimestamp,10):typeof e.messageTimestamp=="number"?a.messageTimestamp=e.messageTimestamp:typeof e.messageTimestamp=="object"&&(a.messageTimestamp=new I.LongBits(e.messageTimestamp.low>>>0,e.messageTimestamp.high>>>0).toNumber(!0))),e.participant!=null&&(a.participant=String(e.participant)),a},r.toObject=function(e,a){a||(a={});var A={};return e.key!=null&&e.hasOwnProperty("key")&&(A.key=E.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=E.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),e.messageTimestamp!=null&&e.hasOwnProperty("messageTimestamp")&&(typeof e.messageTimestamp=="number"?A.messageTimestamp=a.longs===String?String(e.messageTimestamp):e.messageTimestamp:A.messageTimestamp=a.longs===String?re(e.messageTimestamp,!0):a.longs===Number?ae(e.messageTimestamp,!0):e.messageTimestamp,a.oneofs&&(A._messageTimestamp="messageTimestamp")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NotificationMessageInfo"},r})(),n.NotificationSettings=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageVibrate=e.string();break}case 2:{s.messagePopup=e.string();break}case 3:{s.messageLight=e.string();break}case 4:{s.lowPriorityNotifications=e.bool();break}case 5:{s.reactionsMuted=e.bool();break}case 6:{s.callVibrate=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.NotificationSettings)return e;var a=new E.proto.NotificationSettings;return e.messageVibrate!=null&&(a.messageVibrate=String(e.messageVibrate)),e.messagePopup!=null&&(a.messagePopup=String(e.messagePopup)),e.messageLight!=null&&(a.messageLight=String(e.messageLight)),e.lowPriorityNotifications!=null&&(a.lowPriorityNotifications=!!e.lowPriorityNotifications),e.reactionsMuted!=null&&(a.reactionsMuted=!!e.reactionsMuted),e.callVibrate!=null&&(a.callVibrate=String(e.callVibrate)),a},r.toObject=function(e,a){a||(a={});var A={};return e.messageVibrate!=null&&e.hasOwnProperty("messageVibrate")&&(A.messageVibrate=e.messageVibrate,a.oneofs&&(A._messageVibrate="messageVibrate")),e.messagePopup!=null&&e.hasOwnProperty("messagePopup")&&(A.messagePopup=e.messagePopup,a.oneofs&&(A._messagePopup="messagePopup")),e.messageLight!=null&&e.hasOwnProperty("messageLight")&&(A.messageLight=e.messageLight,a.oneofs&&(A._messageLight="messageLight")),e.lowPriorityNotifications!=null&&e.hasOwnProperty("lowPriorityNotifications")&&(A.lowPriorityNotifications=e.lowPriorityNotifications,a.oneofs&&(A._lowPriorityNotifications="lowPriorityNotifications")),e.reactionsMuted!=null&&e.hasOwnProperty("reactionsMuted")&&(A.reactionsMuted=e.reactionsMuted,a.oneofs&&(A._reactionsMuted="reactionsMuted")),e.callVibrate!=null&&e.hasOwnProperty("callVibrate")&&(A.callVibrate=e.callVibrate,a.oneofs&&(A._callVibrate="callVibrate")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NotificationSettings"},r})(),n.PairingRequest=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.companionPublicKey=e.bytes();break}case 2:{s.companionIdentityKey=e.bytes();break}case 3:{s.advSecret=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PairingRequest)return e;var a=new E.proto.PairingRequest;return e.companionPublicKey!=null&&(typeof e.companionPublicKey=="string"?I.base64.decode(e.companionPublicKey,a.companionPublicKey=I.newBuffer(I.base64.length(e.companionPublicKey)),0):e.companionPublicKey.length>=0&&(a.companionPublicKey=e.companionPublicKey)),e.companionIdentityKey!=null&&(typeof e.companionIdentityKey=="string"?I.base64.decode(e.companionIdentityKey,a.companionIdentityKey=I.newBuffer(I.base64.length(e.companionIdentityKey)),0):e.companionIdentityKey.length>=0&&(a.companionIdentityKey=e.companionIdentityKey)),e.advSecret!=null&&(typeof e.advSecret=="string"?I.base64.decode(e.advSecret,a.advSecret=I.newBuffer(I.base64.length(e.advSecret)),0):e.advSecret.length>=0&&(a.advSecret=e.advSecret)),a},r.toObject=function(e,a){a||(a={});var A={};return e.companionPublicKey!=null&&e.hasOwnProperty("companionPublicKey")&&(A.companionPublicKey=a.bytes===String?I.base64.encode(e.companionPublicKey,0,e.companionPublicKey.length):a.bytes===Array?Array.prototype.slice.call(e.companionPublicKey):e.companionPublicKey,a.oneofs&&(A._companionPublicKey="companionPublicKey")),e.companionIdentityKey!=null&&e.hasOwnProperty("companionIdentityKey")&&(A.companionIdentityKey=a.bytes===String?I.base64.encode(e.companionIdentityKey,0,e.companionIdentityKey.length):a.bytes===Array?Array.prototype.slice.call(e.companionIdentityKey):e.companionIdentityKey,a.oneofs&&(A._companionIdentityKey="companionIdentityKey")),e.advSecret!=null&&e.hasOwnProperty("advSecret")&&(A.advSecret=a.bytes===String?I.base64.encode(e.advSecret,0,e.advSecret.length):a.bytes===Array?Array.prototype.slice.call(e.advSecret):e.advSecret,a.oneofs&&(A._advSecret="advSecret")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PairingRequest"},r})(),n.PastParticipant=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.leaveReason=e.int32();break}case 3:{s.leaveTs=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PastParticipant)return e;var a=new E.proto.PastParticipant;switch(e.userJid!=null&&(a.userJid=String(e.userJid)),e.leaveReason){default:if(typeof e.leaveReason=="number"){a.leaveReason=e.leaveReason;break}break;case"LEFT":case 0:a.leaveReason=0;break;case"REMOVED":case 1:a.leaveReason=1;break}return e.leaveTs!=null&&(I.Long?(a.leaveTs=I.Long.fromValue(e.leaveTs)).unsigned=!0:typeof e.leaveTs=="string"?a.leaveTs=parseInt(e.leaveTs,10):typeof e.leaveTs=="number"?a.leaveTs=e.leaveTs:typeof e.leaveTs=="object"&&(a.leaveTs=new I.LongBits(e.leaveTs.low>>>0,e.leaveTs.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};return e.userJid!=null&&e.hasOwnProperty("userJid")&&(A.userJid=e.userJid,a.oneofs&&(A._userJid="userJid")),e.leaveReason!=null&&e.hasOwnProperty("leaveReason")&&(A.leaveReason=a.enums===String?E.proto.PastParticipant.LeaveReason[e.leaveReason]===void 0?e.leaveReason:E.proto.PastParticipant.LeaveReason[e.leaveReason]:e.leaveReason,a.oneofs&&(A._leaveReason="leaveReason")),e.leaveTs!=null&&e.hasOwnProperty("leaveTs")&&(typeof e.leaveTs=="number"?A.leaveTs=a.longs===String?String(e.leaveTs):e.leaveTs:A.leaveTs=a.longs===String?re(e.leaveTs,!0):a.longs===Number?ae(e.leaveTs,!0):e.leaveTs,a.oneofs&&(A._leaveTs="leaveTs")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PastParticipant"},r.LeaveReason=(function(){let i={},e=Object.create(i);return e[i[0]="LEFT"]=0,e[i[1]="REMOVED"]=1,e})(),r})(),n.PastParticipants=(function(){function r(i){if(this.pastParticipants=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.groupJid=e.string();break}case 2:{s.pastParticipants&&s.pastParticipants.length||(s.pastParticipants=[]),s.pastParticipants.push(E.proto.PastParticipant.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PastParticipants)return e;var a=new E.proto.PastParticipants;if(e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.pastParticipants){if(!Array.isArray(e.pastParticipants))throw TypeError(".proto.PastParticipants.pastParticipants: array expected");a.pastParticipants=[];for(var A=0;A>>3){case 1:{s.currentLthash=e.bytes();break}case 2:{s.newLthash=e.bytes();break}case 3:{s.patchVersion=e.bytes();break}case 4:{s.collectionName=e.bytes();break}case 5:{s.firstFourBytesFromAHashOfSnapshotMacKey=e.bytes();break}case 6:{s.newLthashSubtract=e.bytes();break}case 7:{s.numberAdd=e.int32();break}case 8:{s.numberRemove=e.int32();break}case 9:{s.numberOverride=e.int32();break}case 10:{s.senderPlatform=e.int32();break}case 11:{s.isSenderPrimary=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PatchDebugData)return e;var a=new E.proto.PatchDebugData;switch(e.currentLthash!=null&&(typeof e.currentLthash=="string"?I.base64.decode(e.currentLthash,a.currentLthash=I.newBuffer(I.base64.length(e.currentLthash)),0):e.currentLthash.length>=0&&(a.currentLthash=e.currentLthash)),e.newLthash!=null&&(typeof e.newLthash=="string"?I.base64.decode(e.newLthash,a.newLthash=I.newBuffer(I.base64.length(e.newLthash)),0):e.newLthash.length>=0&&(a.newLthash=e.newLthash)),e.patchVersion!=null&&(typeof e.patchVersion=="string"?I.base64.decode(e.patchVersion,a.patchVersion=I.newBuffer(I.base64.length(e.patchVersion)),0):e.patchVersion.length>=0&&(a.patchVersion=e.patchVersion)),e.collectionName!=null&&(typeof e.collectionName=="string"?I.base64.decode(e.collectionName,a.collectionName=I.newBuffer(I.base64.length(e.collectionName)),0):e.collectionName.length>=0&&(a.collectionName=e.collectionName)),e.firstFourBytesFromAHashOfSnapshotMacKey!=null&&(typeof e.firstFourBytesFromAHashOfSnapshotMacKey=="string"?I.base64.decode(e.firstFourBytesFromAHashOfSnapshotMacKey,a.firstFourBytesFromAHashOfSnapshotMacKey=I.newBuffer(I.base64.length(e.firstFourBytesFromAHashOfSnapshotMacKey)),0):e.firstFourBytesFromAHashOfSnapshotMacKey.length>=0&&(a.firstFourBytesFromAHashOfSnapshotMacKey=e.firstFourBytesFromAHashOfSnapshotMacKey)),e.newLthashSubtract!=null&&(typeof e.newLthashSubtract=="string"?I.base64.decode(e.newLthashSubtract,a.newLthashSubtract=I.newBuffer(I.base64.length(e.newLthashSubtract)),0):e.newLthashSubtract.length>=0&&(a.newLthashSubtract=e.newLthashSubtract)),e.numberAdd!=null&&(a.numberAdd=e.numberAdd|0),e.numberRemove!=null&&(a.numberRemove=e.numberRemove|0),e.numberOverride!=null&&(a.numberOverride=e.numberOverride|0),e.senderPlatform){default:if(typeof e.senderPlatform=="number"){a.senderPlatform=e.senderPlatform;break}break;case"ANDROID":case 0:a.senderPlatform=0;break;case"SMBA":case 1:a.senderPlatform=1;break;case"IPHONE":case 2:a.senderPlatform=2;break;case"SMBI":case 3:a.senderPlatform=3;break;case"WEB":case 4:a.senderPlatform=4;break;case"UWP":case 5:a.senderPlatform=5;break;case"DARWIN":case 6:a.senderPlatform=6;break;case"IPAD":case 7:a.senderPlatform=7;break;case"WEAROS":case 8:a.senderPlatform=8;break;case"WASG":case 9:a.senderPlatform=9;break;case"WEARM":case 10:a.senderPlatform=10;break;case"CAPI":case 11:a.senderPlatform=11;break}return e.isSenderPrimary!=null&&(a.isSenderPrimary=!!e.isSenderPrimary),a},r.toObject=function(e,a){a||(a={});var A={};return e.currentLthash!=null&&e.hasOwnProperty("currentLthash")&&(A.currentLthash=a.bytes===String?I.base64.encode(e.currentLthash,0,e.currentLthash.length):a.bytes===Array?Array.prototype.slice.call(e.currentLthash):e.currentLthash,a.oneofs&&(A._currentLthash="currentLthash")),e.newLthash!=null&&e.hasOwnProperty("newLthash")&&(A.newLthash=a.bytes===String?I.base64.encode(e.newLthash,0,e.newLthash.length):a.bytes===Array?Array.prototype.slice.call(e.newLthash):e.newLthash,a.oneofs&&(A._newLthash="newLthash")),e.patchVersion!=null&&e.hasOwnProperty("patchVersion")&&(A.patchVersion=a.bytes===String?I.base64.encode(e.patchVersion,0,e.patchVersion.length):a.bytes===Array?Array.prototype.slice.call(e.patchVersion):e.patchVersion,a.oneofs&&(A._patchVersion="patchVersion")),e.collectionName!=null&&e.hasOwnProperty("collectionName")&&(A.collectionName=a.bytes===String?I.base64.encode(e.collectionName,0,e.collectionName.length):a.bytes===Array?Array.prototype.slice.call(e.collectionName):e.collectionName,a.oneofs&&(A._collectionName="collectionName")),e.firstFourBytesFromAHashOfSnapshotMacKey!=null&&e.hasOwnProperty("firstFourBytesFromAHashOfSnapshotMacKey")&&(A.firstFourBytesFromAHashOfSnapshotMacKey=a.bytes===String?I.base64.encode(e.firstFourBytesFromAHashOfSnapshotMacKey,0,e.firstFourBytesFromAHashOfSnapshotMacKey.length):a.bytes===Array?Array.prototype.slice.call(e.firstFourBytesFromAHashOfSnapshotMacKey):e.firstFourBytesFromAHashOfSnapshotMacKey,a.oneofs&&(A._firstFourBytesFromAHashOfSnapshotMacKey="firstFourBytesFromAHashOfSnapshotMacKey")),e.newLthashSubtract!=null&&e.hasOwnProperty("newLthashSubtract")&&(A.newLthashSubtract=a.bytes===String?I.base64.encode(e.newLthashSubtract,0,e.newLthashSubtract.length):a.bytes===Array?Array.prototype.slice.call(e.newLthashSubtract):e.newLthashSubtract,a.oneofs&&(A._newLthashSubtract="newLthashSubtract")),e.numberAdd!=null&&e.hasOwnProperty("numberAdd")&&(A.numberAdd=e.numberAdd,a.oneofs&&(A._numberAdd="numberAdd")),e.numberRemove!=null&&e.hasOwnProperty("numberRemove")&&(A.numberRemove=e.numberRemove,a.oneofs&&(A._numberRemove="numberRemove")),e.numberOverride!=null&&e.hasOwnProperty("numberOverride")&&(A.numberOverride=e.numberOverride,a.oneofs&&(A._numberOverride="numberOverride")),e.senderPlatform!=null&&e.hasOwnProperty("senderPlatform")&&(A.senderPlatform=a.enums===String?E.proto.PatchDebugData.Platform[e.senderPlatform]===void 0?e.senderPlatform:E.proto.PatchDebugData.Platform[e.senderPlatform]:e.senderPlatform,a.oneofs&&(A._senderPlatform="senderPlatform")),e.isSenderPrimary!=null&&e.hasOwnProperty("isSenderPrimary")&&(A.isSenderPrimary=e.isSenderPrimary,a.oneofs&&(A._isSenderPrimary="isSenderPrimary")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PatchDebugData"},r.Platform=(function(){let i={},e=Object.create(i);return e[i[0]="ANDROID"]=0,e[i[1]="SMBA"]=1,e[i[2]="IPHONE"]=2,e[i[3]="SMBI"]=3,e[i[4]="WEB"]=4,e[i[5]="UWP"]=5,e[i[6]="DARWIN"]=6,e[i[7]="IPAD"]=7,e[i[8]="WEAROS"]=8,e[i[9]="WASG"]=9,e[i[10]="WEARM"]=10,e[i[11]="CAPI"]=11,e})(),r})(),n.PaymentBackground=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.fileLength=e.uint64();break}case 3:{s.width=e.uint32();break}case 4:{s.height=e.uint32();break}case 5:{s.mimetype=e.string();break}case 6:{s.placeholderArgb=e.fixed32();break}case 7:{s.textArgb=e.fixed32();break}case 8:{s.subtextArgb=e.fixed32();break}case 9:{s.mediaData=E.proto.PaymentBackground.MediaData.decode(e,e.uint32());break}case 10:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PaymentBackground)return e;var a=new E.proto.PaymentBackground;if(e.id!=null&&(a.id=String(e.id)),e.fileLength!=null&&(I.Long?(a.fileLength=I.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new I.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.width!=null&&(a.width=e.width>>>0),e.height!=null&&(a.height=e.height>>>0),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.placeholderArgb!=null&&(a.placeholderArgb=e.placeholderArgb>>>0),e.textArgb!=null&&(a.textArgb=e.textArgb>>>0),e.subtextArgb!=null&&(a.subtextArgb=e.subtextArgb>>>0),e.mediaData!=null){if(typeof e.mediaData!="object")throw TypeError(".proto.PaymentBackground.mediaData: object expected");a.mediaData=E.proto.PaymentBackground.MediaData.fromObject(e.mediaData)}switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN":case 0:a.type=0;break;case"DEFAULT":case 1:a.type=1;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?re(e.fileLength,!0):a.longs===Number?ae(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),e.width!=null&&e.hasOwnProperty("width")&&(A.width=e.width,a.oneofs&&(A._width="width")),e.height!=null&&e.hasOwnProperty("height")&&(A.height=e.height,a.oneofs&&(A._height="height")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.placeholderArgb!=null&&e.hasOwnProperty("placeholderArgb")&&(A.placeholderArgb=e.placeholderArgb,a.oneofs&&(A._placeholderArgb="placeholderArgb")),e.textArgb!=null&&e.hasOwnProperty("textArgb")&&(A.textArgb=e.textArgb,a.oneofs&&(A._textArgb="textArgb")),e.subtextArgb!=null&&e.hasOwnProperty("subtextArgb")&&(A.subtextArgb=e.subtextArgb,a.oneofs&&(A._subtextArgb="subtextArgb")),e.mediaData!=null&&e.hasOwnProperty("mediaData")&&(A.mediaData=E.proto.PaymentBackground.MediaData.toObject(e.mediaData,a),a.oneofs&&(A._mediaData="mediaData")),e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?E.proto.PaymentBackground.Type[e.type]===void 0?e.type:E.proto.PaymentBackground.Type[e.type]:e.type,a.oneofs&&(A._type="type")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PaymentBackground"},r.MediaData=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.mediaKey=A.bytes();break}case 2:{c.mediaKeyTimestamp=A.int64();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.PaymentBackground.MediaData)return A;var t=new E.proto.PaymentBackground.MediaData;return A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(I.Long?(t.mediaKeyTimestamp=I.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?t.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?t.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(t.mediaKeyTimestamp=new I.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.fileSha256!=null&&(typeof A.fileSha256=="string"?I.base64.decode(A.fileSha256,t.fileSha256=I.newBuffer(I.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(t.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(t.directPath=String(A.directPath)),t},i.toObject=function(A,t){t||(t={});var s={};return A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=t.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=t.longs===String?re(A.mediaKeyTimestamp):t.longs===Number?ae(A.mediaKeyTimestamp):A.mediaKeyTimestamp,t.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=t.bytes===String?I.base64.encode(A.fileSha256,0,A.fileSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,t.oneofs&&(s._fileSha256="fileSha256")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,t.oneofs&&(s._directPath="directPath")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.PaymentBackground.MediaData"},i})(),r.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="DEFAULT"]=1,e})(),r})(),n.PaymentInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.currencyDeprecated=e.int32();break}case 2:{s.amount1000=e.uint64();break}case 3:{s.receiverJid=e.string();break}case 4:{s.status=e.int32();break}case 5:{s.transactionTimestamp=e.uint64();break}case 6:{s.requestMessageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 7:{s.expiryTimestamp=e.uint64();break}case 8:{s.futureproofed=e.bool();break}case 9:{s.currency=e.string();break}case 10:{s.txnStatus=e.int32();break}case 11:{s.useNoviFiatFormat=e.bool();break}case 12:{s.primaryAmount=E.proto.Money.decode(e,e.uint32());break}case 13:{s.exchangeAmount=E.proto.Money.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PaymentInfo)return e;var a=new E.proto.PaymentInfo;switch(e.currencyDeprecated){default:if(typeof e.currencyDeprecated=="number"){a.currencyDeprecated=e.currencyDeprecated;break}break;case"UNKNOWN_CURRENCY":case 0:a.currencyDeprecated=0;break;case"INR":case 1:a.currencyDeprecated=1;break}switch(e.amount1000!=null&&(I.Long?(a.amount1000=I.Long.fromValue(e.amount1000)).unsigned=!0:typeof e.amount1000=="string"?a.amount1000=parseInt(e.amount1000,10):typeof e.amount1000=="number"?a.amount1000=e.amount1000:typeof e.amount1000=="object"&&(a.amount1000=new I.LongBits(e.amount1000.low>>>0,e.amount1000.high>>>0).toNumber(!0))),e.receiverJid!=null&&(a.receiverJid=String(e.receiverJid)),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"UNKNOWN_STATUS":case 0:a.status=0;break;case"PROCESSING":case 1:a.status=1;break;case"SENT":case 2:a.status=2;break;case"NEED_TO_ACCEPT":case 3:a.status=3;break;case"COMPLETE":case 4:a.status=4;break;case"COULD_NOT_COMPLETE":case 5:a.status=5;break;case"REFUNDED":case 6:a.status=6;break;case"EXPIRED":case 7:a.status=7;break;case"REJECTED":case 8:a.status=8;break;case"CANCELLED":case 9:a.status=9;break;case"WAITING_FOR_PAYER":case 10:a.status=10;break;case"WAITING":case 11:a.status=11;break}if(e.transactionTimestamp!=null&&(I.Long?(a.transactionTimestamp=I.Long.fromValue(e.transactionTimestamp)).unsigned=!0:typeof e.transactionTimestamp=="string"?a.transactionTimestamp=parseInt(e.transactionTimestamp,10):typeof e.transactionTimestamp=="number"?a.transactionTimestamp=e.transactionTimestamp:typeof e.transactionTimestamp=="object"&&(a.transactionTimestamp=new I.LongBits(e.transactionTimestamp.low>>>0,e.transactionTimestamp.high>>>0).toNumber(!0))),e.requestMessageKey!=null){if(typeof e.requestMessageKey!="object")throw TypeError(".proto.PaymentInfo.requestMessageKey: object expected");a.requestMessageKey=E.proto.MessageKey.fromObject(e.requestMessageKey)}switch(e.expiryTimestamp!=null&&(I.Long?(a.expiryTimestamp=I.Long.fromValue(e.expiryTimestamp)).unsigned=!0:typeof e.expiryTimestamp=="string"?a.expiryTimestamp=parseInt(e.expiryTimestamp,10):typeof e.expiryTimestamp=="number"?a.expiryTimestamp=e.expiryTimestamp:typeof e.expiryTimestamp=="object"&&(a.expiryTimestamp=new I.LongBits(e.expiryTimestamp.low>>>0,e.expiryTimestamp.high>>>0).toNumber(!0))),e.futureproofed!=null&&(a.futureproofed=!!e.futureproofed),e.currency!=null&&(a.currency=String(e.currency)),e.txnStatus){default:if(typeof e.txnStatus=="number"){a.txnStatus=e.txnStatus;break}break;case"UNKNOWN":case 0:a.txnStatus=0;break;case"PENDING_SETUP":case 1:a.txnStatus=1;break;case"PENDING_RECEIVER_SETUP":case 2:a.txnStatus=2;break;case"INIT":case 3:a.txnStatus=3;break;case"SUCCESS":case 4:a.txnStatus=4;break;case"COMPLETED":case 5:a.txnStatus=5;break;case"FAILED":case 6:a.txnStatus=6;break;case"FAILED_RISK":case 7:a.txnStatus=7;break;case"FAILED_PROCESSING":case 8:a.txnStatus=8;break;case"FAILED_RECEIVER_PROCESSING":case 9:a.txnStatus=9;break;case"FAILED_DA":case 10:a.txnStatus=10;break;case"FAILED_DA_FINAL":case 11:a.txnStatus=11;break;case"REFUNDED_TXN":case 12:a.txnStatus=12;break;case"REFUND_FAILED":case 13:a.txnStatus=13;break;case"REFUND_FAILED_PROCESSING":case 14:a.txnStatus=14;break;case"REFUND_FAILED_DA":case 15:a.txnStatus=15;break;case"EXPIRED_TXN":case 16:a.txnStatus=16;break;case"AUTH_CANCELED":case 17:a.txnStatus=17;break;case"AUTH_CANCEL_FAILED_PROCESSING":case 18:a.txnStatus=18;break;case"AUTH_CANCEL_FAILED":case 19:a.txnStatus=19;break;case"COLLECT_INIT":case 20:a.txnStatus=20;break;case"COLLECT_SUCCESS":case 21:a.txnStatus=21;break;case"COLLECT_FAILED":case 22:a.txnStatus=22;break;case"COLLECT_FAILED_RISK":case 23:a.txnStatus=23;break;case"COLLECT_REJECTED":case 24:a.txnStatus=24;break;case"COLLECT_EXPIRED":case 25:a.txnStatus=25;break;case"COLLECT_CANCELED":case 26:a.txnStatus=26;break;case"COLLECT_CANCELLING":case 27:a.txnStatus=27;break;case"IN_REVIEW":case 28:a.txnStatus=28;break;case"REVERSAL_SUCCESS":case 29:a.txnStatus=29;break;case"REVERSAL_PENDING":case 30:a.txnStatus=30;break;case"REFUND_PENDING":case 31:a.txnStatus=31;break}if(e.useNoviFiatFormat!=null&&(a.useNoviFiatFormat=!!e.useNoviFiatFormat),e.primaryAmount!=null){if(typeof e.primaryAmount!="object")throw TypeError(".proto.PaymentInfo.primaryAmount: object expected");a.primaryAmount=E.proto.Money.fromObject(e.primaryAmount)}if(e.exchangeAmount!=null){if(typeof e.exchangeAmount!="object")throw TypeError(".proto.PaymentInfo.exchangeAmount: object expected");a.exchangeAmount=E.proto.Money.fromObject(e.exchangeAmount)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.currencyDeprecated!=null&&e.hasOwnProperty("currencyDeprecated")&&(A.currencyDeprecated=a.enums===String?E.proto.PaymentInfo.Currency[e.currencyDeprecated]===void 0?e.currencyDeprecated:E.proto.PaymentInfo.Currency[e.currencyDeprecated]:e.currencyDeprecated,a.oneofs&&(A._currencyDeprecated="currencyDeprecated")),e.amount1000!=null&&e.hasOwnProperty("amount1000")&&(typeof e.amount1000=="number"?A.amount1000=a.longs===String?String(e.amount1000):e.amount1000:A.amount1000=a.longs===String?re(e.amount1000,!0):a.longs===Number?ae(e.amount1000,!0):e.amount1000,a.oneofs&&(A._amount1000="amount1000")),e.receiverJid!=null&&e.hasOwnProperty("receiverJid")&&(A.receiverJid=e.receiverJid,a.oneofs&&(A._receiverJid="receiverJid")),e.status!=null&&e.hasOwnProperty("status")&&(A.status=a.enums===String?E.proto.PaymentInfo.Status[e.status]===void 0?e.status:E.proto.PaymentInfo.Status[e.status]:e.status,a.oneofs&&(A._status="status")),e.transactionTimestamp!=null&&e.hasOwnProperty("transactionTimestamp")&&(typeof e.transactionTimestamp=="number"?A.transactionTimestamp=a.longs===String?String(e.transactionTimestamp):e.transactionTimestamp:A.transactionTimestamp=a.longs===String?re(e.transactionTimestamp,!0):a.longs===Number?ae(e.transactionTimestamp,!0):e.transactionTimestamp,a.oneofs&&(A._transactionTimestamp="transactionTimestamp")),e.requestMessageKey!=null&&e.hasOwnProperty("requestMessageKey")&&(A.requestMessageKey=E.proto.MessageKey.toObject(e.requestMessageKey,a),a.oneofs&&(A._requestMessageKey="requestMessageKey")),e.expiryTimestamp!=null&&e.hasOwnProperty("expiryTimestamp")&&(typeof e.expiryTimestamp=="number"?A.expiryTimestamp=a.longs===String?String(e.expiryTimestamp):e.expiryTimestamp:A.expiryTimestamp=a.longs===String?re(e.expiryTimestamp,!0):a.longs===Number?ae(e.expiryTimestamp,!0):e.expiryTimestamp,a.oneofs&&(A._expiryTimestamp="expiryTimestamp")),e.futureproofed!=null&&e.hasOwnProperty("futureproofed")&&(A.futureproofed=e.futureproofed,a.oneofs&&(A._futureproofed="futureproofed")),e.currency!=null&&e.hasOwnProperty("currency")&&(A.currency=e.currency,a.oneofs&&(A._currency="currency")),e.txnStatus!=null&&e.hasOwnProperty("txnStatus")&&(A.txnStatus=a.enums===String?E.proto.PaymentInfo.TxnStatus[e.txnStatus]===void 0?e.txnStatus:E.proto.PaymentInfo.TxnStatus[e.txnStatus]:e.txnStatus,a.oneofs&&(A._txnStatus="txnStatus")),e.useNoviFiatFormat!=null&&e.hasOwnProperty("useNoviFiatFormat")&&(A.useNoviFiatFormat=e.useNoviFiatFormat,a.oneofs&&(A._useNoviFiatFormat="useNoviFiatFormat")),e.primaryAmount!=null&&e.hasOwnProperty("primaryAmount")&&(A.primaryAmount=E.proto.Money.toObject(e.primaryAmount,a),a.oneofs&&(A._primaryAmount="primaryAmount")),e.exchangeAmount!=null&&e.hasOwnProperty("exchangeAmount")&&(A.exchangeAmount=E.proto.Money.toObject(e.exchangeAmount,a),a.oneofs&&(A._exchangeAmount="exchangeAmount")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PaymentInfo"},r.Currency=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_CURRENCY"]=0,e[i[1]="INR"]=1,e})(),r.Status=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_STATUS"]=0,e[i[1]="PROCESSING"]=1,e[i[2]="SENT"]=2,e[i[3]="NEED_TO_ACCEPT"]=3,e[i[4]="COMPLETE"]=4,e[i[5]="COULD_NOT_COMPLETE"]=5,e[i[6]="REFUNDED"]=6,e[i[7]="EXPIRED"]=7,e[i[8]="REJECTED"]=8,e[i[9]="CANCELLED"]=9,e[i[10]="WAITING_FOR_PAYER"]=10,e[i[11]="WAITING"]=11,e})(),r.TxnStatus=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="PENDING_SETUP"]=1,e[i[2]="PENDING_RECEIVER_SETUP"]=2,e[i[3]="INIT"]=3,e[i[4]="SUCCESS"]=4,e[i[5]="COMPLETED"]=5,e[i[6]="FAILED"]=6,e[i[7]="FAILED_RISK"]=7,e[i[8]="FAILED_PROCESSING"]=8,e[i[9]="FAILED_RECEIVER_PROCESSING"]=9,e[i[10]="FAILED_DA"]=10,e[i[11]="FAILED_DA_FINAL"]=11,e[i[12]="REFUNDED_TXN"]=12,e[i[13]="REFUND_FAILED"]=13,e[i[14]="REFUND_FAILED_PROCESSING"]=14,e[i[15]="REFUND_FAILED_DA"]=15,e[i[16]="EXPIRED_TXN"]=16,e[i[17]="AUTH_CANCELED"]=17,e[i[18]="AUTH_CANCEL_FAILED_PROCESSING"]=18,e[i[19]="AUTH_CANCEL_FAILED"]=19,e[i[20]="COLLECT_INIT"]=20,e[i[21]="COLLECT_SUCCESS"]=21,e[i[22]="COLLECT_FAILED"]=22,e[i[23]="COLLECT_FAILED_RISK"]=23,e[i[24]="COLLECT_REJECTED"]=24,e[i[25]="COLLECT_EXPIRED"]=25,e[i[26]="COLLECT_CANCELED"]=26,e[i[27]="COLLECT_CANCELLING"]=27,e[i[28]="IN_REVIEW"]=28,e[i[29]="REVERSAL_SUCCESS"]=29,e[i[30]="REVERSAL_PENDING"]=30,e[i[31]="REFUND_PENDING"]=31,e})(),r})(),n.PhoneNumberToLIDMapping=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pnJid=e.string();break}case 2:{s.lidJid=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PhoneNumberToLIDMapping)return e;var a=new E.proto.PhoneNumberToLIDMapping;return e.pnJid!=null&&(a.pnJid=String(e.pnJid)),e.lidJid!=null&&(a.lidJid=String(e.lidJid)),a},r.toObject=function(e,a){a||(a={});var A={};return e.pnJid!=null&&e.hasOwnProperty("pnJid")&&(A.pnJid=e.pnJid,a.oneofs&&(A._pnJid="pnJid")),e.lidJid!=null&&e.hasOwnProperty("lidJid")&&(A.lidJid=e.lidJid,a.oneofs&&(A._lidJid="lidJid")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PhoneNumberToLIDMapping"},r})(),n.PhotoChange=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.oldPhoto=e.bytes();break}case 2:{s.newPhoto=e.bytes();break}case 3:{s.newPhotoId=e.uint32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PhotoChange)return e;var a=new E.proto.PhotoChange;return e.oldPhoto!=null&&(typeof e.oldPhoto=="string"?I.base64.decode(e.oldPhoto,a.oldPhoto=I.newBuffer(I.base64.length(e.oldPhoto)),0):e.oldPhoto.length>=0&&(a.oldPhoto=e.oldPhoto)),e.newPhoto!=null&&(typeof e.newPhoto=="string"?I.base64.decode(e.newPhoto,a.newPhoto=I.newBuffer(I.base64.length(e.newPhoto)),0):e.newPhoto.length>=0&&(a.newPhoto=e.newPhoto)),e.newPhotoId!=null&&(a.newPhotoId=e.newPhotoId>>>0),a},r.toObject=function(e,a){a||(a={});var A={};return e.oldPhoto!=null&&e.hasOwnProperty("oldPhoto")&&(A.oldPhoto=a.bytes===String?I.base64.encode(e.oldPhoto,0,e.oldPhoto.length):a.bytes===Array?Array.prototype.slice.call(e.oldPhoto):e.oldPhoto,a.oneofs&&(A._oldPhoto="oldPhoto")),e.newPhoto!=null&&e.hasOwnProperty("newPhoto")&&(A.newPhoto=a.bytes===String?I.base64.encode(e.newPhoto,0,e.newPhoto.length):a.bytes===Array?Array.prototype.slice.call(e.newPhoto):e.newPhoto,a.oneofs&&(A._newPhoto="newPhoto")),e.newPhotoId!=null&&e.hasOwnProperty("newPhotoId")&&(A.newPhotoId=e.newPhotoId,a.oneofs&&(A._newPhotoId="newPhotoId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PhotoChange"},r})(),n.PinInChat=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.key=E.proto.MessageKey.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.messageAddOnContextInfo=E.proto.MessageAddOnContextInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PinInChat)return e;var a=new E.proto.PinInChat;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN_TYPE":case 0:a.type=0;break;case"PIN_FOR_ALL":case 1:a.type=1;break;case"UNPIN_FOR_ALL":case 2:a.type=2;break}if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.PinInChat.key: object expected");a.key=E.proto.MessageKey.fromObject(e.key)}if(e.senderTimestampMs!=null&&(I.Long?(a.senderTimestampMs=I.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new I.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(I.Long?(a.serverTimestampMs=I.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new I.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.messageAddOnContextInfo!=null){if(typeof e.messageAddOnContextInfo!="object")throw TypeError(".proto.PinInChat.messageAddOnContextInfo: object expected");a.messageAddOnContextInfo=E.proto.MessageAddOnContextInfo.fromObject(e.messageAddOnContextInfo)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?E.proto.PinInChat.Type[e.type]===void 0?e.type:E.proto.PinInChat.Type[e.type]:e.type,a.oneofs&&(A._type="type")),e.key!=null&&e.hasOwnProperty("key")&&(A.key=E.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?re(e.senderTimestampMs):a.longs===Number?ae(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?re(e.serverTimestampMs):a.longs===Number?ae(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.messageAddOnContextInfo!=null&&e.hasOwnProperty("messageAddOnContextInfo")&&(A.messageAddOnContextInfo=E.proto.MessageAddOnContextInfo.toObject(e.messageAddOnContextInfo,a),a.oneofs&&(A._messageAddOnContextInfo="messageAddOnContextInfo")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PinInChat"},r.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="PIN_FOR_ALL"]=1,e[i[2]="UNPIN_FOR_ALL"]=2,e})(),r})(),n.Point=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.xDeprecated=e.int32();break}case 2:{s.yDeprecated=e.int32();break}case 3:{s.x=e.double();break}case 4:{s.y=e.double();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Point)return e;var a=new E.proto.Point;return e.xDeprecated!=null&&(a.xDeprecated=e.xDeprecated|0),e.yDeprecated!=null&&(a.yDeprecated=e.yDeprecated|0),e.x!=null&&(a.x=Number(e.x)),e.y!=null&&(a.y=Number(e.y)),a},r.toObject=function(e,a){a||(a={});var A={};return e.xDeprecated!=null&&e.hasOwnProperty("xDeprecated")&&(A.xDeprecated=e.xDeprecated,a.oneofs&&(A._xDeprecated="xDeprecated")),e.yDeprecated!=null&&e.hasOwnProperty("yDeprecated")&&(A.yDeprecated=e.yDeprecated,a.oneofs&&(A._yDeprecated="yDeprecated")),e.x!=null&&e.hasOwnProperty("x")&&(A.x=a.json&&!isFinite(e.x)?String(e.x):e.x,a.oneofs&&(A._x="x")),e.y!=null&&e.hasOwnProperty("y")&&(A.y=a.json&&!isFinite(e.y)?String(e.y):e.y,a.oneofs&&(A._y="y")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Point"},r})(),n.PollAdditionalMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pollInvalidated=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PollAdditionalMetadata)return e;var a=new E.proto.PollAdditionalMetadata;return e.pollInvalidated!=null&&(a.pollInvalidated=!!e.pollInvalidated),a},r.toObject=function(e,a){a||(a={});var A={};return e.pollInvalidated!=null&&e.hasOwnProperty("pollInvalidated")&&(A.pollInvalidated=e.pollInvalidated,a.oneofs&&(A._pollInvalidated="pollInvalidated")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollAdditionalMetadata"},r})(),n.PollEncValue=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encPayload=e.bytes();break}case 2:{s.encIv=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PollEncValue)return e;var a=new E.proto.PollEncValue;return e.encPayload!=null&&(typeof e.encPayload=="string"?I.base64.decode(e.encPayload,a.encPayload=I.newBuffer(I.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),e.encIv!=null&&(typeof e.encIv=="string"?I.base64.decode(e.encIv,a.encIv=I.newBuffer(I.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),a},r.toObject=function(e,a){a||(a={});var A={};return e.encPayload!=null&&e.hasOwnProperty("encPayload")&&(A.encPayload=a.bytes===String?I.base64.encode(e.encPayload,0,e.encPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encPayload):e.encPayload,a.oneofs&&(A._encPayload="encPayload")),e.encIv!=null&&e.hasOwnProperty("encIv")&&(A.encIv=a.bytes===String?I.base64.encode(e.encIv,0,e.encIv.length):a.bytes===Array?Array.prototype.slice.call(e.encIv):e.encIv,a.oneofs&&(A._encIv="encIv")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollEncValue"},r})(),n.PollUpdate=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pollUpdateMessageKey=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.vote=E.proto.Message.PollVoteMessage.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PollUpdate)return e;var a=new E.proto.PollUpdate;if(e.pollUpdateMessageKey!=null){if(typeof e.pollUpdateMessageKey!="object")throw TypeError(".proto.PollUpdate.pollUpdateMessageKey: object expected");a.pollUpdateMessageKey=E.proto.MessageKey.fromObject(e.pollUpdateMessageKey)}if(e.vote!=null){if(typeof e.vote!="object")throw TypeError(".proto.PollUpdate.vote: object expected");a.vote=E.proto.Message.PollVoteMessage.fromObject(e.vote)}return e.senderTimestampMs!=null&&(I.Long?(a.senderTimestampMs=I.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new I.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(I.Long?(a.serverTimestampMs=I.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new I.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.unread!=null&&(a.unread=!!e.unread),a},r.toObject=function(e,a){a||(a={});var A={};return e.pollUpdateMessageKey!=null&&e.hasOwnProperty("pollUpdateMessageKey")&&(A.pollUpdateMessageKey=E.proto.MessageKey.toObject(e.pollUpdateMessageKey,a),a.oneofs&&(A._pollUpdateMessageKey="pollUpdateMessageKey")),e.vote!=null&&e.hasOwnProperty("vote")&&(A.vote=E.proto.Message.PollVoteMessage.toObject(e.vote,a),a.oneofs&&(A._vote="vote")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?re(e.senderTimestampMs):a.longs===Number?ae(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?re(e.serverTimestampMs):a.longs===Number?ae(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollUpdate"},r})(),n.PreKeyRecordStructure=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.publicKey=e.bytes();break}case 3:{s.privateKey=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PreKeyRecordStructure)return e;var a=new E.proto.PreKeyRecordStructure;return e.id!=null&&(a.id=e.id>>>0),e.publicKey!=null&&(typeof e.publicKey=="string"?I.base64.decode(e.publicKey,a.publicKey=I.newBuffer(I.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?I.base64.decode(e.privateKey,a.privateKey=I.newBuffer(I.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?I.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?I.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PreKeyRecordStructure"},r})(),n.PreKeySignalMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 5:{s.registrationId=e.uint32();break}case 1:{s.preKeyId=e.uint32();break}case 6:{s.signedPreKeyId=e.uint32();break}case 2:{s.baseKey=e.bytes();break}case 3:{s.identityKey=e.bytes();break}case 4:{s.message=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PreKeySignalMessage)return e;var a=new E.proto.PreKeySignalMessage;return e.registrationId!=null&&(a.registrationId=e.registrationId>>>0),e.preKeyId!=null&&(a.preKeyId=e.preKeyId>>>0),e.signedPreKeyId!=null&&(a.signedPreKeyId=e.signedPreKeyId>>>0),e.baseKey!=null&&(typeof e.baseKey=="string"?I.base64.decode(e.baseKey,a.baseKey=I.newBuffer(I.base64.length(e.baseKey)),0):e.baseKey.length>=0&&(a.baseKey=e.baseKey)),e.identityKey!=null&&(typeof e.identityKey=="string"?I.base64.decode(e.identityKey,a.identityKey=I.newBuffer(I.base64.length(e.identityKey)),0):e.identityKey.length>=0&&(a.identityKey=e.identityKey)),e.message!=null&&(typeof e.message=="string"?I.base64.decode(e.message,a.message=I.newBuffer(I.base64.length(e.message)),0):e.message.length>=0&&(a.message=e.message)),a},r.toObject=function(e,a){a||(a={});var A={};return e.preKeyId!=null&&e.hasOwnProperty("preKeyId")&&(A.preKeyId=e.preKeyId,a.oneofs&&(A._preKeyId="preKeyId")),e.baseKey!=null&&e.hasOwnProperty("baseKey")&&(A.baseKey=a.bytes===String?I.base64.encode(e.baseKey,0,e.baseKey.length):a.bytes===Array?Array.prototype.slice.call(e.baseKey):e.baseKey,a.oneofs&&(A._baseKey="baseKey")),e.identityKey!=null&&e.hasOwnProperty("identityKey")&&(A.identityKey=a.bytes===String?I.base64.encode(e.identityKey,0,e.identityKey.length):a.bytes===Array?Array.prototype.slice.call(e.identityKey):e.identityKey,a.oneofs&&(A._identityKey="identityKey")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=a.bytes===String?I.base64.encode(e.message,0,e.message.length):a.bytes===Array?Array.prototype.slice.call(e.message):e.message,a.oneofs&&(A._message="message")),e.registrationId!=null&&e.hasOwnProperty("registrationId")&&(A.registrationId=e.registrationId,a.oneofs&&(A._registrationId="registrationId")),e.signedPreKeyId!=null&&e.hasOwnProperty("signedPreKeyId")&&(A.signedPreKeyId=e.signedPreKeyId,a.oneofs&&(A._signedPreKeyId="signedPreKeyId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PreKeySignalMessage"},r})(),n.PremiumMessageInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.serverCampaignId=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PremiumMessageInfo)return e;var a=new E.proto.PremiumMessageInfo;return e.serverCampaignId!=null&&(a.serverCampaignId=String(e.serverCampaignId)),a},r.toObject=function(e,a){a||(a={});var A={};return e.serverCampaignId!=null&&e.hasOwnProperty("serverCampaignId")&&(A.serverCampaignId=e.serverCampaignId,a.oneofs&&(A._serverCampaignId="serverCampaignId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PremiumMessageInfo"},r})(),n.PrimaryEphemeralIdentity=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.nonce=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.PrimaryEphemeralIdentity)return e;var a=new E.proto.PrimaryEphemeralIdentity;return e.publicKey!=null&&(typeof e.publicKey=="string"?I.base64.decode(e.publicKey,a.publicKey=I.newBuffer(I.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.nonce!=null&&(typeof e.nonce=="string"?I.base64.decode(e.nonce,a.nonce=I.newBuffer(I.base64.length(e.nonce)),0):e.nonce.length>=0&&(a.nonce=e.nonce)),a},r.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?I.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.nonce!=null&&e.hasOwnProperty("nonce")&&(A.nonce=a.bytes===String?I.base64.encode(e.nonce,0,e.nonce.length):a.bytes===Array?Array.prototype.slice.call(e.nonce):e.nonce,a.oneofs&&(A._nonce="nonce")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PrimaryEphemeralIdentity"},r})(),n.PrivacySystemMessage=(function(){let r={},o=Object.create(r);return o[r[1]="E2EE_MSG"]=1,o[r[2]="NE2EE_SELF"]=2,o[r[3]="NE2EE_OTHER"]=3,o})(),n.ProcessedVideo=(function(){function r(i){if(this.capabilities=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.directPath=e.string();break}case 2:{s.fileSha256=e.bytes();break}case 3:{s.height=e.uint32();break}case 4:{s.width=e.uint32();break}case 5:{s.fileLength=e.uint64();break}case 6:{s.bitrate=e.uint32();break}case 7:{s.quality=e.int32();break}case 8:{s.capabilities&&s.capabilities.length||(s.capabilities=[]),s.capabilities.push(e.string());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ProcessedVideo)return e;var a=new E.proto.ProcessedVideo;switch(e.directPath!=null&&(a.directPath=String(e.directPath)),e.fileSha256!=null&&(typeof e.fileSha256=="string"?I.base64.decode(e.fileSha256,a.fileSha256=I.newBuffer(I.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.height!=null&&(a.height=e.height>>>0),e.width!=null&&(a.width=e.width>>>0),e.fileLength!=null&&(I.Long?(a.fileLength=I.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new I.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.bitrate!=null&&(a.bitrate=e.bitrate>>>0),e.quality){default:if(typeof e.quality=="number"){a.quality=e.quality;break}break;case"UNDEFINED":case 0:a.quality=0;break;case"LOW":case 1:a.quality=1;break;case"MID":case 2:a.quality=2;break;case"HIGH":case 3:a.quality=3;break}if(e.capabilities){if(!Array.isArray(e.capabilities))throw TypeError(".proto.ProcessedVideo.capabilities: array expected");a.capabilities=[];for(var A=0;A>>3){case 1:{s.companionEphemeralIdentity=e.bytes();break}case 2:{s.commitment=E.proto.CompanionCommitment.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ProloguePayload)return e;var a=new E.proto.ProloguePayload;if(e.companionEphemeralIdentity!=null&&(typeof e.companionEphemeralIdentity=="string"?I.base64.decode(e.companionEphemeralIdentity,a.companionEphemeralIdentity=I.newBuffer(I.base64.length(e.companionEphemeralIdentity)),0):e.companionEphemeralIdentity.length>=0&&(a.companionEphemeralIdentity=e.companionEphemeralIdentity)),e.commitment!=null){if(typeof e.commitment!="object")throw TypeError(".proto.ProloguePayload.commitment: object expected");a.commitment=E.proto.CompanionCommitment.fromObject(e.commitment)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.companionEphemeralIdentity!=null&&e.hasOwnProperty("companionEphemeralIdentity")&&(A.companionEphemeralIdentity=a.bytes===String?I.base64.encode(e.companionEphemeralIdentity,0,e.companionEphemeralIdentity.length):a.bytes===Array?Array.prototype.slice.call(e.companionEphemeralIdentity):e.companionEphemeralIdentity,a.oneofs&&(A._companionEphemeralIdentity="companionEphemeralIdentity")),e.commitment!=null&&e.hasOwnProperty("commitment")&&(A.commitment=E.proto.CompanionCommitment.toObject(e.commitment,a),a.oneofs&&(A._commitment="commitment")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ProloguePayload"},r})(),n.Pushname=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.pushname=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Pushname)return e;var a=new E.proto.Pushname;return e.id!=null&&(a.id=String(e.id)),e.pushname!=null&&(a.pushname=String(e.pushname)),a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.pushname!=null&&e.hasOwnProperty("pushname")&&(A.pushname=e.pushname,a.oneofs&&(A._pushname="pushname")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Pushname"},r})(),n.QuarantinedMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.originalData=e.bytes();break}case 2:{s.extractedText=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.QuarantinedMessage)return e;var a=new E.proto.QuarantinedMessage;return e.originalData!=null&&(typeof e.originalData=="string"?I.base64.decode(e.originalData,a.originalData=I.newBuffer(I.base64.length(e.originalData)),0):e.originalData.length>=0&&(a.originalData=e.originalData)),e.extractedText!=null&&(a.extractedText=String(e.extractedText)),a},r.toObject=function(e,a){a||(a={});var A={};return e.originalData!=null&&e.hasOwnProperty("originalData")&&(A.originalData=a.bytes===String?I.base64.encode(e.originalData,0,e.originalData.length):a.bytes===Array?Array.prototype.slice.call(e.originalData):e.originalData,a.oneofs&&(A._originalData="originalData")),e.extractedText!=null&&e.hasOwnProperty("extractedText")&&(A.extractedText=e.extractedText,a.oneofs&&(A._extractedText="extractedText")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.QuarantinedMessage"},r})(),n.Reaction=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.text=e.string();break}case 3:{s.groupingKey=e.string();break}case 4:{s.senderTimestampMs=e.int64();break}case 5:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Reaction)return e;var a=new E.proto.Reaction;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.Reaction.key: object expected");a.key=E.proto.MessageKey.fromObject(e.key)}return e.text!=null&&(a.text=String(e.text)),e.groupingKey!=null&&(a.groupingKey=String(e.groupingKey)),e.senderTimestampMs!=null&&(I.Long?(a.senderTimestampMs=I.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new I.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.unread!=null&&(a.unread=!!e.unread),a},r.toObject=function(e,a){a||(a={});var A={};return e.key!=null&&e.hasOwnProperty("key")&&(A.key=E.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),e.groupingKey!=null&&e.hasOwnProperty("groupingKey")&&(A.groupingKey=e.groupingKey,a.oneofs&&(A._groupingKey="groupingKey")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?re(e.senderTimestampMs):a.longs===Number?ae(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Reaction"},r})(),n.RecentEmojiWeight=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.emoji=e.string();break}case 2:{s.weight=e.float();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.RecentEmojiWeight)return e;var a=new E.proto.RecentEmojiWeight;return e.emoji!=null&&(a.emoji=String(e.emoji)),e.weight!=null&&(a.weight=Number(e.weight)),a},r.toObject=function(e,a){a||(a={});var A={};return e.emoji!=null&&e.hasOwnProperty("emoji")&&(A.emoji=e.emoji,a.oneofs&&(A._emoji="emoji")),e.weight!=null&&e.hasOwnProperty("weight")&&(A.weight=a.json&&!isFinite(e.weight)?String(e.weight):e.weight,a.oneofs&&(A._weight="weight")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.RecentEmojiWeight"},r})(),n.RecordStructure=(function(){function r(i){if(this.previousSessions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.currentSession=E.proto.SessionStructure.decode(e,e.uint32());break}case 2:{s.previousSessions&&s.previousSessions.length||(s.previousSessions=[]),s.previousSessions.push(E.proto.SessionStructure.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.RecordStructure)return e;var a=new E.proto.RecordStructure;if(e.currentSession!=null){if(typeof e.currentSession!="object")throw TypeError(".proto.RecordStructure.currentSession: object expected");a.currentSession=E.proto.SessionStructure.fromObject(e.currentSession)}if(e.previousSessions){if(!Array.isArray(e.previousSessions))throw TypeError(".proto.RecordStructure.previousSessions: array expected");a.previousSessions=[];for(var A=0;A>>3){case 1:{s.minVersion=e.uint32();break}case 2:{s.maxVersion=e.uint32();break}case 3:{s.notReportableMinVersion=e.uint32();break}case 4:{s.never=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.Reportable)return e;var a=new E.proto.Reportable;return e.minVersion!=null&&(a.minVersion=e.minVersion>>>0),e.maxVersion!=null&&(a.maxVersion=e.maxVersion>>>0),e.notReportableMinVersion!=null&&(a.notReportableMinVersion=e.notReportableMinVersion>>>0),e.never!=null&&(a.never=!!e.never),a},r.toObject=function(e,a){a||(a={});var A={};return e.minVersion!=null&&e.hasOwnProperty("minVersion")&&(A.minVersion=e.minVersion,a.oneofs&&(A._minVersion="minVersion")),e.maxVersion!=null&&e.hasOwnProperty("maxVersion")&&(A.maxVersion=e.maxVersion,a.oneofs&&(A._maxVersion="maxVersion")),e.notReportableMinVersion!=null&&e.hasOwnProperty("notReportableMinVersion")&&(A.notReportableMinVersion=e.notReportableMinVersion,a.oneofs&&(A._notReportableMinVersion="notReportableMinVersion")),e.never!=null&&e.hasOwnProperty("never")&&(A.never=e.never,a.oneofs&&(A._never="never")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Reportable"},r})(),n.ReportingTokenInfo=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.reportingTag=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ReportingTokenInfo)return e;var a=new E.proto.ReportingTokenInfo;return e.reportingTag!=null&&(typeof e.reportingTag=="string"?I.base64.decode(e.reportingTag,a.reportingTag=I.newBuffer(I.base64.length(e.reportingTag)),0):e.reportingTag.length>=0&&(a.reportingTag=e.reportingTag)),a},r.toObject=function(e,a){a||(a={});var A={};return e.reportingTag!=null&&e.hasOwnProperty("reportingTag")&&(A.reportingTag=a.bytes===String?I.base64.encode(e.reportingTag,0,e.reportingTag.length):a.bytes===Array?Array.prototype.slice.call(e.reportingTag):e.reportingTag,a.oneofs&&(A._reportingTag="reportingTag")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ReportingTokenInfo"},r})(),n.SenderKeyDistributionMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.iteration=e.uint32();break}case 3:{s.chainKey=e.bytes();break}case 4:{s.signingKey=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SenderKeyDistributionMessage)return e;var a=new E.proto.SenderKeyDistributionMessage;return e.id!=null&&(a.id=e.id>>>0),e.iteration!=null&&(a.iteration=e.iteration>>>0),e.chainKey!=null&&(typeof e.chainKey=="string"?I.base64.decode(e.chainKey,a.chainKey=I.newBuffer(I.base64.length(e.chainKey)),0):e.chainKey.length>=0&&(a.chainKey=e.chainKey)),e.signingKey!=null&&(typeof e.signingKey=="string"?I.base64.decode(e.signingKey,a.signingKey=I.newBuffer(I.base64.length(e.signingKey)),0):e.signingKey.length>=0&&(a.signingKey=e.signingKey)),a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.iteration!=null&&e.hasOwnProperty("iteration")&&(A.iteration=e.iteration,a.oneofs&&(A._iteration="iteration")),e.chainKey!=null&&e.hasOwnProperty("chainKey")&&(A.chainKey=a.bytes===String?I.base64.encode(e.chainKey,0,e.chainKey.length):a.bytes===Array?Array.prototype.slice.call(e.chainKey):e.chainKey,a.oneofs&&(A._chainKey="chainKey")),e.signingKey!=null&&e.hasOwnProperty("signingKey")&&(A.signingKey=a.bytes===String?I.base64.encode(e.signingKey,0,e.signingKey.length):a.bytes===Array?Array.prototype.slice.call(e.signingKey):e.signingKey,a.oneofs&&(A._signingKey="signingKey")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SenderKeyDistributionMessage"},r})(),n.SenderKeyMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.iteration=e.uint32();break}case 3:{s.ciphertext=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SenderKeyMessage)return e;var a=new E.proto.SenderKeyMessage;return e.id!=null&&(a.id=e.id>>>0),e.iteration!=null&&(a.iteration=e.iteration>>>0),e.ciphertext!=null&&(typeof e.ciphertext=="string"?I.base64.decode(e.ciphertext,a.ciphertext=I.newBuffer(I.base64.length(e.ciphertext)),0):e.ciphertext.length>=0&&(a.ciphertext=e.ciphertext)),a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.iteration!=null&&e.hasOwnProperty("iteration")&&(A.iteration=e.iteration,a.oneofs&&(A._iteration="iteration")),e.ciphertext!=null&&e.hasOwnProperty("ciphertext")&&(A.ciphertext=a.bytes===String?I.base64.encode(e.ciphertext,0,e.ciphertext.length):a.bytes===Array?Array.prototype.slice.call(e.ciphertext):e.ciphertext,a.oneofs&&(A._ciphertext="ciphertext")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SenderKeyMessage"},r})(),n.SenderKeyRecordStructure=(function(){function r(o){if(this.senderKeyStates=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.senderKeyStates&&t.senderKeyStates.length||(t.senderKeyStates=[]),t.senderKeyStates.push(E.proto.SenderKeyStateStructure.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.SenderKeyRecordStructure)return i;var e=new E.proto.SenderKeyRecordStructure;if(i.senderKeyStates){if(!Array.isArray(i.senderKeyStates))throw TypeError(".proto.SenderKeyRecordStructure.senderKeyStates: array expected");e.senderKeyStates=[];for(var a=0;a>>3){case 1:{s.senderKeyId=e.uint32();break}case 2:{s.senderChainKey=E.proto.SenderKeyStateStructure.SenderChainKey.decode(e,e.uint32());break}case 3:{s.senderSigningKey=E.proto.SenderKeyStateStructure.SenderSigningKey.decode(e,e.uint32());break}case 4:{s.senderMessageKeys&&s.senderMessageKeys.length||(s.senderMessageKeys=[]),s.senderMessageKeys.push(E.proto.SenderKeyStateStructure.SenderMessageKey.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SenderKeyStateStructure)return e;var a=new E.proto.SenderKeyStateStructure;if(e.senderKeyId!=null&&(a.senderKeyId=e.senderKeyId>>>0),e.senderChainKey!=null){if(typeof e.senderChainKey!="object")throw TypeError(".proto.SenderKeyStateStructure.senderChainKey: object expected");a.senderChainKey=E.proto.SenderKeyStateStructure.SenderChainKey.fromObject(e.senderChainKey)}if(e.senderSigningKey!=null){if(typeof e.senderSigningKey!="object")throw TypeError(".proto.SenderKeyStateStructure.senderSigningKey: object expected");a.senderSigningKey=E.proto.SenderKeyStateStructure.SenderSigningKey.fromObject(e.senderSigningKey)}if(e.senderMessageKeys){if(!Array.isArray(e.senderMessageKeys))throw TypeError(".proto.SenderKeyStateStructure.senderMessageKeys: array expected");a.senderMessageKeys=[];for(var A=0;A>>3){case 1:{c.iteration=A.uint32();break}case 2:{c.seed=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SenderKeyStateStructure.SenderChainKey)return A;var t=new E.proto.SenderKeyStateStructure.SenderChainKey;return A.iteration!=null&&(t.iteration=A.iteration>>>0),A.seed!=null&&(typeof A.seed=="string"?I.base64.decode(A.seed,t.seed=I.newBuffer(I.base64.length(A.seed)),0):A.seed.length>=0&&(t.seed=A.seed)),t},i.toObject=function(A,t){t||(t={});var s={};return A.iteration!=null&&A.hasOwnProperty("iteration")&&(s.iteration=A.iteration,t.oneofs&&(s._iteration="iteration")),A.seed!=null&&A.hasOwnProperty("seed")&&(s.seed=t.bytes===String?I.base64.encode(A.seed,0,A.seed.length):t.bytes===Array?Array.prototype.slice.call(A.seed):A.seed,t.oneofs&&(s._seed="seed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderChainKey"},i})(),r.SenderMessageKey=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.iteration=A.uint32();break}case 2:{c.seed=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SenderKeyStateStructure.SenderMessageKey)return A;var t=new E.proto.SenderKeyStateStructure.SenderMessageKey;return A.iteration!=null&&(t.iteration=A.iteration>>>0),A.seed!=null&&(typeof A.seed=="string"?I.base64.decode(A.seed,t.seed=I.newBuffer(I.base64.length(A.seed)),0):A.seed.length>=0&&(t.seed=A.seed)),t},i.toObject=function(A,t){t||(t={});var s={};return A.iteration!=null&&A.hasOwnProperty("iteration")&&(s.iteration=A.iteration,t.oneofs&&(s._iteration="iteration")),A.seed!=null&&A.hasOwnProperty("seed")&&(s.seed=t.bytes===String?I.base64.encode(A.seed,0,A.seed.length):t.bytes===Array?Array.prototype.slice.call(A.seed):A.seed,t.oneofs&&(s._seed="seed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderMessageKey"},i})(),r.SenderSigningKey=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.public=A.bytes();break}case 2:{c.private=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SenderKeyStateStructure.SenderSigningKey)return A;var t=new E.proto.SenderKeyStateStructure.SenderSigningKey;return A.public!=null&&(typeof A.public=="string"?I.base64.decode(A.public,t.public=I.newBuffer(I.base64.length(A.public)),0):A.public.length>=0&&(t.public=A.public)),A.private!=null&&(typeof A.private=="string"?I.base64.decode(A.private,t.private=I.newBuffer(I.base64.length(A.private)),0):A.private.length>=0&&(t.private=A.private)),t},i.toObject=function(A,t){t||(t={});var s={};return A.public!=null&&A.hasOwnProperty("public")&&(s.public=t.bytes===String?I.base64.encode(A.public,0,A.public.length):t.bytes===Array?Array.prototype.slice.call(A.public):A.public,t.oneofs&&(s._public="public")),A.private!=null&&A.hasOwnProperty("private")&&(s.private=t.bytes===String?I.base64.encode(A.private,0,A.private.length):t.bytes===Array?Array.prototype.slice.call(A.private):A.private,t.oneofs&&(s._private="private")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderSigningKey"},i})(),r})(),n.ServerErrorReceipt=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ServerErrorReceipt)return e;var a=new E.proto.ServerErrorReceipt;return e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),a},r.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ServerErrorReceipt"},r})(),n.SessionStructure=(function(){function r(i){if(this.receiverChains=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sessionVersion=e.uint32();break}case 2:{s.localIdentityPublic=e.bytes();break}case 3:{s.remoteIdentityPublic=e.bytes();break}case 4:{s.rootKey=e.bytes();break}case 5:{s.previousCounter=e.uint32();break}case 6:{s.senderChain=E.proto.SessionStructure.Chain.decode(e,e.uint32());break}case 7:{s.receiverChains&&s.receiverChains.length||(s.receiverChains=[]),s.receiverChains.push(E.proto.SessionStructure.Chain.decode(e,e.uint32()));break}case 8:{s.pendingKeyExchange=E.proto.SessionStructure.PendingKeyExchange.decode(e,e.uint32());break}case 9:{s.pendingPreKey=E.proto.SessionStructure.PendingPreKey.decode(e,e.uint32());break}case 10:{s.remoteRegistrationId=e.uint32();break}case 11:{s.localRegistrationId=e.uint32();break}case 12:{s.needsRefresh=e.bool();break}case 13:{s.aliceBaseKey=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SessionStructure)return e;var a=new E.proto.SessionStructure;if(e.sessionVersion!=null&&(a.sessionVersion=e.sessionVersion>>>0),e.localIdentityPublic!=null&&(typeof e.localIdentityPublic=="string"?I.base64.decode(e.localIdentityPublic,a.localIdentityPublic=I.newBuffer(I.base64.length(e.localIdentityPublic)),0):e.localIdentityPublic.length>=0&&(a.localIdentityPublic=e.localIdentityPublic)),e.remoteIdentityPublic!=null&&(typeof e.remoteIdentityPublic=="string"?I.base64.decode(e.remoteIdentityPublic,a.remoteIdentityPublic=I.newBuffer(I.base64.length(e.remoteIdentityPublic)),0):e.remoteIdentityPublic.length>=0&&(a.remoteIdentityPublic=e.remoteIdentityPublic)),e.rootKey!=null&&(typeof e.rootKey=="string"?I.base64.decode(e.rootKey,a.rootKey=I.newBuffer(I.base64.length(e.rootKey)),0):e.rootKey.length>=0&&(a.rootKey=e.rootKey)),e.previousCounter!=null&&(a.previousCounter=e.previousCounter>>>0),e.senderChain!=null){if(typeof e.senderChain!="object")throw TypeError(".proto.SessionStructure.senderChain: object expected");a.senderChain=E.proto.SessionStructure.Chain.fromObject(e.senderChain)}if(e.receiverChains){if(!Array.isArray(e.receiverChains))throw TypeError(".proto.SessionStructure.receiverChains: array expected");a.receiverChains=[];for(var A=0;A>>0),e.localRegistrationId!=null&&(a.localRegistrationId=e.localRegistrationId>>>0),e.needsRefresh!=null&&(a.needsRefresh=!!e.needsRefresh),e.aliceBaseKey!=null&&(typeof e.aliceBaseKey=="string"?I.base64.decode(e.aliceBaseKey,a.aliceBaseKey=I.newBuffer(I.base64.length(e.aliceBaseKey)),0):e.aliceBaseKey.length>=0&&(a.aliceBaseKey=e.aliceBaseKey)),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.receiverChains=[]),e.sessionVersion!=null&&e.hasOwnProperty("sessionVersion")&&(A.sessionVersion=e.sessionVersion,a.oneofs&&(A._sessionVersion="sessionVersion")),e.localIdentityPublic!=null&&e.hasOwnProperty("localIdentityPublic")&&(A.localIdentityPublic=a.bytes===String?I.base64.encode(e.localIdentityPublic,0,e.localIdentityPublic.length):a.bytes===Array?Array.prototype.slice.call(e.localIdentityPublic):e.localIdentityPublic,a.oneofs&&(A._localIdentityPublic="localIdentityPublic")),e.remoteIdentityPublic!=null&&e.hasOwnProperty("remoteIdentityPublic")&&(A.remoteIdentityPublic=a.bytes===String?I.base64.encode(e.remoteIdentityPublic,0,e.remoteIdentityPublic.length):a.bytes===Array?Array.prototype.slice.call(e.remoteIdentityPublic):e.remoteIdentityPublic,a.oneofs&&(A._remoteIdentityPublic="remoteIdentityPublic")),e.rootKey!=null&&e.hasOwnProperty("rootKey")&&(A.rootKey=a.bytes===String?I.base64.encode(e.rootKey,0,e.rootKey.length):a.bytes===Array?Array.prototype.slice.call(e.rootKey):e.rootKey,a.oneofs&&(A._rootKey="rootKey")),e.previousCounter!=null&&e.hasOwnProperty("previousCounter")&&(A.previousCounter=e.previousCounter,a.oneofs&&(A._previousCounter="previousCounter")),e.senderChain!=null&&e.hasOwnProperty("senderChain")&&(A.senderChain=E.proto.SessionStructure.Chain.toObject(e.senderChain,a),a.oneofs&&(A._senderChain="senderChain")),e.receiverChains&&e.receiverChains.length){A.receiverChains=[];for(var t=0;t>>3){case 1:{c.senderRatchetKey=A.bytes();break}case 2:{c.senderRatchetKeyPrivate=A.bytes();break}case 3:{c.chainKey=E.proto.SessionStructure.Chain.ChainKey.decode(A,A.uint32());break}case 4:{c.messageKeys&&c.messageKeys.length||(c.messageKeys=[]),c.messageKeys.push(E.proto.SessionStructure.Chain.MessageKey.decode(A,A.uint32()));break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SessionStructure.Chain)return A;var t=new E.proto.SessionStructure.Chain;if(A.senderRatchetKey!=null&&(typeof A.senderRatchetKey=="string"?I.base64.decode(A.senderRatchetKey,t.senderRatchetKey=I.newBuffer(I.base64.length(A.senderRatchetKey)),0):A.senderRatchetKey.length>=0&&(t.senderRatchetKey=A.senderRatchetKey)),A.senderRatchetKeyPrivate!=null&&(typeof A.senderRatchetKeyPrivate=="string"?I.base64.decode(A.senderRatchetKeyPrivate,t.senderRatchetKeyPrivate=I.newBuffer(I.base64.length(A.senderRatchetKeyPrivate)),0):A.senderRatchetKeyPrivate.length>=0&&(t.senderRatchetKeyPrivate=A.senderRatchetKeyPrivate)),A.chainKey!=null){if(typeof A.chainKey!="object")throw TypeError(".proto.SessionStructure.Chain.chainKey: object expected");t.chainKey=E.proto.SessionStructure.Chain.ChainKey.fromObject(A.chainKey)}if(A.messageKeys){if(!Array.isArray(A.messageKeys))throw TypeError(".proto.SessionStructure.Chain.messageKeys: array expected");t.messageKeys=[];for(var s=0;s>>3){case 1:{p.index=s.uint32();break}case 2:{p.key=s.bytes();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.SessionStructure.Chain.ChainKey)return s;var g=new E.proto.SessionStructure.Chain.ChainKey;return s.index!=null&&(g.index=s.index>>>0),s.key!=null&&(typeof s.key=="string"?I.base64.decode(s.key,g.key=I.newBuffer(I.base64.length(s.key)),0):s.key.length>=0&&(g.key=s.key)),g},a.toObject=function(s,g){g||(g={});var c={};return s.index!=null&&s.hasOwnProperty("index")&&(c.index=s.index,g.oneofs&&(c._index="index")),s.key!=null&&s.hasOwnProperty("key")&&(c.key=g.bytes===String?I.base64.encode(s.key,0,s.key.length):g.bytes===Array?Array.prototype.slice.call(s.key):s.key,g.oneofs&&(c._key="key")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.SessionStructure.Chain.ChainKey"},a})(),i.MessageKey=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.index=s.uint32();break}case 2:{p.cipherKey=s.bytes();break}case 3:{p.macKey=s.bytes();break}case 4:{p.iv=s.bytes();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.SessionStructure.Chain.MessageKey)return s;var g=new E.proto.SessionStructure.Chain.MessageKey;return s.index!=null&&(g.index=s.index>>>0),s.cipherKey!=null&&(typeof s.cipherKey=="string"?I.base64.decode(s.cipherKey,g.cipherKey=I.newBuffer(I.base64.length(s.cipherKey)),0):s.cipherKey.length>=0&&(g.cipherKey=s.cipherKey)),s.macKey!=null&&(typeof s.macKey=="string"?I.base64.decode(s.macKey,g.macKey=I.newBuffer(I.base64.length(s.macKey)),0):s.macKey.length>=0&&(g.macKey=s.macKey)),s.iv!=null&&(typeof s.iv=="string"?I.base64.decode(s.iv,g.iv=I.newBuffer(I.base64.length(s.iv)),0):s.iv.length>=0&&(g.iv=s.iv)),g},a.toObject=function(s,g){g||(g={});var c={};return s.index!=null&&s.hasOwnProperty("index")&&(c.index=s.index,g.oneofs&&(c._index="index")),s.cipherKey!=null&&s.hasOwnProperty("cipherKey")&&(c.cipherKey=g.bytes===String?I.base64.encode(s.cipherKey,0,s.cipherKey.length):g.bytes===Array?Array.prototype.slice.call(s.cipherKey):s.cipherKey,g.oneofs&&(c._cipherKey="cipherKey")),s.macKey!=null&&s.hasOwnProperty("macKey")&&(c.macKey=g.bytes===String?I.base64.encode(s.macKey,0,s.macKey.length):g.bytes===Array?Array.prototype.slice.call(s.macKey):s.macKey,g.oneofs&&(c._macKey="macKey")),s.iv!=null&&s.hasOwnProperty("iv")&&(c.iv=g.bytes===String?I.base64.encode(s.iv,0,s.iv.length):g.bytes===Array?Array.prototype.slice.call(s.iv):s.iv,g.oneofs&&(c._iv="iv")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.SessionStructure.Chain.MessageKey"},a})(),i})(),r.PendingKeyExchange=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.sequence=A.uint32();break}case 2:{c.localBaseKey=A.bytes();break}case 3:{c.localBaseKeyPrivate=A.bytes();break}case 4:{c.localRatchetKey=A.bytes();break}case 5:{c.localRatchetKeyPrivate=A.bytes();break}case 7:{c.localIdentityKey=A.bytes();break}case 8:{c.localIdentityKeyPrivate=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SessionStructure.PendingKeyExchange)return A;var t=new E.proto.SessionStructure.PendingKeyExchange;return A.sequence!=null&&(t.sequence=A.sequence>>>0),A.localBaseKey!=null&&(typeof A.localBaseKey=="string"?I.base64.decode(A.localBaseKey,t.localBaseKey=I.newBuffer(I.base64.length(A.localBaseKey)),0):A.localBaseKey.length>=0&&(t.localBaseKey=A.localBaseKey)),A.localBaseKeyPrivate!=null&&(typeof A.localBaseKeyPrivate=="string"?I.base64.decode(A.localBaseKeyPrivate,t.localBaseKeyPrivate=I.newBuffer(I.base64.length(A.localBaseKeyPrivate)),0):A.localBaseKeyPrivate.length>=0&&(t.localBaseKeyPrivate=A.localBaseKeyPrivate)),A.localRatchetKey!=null&&(typeof A.localRatchetKey=="string"?I.base64.decode(A.localRatchetKey,t.localRatchetKey=I.newBuffer(I.base64.length(A.localRatchetKey)),0):A.localRatchetKey.length>=0&&(t.localRatchetKey=A.localRatchetKey)),A.localRatchetKeyPrivate!=null&&(typeof A.localRatchetKeyPrivate=="string"?I.base64.decode(A.localRatchetKeyPrivate,t.localRatchetKeyPrivate=I.newBuffer(I.base64.length(A.localRatchetKeyPrivate)),0):A.localRatchetKeyPrivate.length>=0&&(t.localRatchetKeyPrivate=A.localRatchetKeyPrivate)),A.localIdentityKey!=null&&(typeof A.localIdentityKey=="string"?I.base64.decode(A.localIdentityKey,t.localIdentityKey=I.newBuffer(I.base64.length(A.localIdentityKey)),0):A.localIdentityKey.length>=0&&(t.localIdentityKey=A.localIdentityKey)),A.localIdentityKeyPrivate!=null&&(typeof A.localIdentityKeyPrivate=="string"?I.base64.decode(A.localIdentityKeyPrivate,t.localIdentityKeyPrivate=I.newBuffer(I.base64.length(A.localIdentityKeyPrivate)),0):A.localIdentityKeyPrivate.length>=0&&(t.localIdentityKeyPrivate=A.localIdentityKeyPrivate)),t},i.toObject=function(A,t){t||(t={});var s={};return A.sequence!=null&&A.hasOwnProperty("sequence")&&(s.sequence=A.sequence,t.oneofs&&(s._sequence="sequence")),A.localBaseKey!=null&&A.hasOwnProperty("localBaseKey")&&(s.localBaseKey=t.bytes===String?I.base64.encode(A.localBaseKey,0,A.localBaseKey.length):t.bytes===Array?Array.prototype.slice.call(A.localBaseKey):A.localBaseKey,t.oneofs&&(s._localBaseKey="localBaseKey")),A.localBaseKeyPrivate!=null&&A.hasOwnProperty("localBaseKeyPrivate")&&(s.localBaseKeyPrivate=t.bytes===String?I.base64.encode(A.localBaseKeyPrivate,0,A.localBaseKeyPrivate.length):t.bytes===Array?Array.prototype.slice.call(A.localBaseKeyPrivate):A.localBaseKeyPrivate,t.oneofs&&(s._localBaseKeyPrivate="localBaseKeyPrivate")),A.localRatchetKey!=null&&A.hasOwnProperty("localRatchetKey")&&(s.localRatchetKey=t.bytes===String?I.base64.encode(A.localRatchetKey,0,A.localRatchetKey.length):t.bytes===Array?Array.prototype.slice.call(A.localRatchetKey):A.localRatchetKey,t.oneofs&&(s._localRatchetKey="localRatchetKey")),A.localRatchetKeyPrivate!=null&&A.hasOwnProperty("localRatchetKeyPrivate")&&(s.localRatchetKeyPrivate=t.bytes===String?I.base64.encode(A.localRatchetKeyPrivate,0,A.localRatchetKeyPrivate.length):t.bytes===Array?Array.prototype.slice.call(A.localRatchetKeyPrivate):A.localRatchetKeyPrivate,t.oneofs&&(s._localRatchetKeyPrivate="localRatchetKeyPrivate")),A.localIdentityKey!=null&&A.hasOwnProperty("localIdentityKey")&&(s.localIdentityKey=t.bytes===String?I.base64.encode(A.localIdentityKey,0,A.localIdentityKey.length):t.bytes===Array?Array.prototype.slice.call(A.localIdentityKey):A.localIdentityKey,t.oneofs&&(s._localIdentityKey="localIdentityKey")),A.localIdentityKeyPrivate!=null&&A.hasOwnProperty("localIdentityKeyPrivate")&&(s.localIdentityKeyPrivate=t.bytes===String?I.base64.encode(A.localIdentityKeyPrivate,0,A.localIdentityKeyPrivate.length):t.bytes===Array?Array.prototype.slice.call(A.localIdentityKeyPrivate):A.localIdentityKeyPrivate,t.oneofs&&(s._localIdentityKeyPrivate="localIdentityKeyPrivate")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SessionStructure.PendingKeyExchange"},i})(),r.PendingPreKey=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.preKeyId=A.uint32();break}case 3:{c.signedPreKeyId=A.int32();break}case 2:{c.baseKey=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SessionStructure.PendingPreKey)return A;var t=new E.proto.SessionStructure.PendingPreKey;return A.preKeyId!=null&&(t.preKeyId=A.preKeyId>>>0),A.signedPreKeyId!=null&&(t.signedPreKeyId=A.signedPreKeyId|0),A.baseKey!=null&&(typeof A.baseKey=="string"?I.base64.decode(A.baseKey,t.baseKey=I.newBuffer(I.base64.length(A.baseKey)),0):A.baseKey.length>=0&&(t.baseKey=A.baseKey)),t},i.toObject=function(A,t){t||(t={});var s={};return A.preKeyId!=null&&A.hasOwnProperty("preKeyId")&&(s.preKeyId=A.preKeyId,t.oneofs&&(s._preKeyId="preKeyId")),A.baseKey!=null&&A.hasOwnProperty("baseKey")&&(s.baseKey=t.bytes===String?I.base64.encode(A.baseKey,0,A.baseKey.length):t.bytes===Array?Array.prototype.slice.call(A.baseKey):A.baseKey,t.oneofs&&(s._baseKey="baseKey")),A.signedPreKeyId!=null&&A.hasOwnProperty("signedPreKeyId")&&(s.signedPreKeyId=A.signedPreKeyId,t.oneofs&&(s._signedPreKeyId="signedPreKeyId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SessionStructure.PendingPreKey"},i})(),r})(),n.SessionTransparencyMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.disclaimerText=e.string();break}case 2:{s.hcaId=e.string();break}case 3:{s.sessionTransparencyType=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SessionTransparencyMetadata)return e;var a=new E.proto.SessionTransparencyMetadata;switch(e.disclaimerText!=null&&(a.disclaimerText=String(e.disclaimerText)),e.hcaId!=null&&(a.hcaId=String(e.hcaId)),e.sessionTransparencyType){default:if(typeof e.sessionTransparencyType=="number"){a.sessionTransparencyType=e.sessionTransparencyType;break}break;case"UNKNOWN_TYPE":case 0:a.sessionTransparencyType=0;break;case"NY_AI_SAFETY_DISCLAIMER":case 1:a.sessionTransparencyType=1;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.disclaimerText!=null&&e.hasOwnProperty("disclaimerText")&&(A.disclaimerText=e.disclaimerText,a.oneofs&&(A._disclaimerText="disclaimerText")),e.hcaId!=null&&e.hasOwnProperty("hcaId")&&(A.hcaId=e.hcaId,a.oneofs&&(A._hcaId="hcaId")),e.sessionTransparencyType!=null&&e.hasOwnProperty("sessionTransparencyType")&&(A.sessionTransparencyType=a.enums===String?E.proto.SessionTransparencyType[e.sessionTransparencyType]===void 0?e.sessionTransparencyType:E.proto.SessionTransparencyType[e.sessionTransparencyType]:e.sessionTransparencyType,a.oneofs&&(A._sessionTransparencyType="sessionTransparencyType")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SessionTransparencyMetadata"},r})(),n.SessionTransparencyType=(function(){let r={},o=Object.create(r);return o[r[0]="UNKNOWN_TYPE"]=0,o[r[1]="NY_AI_SAFETY_DISCLAIMER"]=1,o})(),n.SignalMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.ratchetKey=e.bytes();break}case 2:{s.counter=e.uint32();break}case 3:{s.previousCounter=e.uint32();break}case 4:{s.ciphertext=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SignalMessage)return e;var a=new E.proto.SignalMessage;return e.ratchetKey!=null&&(typeof e.ratchetKey=="string"?I.base64.decode(e.ratchetKey,a.ratchetKey=I.newBuffer(I.base64.length(e.ratchetKey)),0):e.ratchetKey.length>=0&&(a.ratchetKey=e.ratchetKey)),e.counter!=null&&(a.counter=e.counter>>>0),e.previousCounter!=null&&(a.previousCounter=e.previousCounter>>>0),e.ciphertext!=null&&(typeof e.ciphertext=="string"?I.base64.decode(e.ciphertext,a.ciphertext=I.newBuffer(I.base64.length(e.ciphertext)),0):e.ciphertext.length>=0&&(a.ciphertext=e.ciphertext)),a},r.toObject=function(e,a){a||(a={});var A={};return e.ratchetKey!=null&&e.hasOwnProperty("ratchetKey")&&(A.ratchetKey=a.bytes===String?I.base64.encode(e.ratchetKey,0,e.ratchetKey.length):a.bytes===Array?Array.prototype.slice.call(e.ratchetKey):e.ratchetKey,a.oneofs&&(A._ratchetKey="ratchetKey")),e.counter!=null&&e.hasOwnProperty("counter")&&(A.counter=e.counter,a.oneofs&&(A._counter="counter")),e.previousCounter!=null&&e.hasOwnProperty("previousCounter")&&(A.previousCounter=e.previousCounter,a.oneofs&&(A._previousCounter="previousCounter")),e.ciphertext!=null&&e.hasOwnProperty("ciphertext")&&(A.ciphertext=a.bytes===String?I.base64.encode(e.ciphertext,0,e.ciphertext.length):a.bytes===Array?Array.prototype.slice.call(e.ciphertext):e.ciphertext,a.oneofs&&(A._ciphertext="ciphertext")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SignalMessage"},r})(),n.SignedPreKeyRecordStructure=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.publicKey=e.bytes();break}case 3:{s.privateKey=e.bytes();break}case 4:{s.signature=e.bytes();break}case 5:{s.timestamp=e.fixed64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SignedPreKeyRecordStructure)return e;var a=new E.proto.SignedPreKeyRecordStructure;return e.id!=null&&(a.id=e.id>>>0),e.publicKey!=null&&(typeof e.publicKey=="string"?I.base64.decode(e.publicKey,a.publicKey=I.newBuffer(I.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?I.base64.decode(e.privateKey,a.privateKey=I.newBuffer(I.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),e.signature!=null&&(typeof e.signature=="string"?I.base64.decode(e.signature,a.signature=I.newBuffer(I.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.timestamp!=null&&(I.Long?(a.timestamp=I.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new I.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},r.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?I.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?I.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?I.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?re(e.timestamp):a.longs===Number?ae(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SignedPreKeyRecordStructure"},r})(),n.StatusAttribution=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.actionUrl=e.string();break}case 3:{s.statusReshare=E.proto.StatusAttribution.StatusReshare.decode(e,e.uint32());break}case 4:{s.externalShare=E.proto.StatusAttribution.ExternalShare.decode(e,e.uint32());break}case 5:{s.music=E.proto.StatusAttribution.Music.decode(e,e.uint32());break}case 6:{s.groupStatus=E.proto.StatusAttribution.GroupStatus.decode(e,e.uint32());break}case 7:{s.rlAttribution=E.proto.StatusAttribution.RLAttribution.decode(e,e.uint32());break}case 8:{s.aiCreatedAttribution=E.proto.StatusAttribution.AiCreatedAttribution.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.StatusAttribution)return e;var a=new E.proto.StatusAttribution;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN":case 0:a.type=0;break;case"RESHARE":case 1:a.type=1;break;case"EXTERNAL_SHARE":case 2:a.type=2;break;case"MUSIC":case 3:a.type=3;break;case"STATUS_MENTION":case 4:a.type=4;break;case"GROUP_STATUS":case 5:a.type=5;break;case"RL_ATTRIBUTION":case 6:a.type=6;break;case"AI_CREATED":case 7:a.type=7;break;case"LAYOUTS":case 8:a.type=8;break}if(e.actionUrl!=null&&(a.actionUrl=String(e.actionUrl)),e.statusReshare!=null){if(typeof e.statusReshare!="object")throw TypeError(".proto.StatusAttribution.statusReshare: object expected");a.statusReshare=E.proto.StatusAttribution.StatusReshare.fromObject(e.statusReshare)}if(e.externalShare!=null){if(typeof e.externalShare!="object")throw TypeError(".proto.StatusAttribution.externalShare: object expected");a.externalShare=E.proto.StatusAttribution.ExternalShare.fromObject(e.externalShare)}if(e.music!=null){if(typeof e.music!="object")throw TypeError(".proto.StatusAttribution.music: object expected");a.music=E.proto.StatusAttribution.Music.fromObject(e.music)}if(e.groupStatus!=null){if(typeof e.groupStatus!="object")throw TypeError(".proto.StatusAttribution.groupStatus: object expected");a.groupStatus=E.proto.StatusAttribution.GroupStatus.fromObject(e.groupStatus)}if(e.rlAttribution!=null){if(typeof e.rlAttribution!="object")throw TypeError(".proto.StatusAttribution.rlAttribution: object expected");a.rlAttribution=E.proto.StatusAttribution.RLAttribution.fromObject(e.rlAttribution)}if(e.aiCreatedAttribution!=null){if(typeof e.aiCreatedAttribution!="object")throw TypeError(".proto.StatusAttribution.aiCreatedAttribution: object expected");a.aiCreatedAttribution=E.proto.StatusAttribution.AiCreatedAttribution.fromObject(e.aiCreatedAttribution)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?E.proto.StatusAttribution.Type[e.type]===void 0?e.type:E.proto.StatusAttribution.Type[e.type]:e.type,a.oneofs&&(A._type="type")),e.actionUrl!=null&&e.hasOwnProperty("actionUrl")&&(A.actionUrl=e.actionUrl,a.oneofs&&(A._actionUrl="actionUrl")),e.statusReshare!=null&&e.hasOwnProperty("statusReshare")&&(A.statusReshare=E.proto.StatusAttribution.StatusReshare.toObject(e.statusReshare,a),a.oneofs&&(A.attributionData="statusReshare")),e.externalShare!=null&&e.hasOwnProperty("externalShare")&&(A.externalShare=E.proto.StatusAttribution.ExternalShare.toObject(e.externalShare,a),a.oneofs&&(A.attributionData="externalShare")),e.music!=null&&e.hasOwnProperty("music")&&(A.music=E.proto.StatusAttribution.Music.toObject(e.music,a),a.oneofs&&(A.attributionData="music")),e.groupStatus!=null&&e.hasOwnProperty("groupStatus")&&(A.groupStatus=E.proto.StatusAttribution.GroupStatus.toObject(e.groupStatus,a),a.oneofs&&(A.attributionData="groupStatus")),e.rlAttribution!=null&&e.hasOwnProperty("rlAttribution")&&(A.rlAttribution=E.proto.StatusAttribution.RLAttribution.toObject(e.rlAttribution,a),a.oneofs&&(A.attributionData="rlAttribution")),e.aiCreatedAttribution!=null&&e.hasOwnProperty("aiCreatedAttribution")&&(A.aiCreatedAttribution=E.proto.StatusAttribution.AiCreatedAttribution.toObject(e.aiCreatedAttribution,a),a.oneofs&&(A.attributionData="aiCreatedAttribution")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusAttribution"},r.AiCreatedAttribution=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.source=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.StatusAttribution.AiCreatedAttribution)return A;var t=new E.proto.StatusAttribution.AiCreatedAttribution;switch(A.source){default:if(typeof A.source=="number"){t.source=A.source;break}break;case"UNKNOWN":case 0:t.source=0;break;case"STATUS_MIMICRY":case 1:t.source=1;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=t.enums===String?E.proto.StatusAttribution.AiCreatedAttribution.Source[A.source]===void 0?A.source:E.proto.StatusAttribution.AiCreatedAttribution.Source[A.source]:A.source,t.oneofs&&(s._source="source")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.AiCreatedAttribution"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="STATUS_MIMICRY"]=1,A})(),i})(),r.ExternalShare=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.actionUrl=A.string();break}case 2:{c.source=A.int32();break}case 3:{c.duration=A.int32();break}case 4:{c.actionFallbackUrl=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.StatusAttribution.ExternalShare)return A;var t=new E.proto.StatusAttribution.ExternalShare;switch(A.actionUrl!=null&&(t.actionUrl=String(A.actionUrl)),A.source){default:if(typeof A.source=="number"){t.source=A.source;break}break;case"UNKNOWN":case 0:t.source=0;break;case"INSTAGRAM":case 1:t.source=1;break;case"FACEBOOK":case 2:t.source=2;break;case"MESSENGER":case 3:t.source=3;break;case"SPOTIFY":case 4:t.source=4;break;case"YOUTUBE":case 5:t.source=5;break;case"PINTEREST":case 6:t.source=6;break;case"THREADS":case 7:t.source=7;break;case"APPLE_MUSIC":case 8:t.source=8;break;case"SHARECHAT":case 9:t.source=9;break;case"GOOGLE_PHOTOS":case 10:t.source=10;break}return A.duration!=null&&(t.duration=A.duration|0),A.actionFallbackUrl!=null&&(t.actionFallbackUrl=String(A.actionFallbackUrl)),t},i.toObject=function(A,t){t||(t={});var s={};return A.actionUrl!=null&&A.hasOwnProperty("actionUrl")&&(s.actionUrl=A.actionUrl,t.oneofs&&(s._actionUrl="actionUrl")),A.source!=null&&A.hasOwnProperty("source")&&(s.source=t.enums===String?E.proto.StatusAttribution.ExternalShare.Source[A.source]===void 0?A.source:E.proto.StatusAttribution.ExternalShare.Source[A.source]:A.source,t.oneofs&&(s._source="source")),A.duration!=null&&A.hasOwnProperty("duration")&&(s.duration=A.duration,t.oneofs&&(s._duration="duration")),A.actionFallbackUrl!=null&&A.hasOwnProperty("actionFallbackUrl")&&(s.actionFallbackUrl=A.actionFallbackUrl,t.oneofs&&(s._actionFallbackUrl="actionFallbackUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.ExternalShare"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="INSTAGRAM"]=1,A[a[2]="FACEBOOK"]=2,A[a[3]="MESSENGER"]=3,A[a[4]="SPOTIFY"]=4,A[a[5]="YOUTUBE"]=5,A[a[6]="PINTEREST"]=6,A[a[7]="THREADS"]=7,A[a[8]="APPLE_MUSIC"]=8,A[a[9]="SHARECHAT"]=9,A[a[10]="GOOGLE_PHOTOS"]=10,A})(),i})(),r.GroupStatus=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.authorJid=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.StatusAttribution.GroupStatus)return A;var t=new E.proto.StatusAttribution.GroupStatus;return A.authorJid!=null&&(t.authorJid=String(A.authorJid)),t},i.toObject=function(A,t){t||(t={});var s={};return A.authorJid!=null&&A.hasOwnProperty("authorJid")&&(s.authorJid=A.authorJid,t.oneofs&&(s._authorJid="authorJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.GroupStatus"},i})(),r.Music=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.authorName=A.string();break}case 2:{c.songId=A.string();break}case 3:{c.title=A.string();break}case 4:{c.author=A.string();break}case 5:{c.artistAttribution=A.string();break}case 6:{c.isExplicit=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.StatusAttribution.Music)return A;var t=new E.proto.StatusAttribution.Music;return A.authorName!=null&&(t.authorName=String(A.authorName)),A.songId!=null&&(t.songId=String(A.songId)),A.title!=null&&(t.title=String(A.title)),A.author!=null&&(t.author=String(A.author)),A.artistAttribution!=null&&(t.artistAttribution=String(A.artistAttribution)),A.isExplicit!=null&&(t.isExplicit=!!A.isExplicit),t},i.toObject=function(A,t){t||(t={});var s={};return A.authorName!=null&&A.hasOwnProperty("authorName")&&(s.authorName=A.authorName,t.oneofs&&(s._authorName="authorName")),A.songId!=null&&A.hasOwnProperty("songId")&&(s.songId=A.songId,t.oneofs&&(s._songId="songId")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,t.oneofs&&(s._title="title")),A.author!=null&&A.hasOwnProperty("author")&&(s.author=A.author,t.oneofs&&(s._author="author")),A.artistAttribution!=null&&A.hasOwnProperty("artistAttribution")&&(s.artistAttribution=A.artistAttribution,t.oneofs&&(s._artistAttribution="artistAttribution")),A.isExplicit!=null&&A.hasOwnProperty("isExplicit")&&(s.isExplicit=A.isExplicit,t.oneofs&&(s._isExplicit="isExplicit")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.Music"},i})(),r.RLAttribution=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.source=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.StatusAttribution.RLAttribution)return A;var t=new E.proto.StatusAttribution.RLAttribution;switch(A.source){default:if(typeof A.source=="number"){t.source=A.source;break}break;case"UNKNOWN":case 0:t.source=0;break;case"RAY_BAN_META_GLASSES":case 1:t.source=1;break;case"OAKLEY_META_GLASSES":case 2:t.source=2;break;case"HYPERNOVA_GLASSES":case 3:t.source=3;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=t.enums===String?E.proto.StatusAttribution.RLAttribution.Source[A.source]===void 0?A.source:E.proto.StatusAttribution.RLAttribution.Source[A.source]:A.source,t.oneofs&&(s._source="source")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.RLAttribution"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="RAY_BAN_META_GLASSES"]=1,A[a[2]="OAKLEY_META_GLASSES"]=2,A[a[3]="HYPERNOVA_GLASSES"]=3,A})(),i})(),r.StatusReshare=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.source=A.int32();break}case 2:{c.metadata=E.proto.StatusAttribution.StatusReshare.Metadata.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.StatusAttribution.StatusReshare)return A;var t=new E.proto.StatusAttribution.StatusReshare;switch(A.source){default:if(typeof A.source=="number"){t.source=A.source;break}break;case"UNKNOWN":case 0:t.source=0;break;case"INTERNAL_RESHARE":case 1:t.source=1;break;case"MENTION_RESHARE":case 2:t.source=2;break;case"CHANNEL_RESHARE":case 3:t.source=3;break;case"FORWARD":case 4:t.source=4;break}if(A.metadata!=null){if(typeof A.metadata!="object")throw TypeError(".proto.StatusAttribution.StatusReshare.metadata: object expected");t.metadata=E.proto.StatusAttribution.StatusReshare.Metadata.fromObject(A.metadata)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=t.enums===String?E.proto.StatusAttribution.StatusReshare.Source[A.source]===void 0?A.source:E.proto.StatusAttribution.StatusReshare.Source[A.source]:A.source,t.oneofs&&(s._source="source")),A.metadata!=null&&A.hasOwnProperty("metadata")&&(s.metadata=E.proto.StatusAttribution.StatusReshare.Metadata.toObject(A.metadata,t),t.oneofs&&(s._metadata="metadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.StatusReshare"},i.Metadata=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.duration=s.int32();break}case 2:{p.channelJid=s.string();break}case 3:{p.channelMessageId=s.int32();break}case 4:{p.hasMultipleReshares=s.bool();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.StatusAttribution.StatusReshare.Metadata)return s;var g=new E.proto.StatusAttribution.StatusReshare.Metadata;return s.duration!=null&&(g.duration=s.duration|0),s.channelJid!=null&&(g.channelJid=String(s.channelJid)),s.channelMessageId!=null&&(g.channelMessageId=s.channelMessageId|0),s.hasMultipleReshares!=null&&(g.hasMultipleReshares=!!s.hasMultipleReshares),g},a.toObject=function(s,g){g||(g={});var c={};return s.duration!=null&&s.hasOwnProperty("duration")&&(c.duration=s.duration,g.oneofs&&(c._duration="duration")),s.channelJid!=null&&s.hasOwnProperty("channelJid")&&(c.channelJid=s.channelJid,g.oneofs&&(c._channelJid="channelJid")),s.channelMessageId!=null&&s.hasOwnProperty("channelMessageId")&&(c.channelMessageId=s.channelMessageId,g.oneofs&&(c._channelMessageId="channelMessageId")),s.hasMultipleReshares!=null&&s.hasOwnProperty("hasMultipleReshares")&&(c.hasMultipleReshares=s.hasMultipleReshares,g.oneofs&&(c._hasMultipleReshares="hasMultipleReshares")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.StatusAttribution.StatusReshare.Metadata"},a})(),i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="INTERNAL_RESHARE"]=1,A[a[2]="MENTION_RESHARE"]=2,A[a[3]="CHANNEL_RESHARE"]=3,A[a[4]="FORWARD"]=4,A})(),i})(),r.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="RESHARE"]=1,e[i[2]="EXTERNAL_SHARE"]=2,e[i[3]="MUSIC"]=3,e[i[4]="STATUS_MENTION"]=4,e[i[5]="GROUP_STATUS"]=5,e[i[6]="RL_ATTRIBUTION"]=6,e[i[7]="AI_CREATED"]=7,e[i[8]="LAYOUTS"]=8,e})(),r})(),n.StatusMentionMessage=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.quotedStatus=E.proto.Message.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.StatusMentionMessage)return e;var a=new E.proto.StatusMentionMessage;if(e.quotedStatus!=null){if(typeof e.quotedStatus!="object")throw TypeError(".proto.StatusMentionMessage.quotedStatus: object expected");a.quotedStatus=E.proto.Message.fromObject(e.quotedStatus)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.quotedStatus!=null&&e.hasOwnProperty("quotedStatus")&&(A.quotedStatus=E.proto.Message.toObject(e.quotedStatus,a),a.oneofs&&(A._quotedStatus="quotedStatus")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusMentionMessage"},r})(),n.StatusPSA=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 44:{s.campaignId=e.uint64();break}case 45:{s.campaignExpirationTimestamp=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.StatusPSA)return e;var a=new E.proto.StatusPSA;return e.campaignId!=null&&(I.Long?(a.campaignId=I.Long.fromValue(e.campaignId)).unsigned=!0:typeof e.campaignId=="string"?a.campaignId=parseInt(e.campaignId,10):typeof e.campaignId=="number"?a.campaignId=e.campaignId:typeof e.campaignId=="object"&&(a.campaignId=new I.LongBits(e.campaignId.low>>>0,e.campaignId.high>>>0).toNumber(!0))),e.campaignExpirationTimestamp!=null&&(I.Long?(a.campaignExpirationTimestamp=I.Long.fromValue(e.campaignExpirationTimestamp)).unsigned=!0:typeof e.campaignExpirationTimestamp=="string"?a.campaignExpirationTimestamp=parseInt(e.campaignExpirationTimestamp,10):typeof e.campaignExpirationTimestamp=="number"?a.campaignExpirationTimestamp=e.campaignExpirationTimestamp:typeof e.campaignExpirationTimestamp=="object"&&(a.campaignExpirationTimestamp=new I.LongBits(e.campaignExpirationTimestamp.low>>>0,e.campaignExpirationTimestamp.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};if(a.defaults)if(I.Long){var t=new I.Long(0,0,!0);A.campaignId=a.longs===String?t.toString():a.longs===Number?t.toNumber():t}else A.campaignId=a.longs===String?"0":0;return e.campaignId!=null&&e.hasOwnProperty("campaignId")&&(typeof e.campaignId=="number"?A.campaignId=a.longs===String?String(e.campaignId):e.campaignId:A.campaignId=a.longs===String?re(e.campaignId,!0):a.longs===Number?ae(e.campaignId,!0):e.campaignId),e.campaignExpirationTimestamp!=null&&e.hasOwnProperty("campaignExpirationTimestamp")&&(typeof e.campaignExpirationTimestamp=="number"?A.campaignExpirationTimestamp=a.longs===String?String(e.campaignExpirationTimestamp):e.campaignExpirationTimestamp:A.campaignExpirationTimestamp=a.longs===String?re(e.campaignExpirationTimestamp,!0):a.longs===Number?ae(e.campaignExpirationTimestamp,!0):e.campaignExpirationTimestamp,a.oneofs&&(A._campaignExpirationTimestamp="campaignExpirationTimestamp")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusPSA"},r})(),n.StickerMetadata=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.url=e.string();break}case 2:{s.fileSha256=e.bytes();break}case 3:{s.fileEncSha256=e.bytes();break}case 4:{s.mediaKey=e.bytes();break}case 5:{s.mimetype=e.string();break}case 6:{s.height=e.uint32();break}case 7:{s.width=e.uint32();break}case 8:{s.directPath=e.string();break}case 9:{s.fileLength=e.uint64();break}case 10:{s.weight=e.float();break}case 11:{s.lastStickerSentTs=e.int64();break}case 12:{s.isLottie=e.bool();break}case 13:{s.imageHash=e.string();break}case 14:{s.isAvatarSticker=e.bool();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.StickerMetadata)return e;var a=new E.proto.StickerMetadata;return e.url!=null&&(a.url=String(e.url)),e.fileSha256!=null&&(typeof e.fileSha256=="string"?I.base64.decode(e.fileSha256,a.fileSha256=I.newBuffer(I.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?I.base64.decode(e.fileEncSha256,a.fileEncSha256=I.newBuffer(I.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),e.mediaKey!=null&&(typeof e.mediaKey=="string"?I.base64.decode(e.mediaKey,a.mediaKey=I.newBuffer(I.base64.length(e.mediaKey)),0):e.mediaKey.length>=0&&(a.mediaKey=e.mediaKey)),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.height!=null&&(a.height=e.height>>>0),e.width!=null&&(a.width=e.width>>>0),e.directPath!=null&&(a.directPath=String(e.directPath)),e.fileLength!=null&&(I.Long?(a.fileLength=I.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new I.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.weight!=null&&(a.weight=Number(e.weight)),e.lastStickerSentTs!=null&&(I.Long?(a.lastStickerSentTs=I.Long.fromValue(e.lastStickerSentTs)).unsigned=!1:typeof e.lastStickerSentTs=="string"?a.lastStickerSentTs=parseInt(e.lastStickerSentTs,10):typeof e.lastStickerSentTs=="number"?a.lastStickerSentTs=e.lastStickerSentTs:typeof e.lastStickerSentTs=="object"&&(a.lastStickerSentTs=new I.LongBits(e.lastStickerSentTs.low>>>0,e.lastStickerSentTs.high>>>0).toNumber())),e.isLottie!=null&&(a.isLottie=!!e.isLottie),e.imageHash!=null&&(a.imageHash=String(e.imageHash)),e.isAvatarSticker!=null&&(a.isAvatarSticker=!!e.isAvatarSticker),a},r.toObject=function(e,a){a||(a={});var A={};return e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=a.bytes===String?I.base64.encode(e.fileSha256,0,e.fileSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileSha256):e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?I.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=a.bytes===String?I.base64.encode(e.mediaKey,0,e.mediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.mediaKey):e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.height!=null&&e.hasOwnProperty("height")&&(A.height=e.height,a.oneofs&&(A._height="height")),e.width!=null&&e.hasOwnProperty("width")&&(A.width=e.width,a.oneofs&&(A._width="width")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?re(e.fileLength,!0):a.longs===Number?ae(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),e.weight!=null&&e.hasOwnProperty("weight")&&(A.weight=a.json&&!isFinite(e.weight)?String(e.weight):e.weight,a.oneofs&&(A._weight="weight")),e.lastStickerSentTs!=null&&e.hasOwnProperty("lastStickerSentTs")&&(typeof e.lastStickerSentTs=="number"?A.lastStickerSentTs=a.longs===String?String(e.lastStickerSentTs):e.lastStickerSentTs:A.lastStickerSentTs=a.longs===String?re(e.lastStickerSentTs):a.longs===Number?ae(e.lastStickerSentTs):e.lastStickerSentTs,a.oneofs&&(A._lastStickerSentTs="lastStickerSentTs")),e.isLottie!=null&&e.hasOwnProperty("isLottie")&&(A.isLottie=e.isLottie,a.oneofs&&(A._isLottie="isLottie")),e.imageHash!=null&&e.hasOwnProperty("imageHash")&&(A.imageHash=e.imageHash,a.oneofs&&(A._imageHash="imageHash")),e.isAvatarSticker!=null&&e.hasOwnProperty("isAvatarSticker")&&(A.isAvatarSticker=e.isAvatarSticker,a.oneofs&&(A._isAvatarSticker="isAvatarSticker")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StickerMetadata"},r})(),n.SyncActionData=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.index=e.bytes();break}case 2:{s.value=E.proto.SyncActionValue.decode(e,e.uint32());break}case 3:{s.padding=e.bytes();break}case 4:{s.version=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncActionData)return e;var a=new E.proto.SyncActionData;if(e.index!=null&&(typeof e.index=="string"?I.base64.decode(e.index,a.index=I.newBuffer(I.base64.length(e.index)),0):e.index.length>=0&&(a.index=e.index)),e.value!=null){if(typeof e.value!="object")throw TypeError(".proto.SyncActionData.value: object expected");a.value=E.proto.SyncActionValue.fromObject(e.value)}return e.padding!=null&&(typeof e.padding=="string"?I.base64.decode(e.padding,a.padding=I.newBuffer(I.base64.length(e.padding)),0):e.padding.length>=0&&(a.padding=e.padding)),e.version!=null&&(a.version=e.version|0),a},r.toObject=function(e,a){a||(a={});var A={};return e.index!=null&&e.hasOwnProperty("index")&&(A.index=a.bytes===String?I.base64.encode(e.index,0,e.index.length):a.bytes===Array?Array.prototype.slice.call(e.index):e.index,a.oneofs&&(A._index="index")),e.value!=null&&e.hasOwnProperty("value")&&(A.value=E.proto.SyncActionValue.toObject(e.value,a),a.oneofs&&(A._value="value")),e.padding!=null&&e.hasOwnProperty("padding")&&(A.padding=a.bytes===String?I.base64.encode(e.padding,0,e.padding.length):a.bytes===Array?Array.prototype.slice.call(e.padding):e.padding,a.oneofs&&(A._padding="padding")),e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncActionData"},r})(),n.SyncActionValue=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.timestamp=e.int64();break}case 2:{s.starAction=E.proto.SyncActionValue.StarAction.decode(e,e.uint32());break}case 3:{s.contactAction=E.proto.SyncActionValue.ContactAction.decode(e,e.uint32());break}case 4:{s.muteAction=E.proto.SyncActionValue.MuteAction.decode(e,e.uint32());break}case 5:{s.pinAction=E.proto.SyncActionValue.PinAction.decode(e,e.uint32());break}case 7:{s.pushNameSetting=E.proto.SyncActionValue.PushNameSetting.decode(e,e.uint32());break}case 8:{s.quickReplyAction=E.proto.SyncActionValue.QuickReplyAction.decode(e,e.uint32());break}case 11:{s.recentEmojiWeightsAction=E.proto.SyncActionValue.RecentEmojiWeightsAction.decode(e,e.uint32());break}case 14:{s.labelEditAction=E.proto.SyncActionValue.LabelEditAction.decode(e,e.uint32());break}case 15:{s.labelAssociationAction=E.proto.SyncActionValue.LabelAssociationAction.decode(e,e.uint32());break}case 16:{s.localeSetting=E.proto.SyncActionValue.LocaleSetting.decode(e,e.uint32());break}case 17:{s.archiveChatAction=E.proto.SyncActionValue.ArchiveChatAction.decode(e,e.uint32());break}case 18:{s.deleteMessageForMeAction=E.proto.SyncActionValue.DeleteMessageForMeAction.decode(e,e.uint32());break}case 19:{s.keyExpiration=E.proto.SyncActionValue.KeyExpiration.decode(e,e.uint32());break}case 20:{s.markChatAsReadAction=E.proto.SyncActionValue.MarkChatAsReadAction.decode(e,e.uint32());break}case 21:{s.clearChatAction=E.proto.SyncActionValue.ClearChatAction.decode(e,e.uint32());break}case 22:{s.deleteChatAction=E.proto.SyncActionValue.DeleteChatAction.decode(e,e.uint32());break}case 23:{s.unarchiveChatsSetting=E.proto.SyncActionValue.UnarchiveChatsSetting.decode(e,e.uint32());break}case 24:{s.primaryFeature=E.proto.SyncActionValue.PrimaryFeature.decode(e,e.uint32());break}case 26:{s.androidUnsupportedActions=E.proto.SyncActionValue.AndroidUnsupportedActions.decode(e,e.uint32());break}case 27:{s.agentAction=E.proto.SyncActionValue.AgentAction.decode(e,e.uint32());break}case 28:{s.subscriptionAction=E.proto.SyncActionValue.SubscriptionAction.decode(e,e.uint32());break}case 29:{s.userStatusMuteAction=E.proto.SyncActionValue.UserStatusMuteAction.decode(e,e.uint32());break}case 30:{s.timeFormatAction=E.proto.SyncActionValue.TimeFormatAction.decode(e,e.uint32());break}case 31:{s.nuxAction=E.proto.SyncActionValue.NuxAction.decode(e,e.uint32());break}case 32:{s.primaryVersionAction=E.proto.SyncActionValue.PrimaryVersionAction.decode(e,e.uint32());break}case 33:{s.stickerAction=E.proto.SyncActionValue.StickerAction.decode(e,e.uint32());break}case 34:{s.removeRecentStickerAction=E.proto.SyncActionValue.RemoveRecentStickerAction.decode(e,e.uint32());break}case 35:{s.chatAssignment=E.proto.SyncActionValue.ChatAssignmentAction.decode(e,e.uint32());break}case 36:{s.chatAssignmentOpenedStatus=E.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.decode(e,e.uint32());break}case 37:{s.pnForLidChatAction=E.proto.SyncActionValue.PnForLidChatAction.decode(e,e.uint32());break}case 38:{s.marketingMessageAction=E.proto.SyncActionValue.MarketingMessageAction.decode(e,e.uint32());break}case 39:{s.marketingMessageBroadcastAction=E.proto.SyncActionValue.MarketingMessageBroadcastAction.decode(e,e.uint32());break}case 40:{s.externalWebBetaAction=E.proto.SyncActionValue.ExternalWebBetaAction.decode(e,e.uint32());break}case 41:{s.privacySettingRelayAllCalls=E.proto.SyncActionValue.PrivacySettingRelayAllCalls.decode(e,e.uint32());break}case 42:{s.callLogAction=E.proto.SyncActionValue.CallLogAction.decode(e,e.uint32());break}case 43:{s.ugcBot=E.proto.SyncActionValue.UGCBot.decode(e,e.uint32());break}case 44:{s.statusPrivacy=E.proto.SyncActionValue.StatusPrivacyAction.decode(e,e.uint32());break}case 45:{s.botWelcomeRequestAction=E.proto.SyncActionValue.BotWelcomeRequestAction.decode(e,e.uint32());break}case 46:{s.deleteIndividualCallLog=E.proto.SyncActionValue.DeleteIndividualCallLogAction.decode(e,e.uint32());break}case 47:{s.labelReorderingAction=E.proto.SyncActionValue.LabelReorderingAction.decode(e,e.uint32());break}case 48:{s.paymentInfoAction=E.proto.SyncActionValue.PaymentInfoAction.decode(e,e.uint32());break}case 49:{s.customPaymentMethodsAction=E.proto.SyncActionValue.CustomPaymentMethodsAction.decode(e,e.uint32());break}case 50:{s.lockChatAction=E.proto.SyncActionValue.LockChatAction.decode(e,e.uint32());break}case 51:{s.chatLockSettings=E.proto.ChatLockSettings.decode(e,e.uint32());break}case 52:{s.wamoUserIdentifierAction=E.proto.SyncActionValue.WamoUserIdentifierAction.decode(e,e.uint32());break}case 53:{s.privacySettingDisableLinkPreviewsAction=E.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.decode(e,e.uint32());break}case 54:{s.deviceCapabilities=E.proto.DeviceCapabilities.decode(e,e.uint32());break}case 55:{s.noteEditAction=E.proto.SyncActionValue.NoteEditAction.decode(e,e.uint32());break}case 56:{s.favoritesAction=E.proto.SyncActionValue.FavoritesAction.decode(e,e.uint32());break}case 57:{s.merchantPaymentPartnerAction=E.proto.SyncActionValue.MerchantPaymentPartnerAction.decode(e,e.uint32());break}case 58:{s.waffleAccountLinkStateAction=E.proto.SyncActionValue.WaffleAccountLinkStateAction.decode(e,e.uint32());break}case 59:{s.usernameChatStartMode=E.proto.SyncActionValue.UsernameChatStartModeAction.decode(e,e.uint32());break}case 60:{s.notificationActivitySettingAction=E.proto.SyncActionValue.NotificationActivitySettingAction.decode(e,e.uint32());break}case 61:{s.lidContactAction=E.proto.SyncActionValue.LidContactAction.decode(e,e.uint32());break}case 62:{s.ctwaPerCustomerDataSharingAction=E.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.decode(e,e.uint32());break}case 63:{s.paymentTosAction=E.proto.SyncActionValue.PaymentTosAction.decode(e,e.uint32());break}case 64:{s.privacySettingChannelsPersonalisedRecommendationAction=E.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.decode(e,e.uint32());break}case 65:{s.businessBroadcastAssociationAction=E.proto.SyncActionValue.BusinessBroadcastAssociationAction.decode(e,e.uint32());break}case 66:{s.detectedOutcomesStatusAction=E.proto.SyncActionValue.DetectedOutcomesStatusAction.decode(e,e.uint32());break}case 68:{s.maibaAiFeaturesControlAction=E.proto.SyncActionValue.MaibaAIFeaturesControlAction.decode(e,e.uint32());break}case 69:{s.businessBroadcastListAction=E.proto.SyncActionValue.BusinessBroadcastListAction.decode(e,e.uint32());break}case 70:{s.musicUserIdAction=E.proto.SyncActionValue.MusicUserIdAction.decode(e,e.uint32());break}case 71:{s.statusPostOptInNotificationPreferencesAction=E.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.decode(e,e.uint32());break}case 72:{s.avatarUpdatedAction=E.proto.SyncActionValue.AvatarUpdatedAction.decode(e,e.uint32());break}case 74:{s.privateProcessingSettingAction=E.proto.SyncActionValue.PrivateProcessingSettingAction.decode(e,e.uint32());break}case 75:{s.newsletterSavedInterestsAction=E.proto.SyncActionValue.NewsletterSavedInterestsAction.decode(e,e.uint32());break}case 76:{s.aiThreadRenameAction=E.proto.SyncActionValue.AiThreadRenameAction.decode(e,e.uint32());break}case 77:{s.interactiveMessageAction=E.proto.SyncActionValue.InteractiveMessageAction.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncActionValue)return e;var a=new E.proto.SyncActionValue;if(e.timestamp!=null&&(I.Long?(a.timestamp=I.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new I.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),e.starAction!=null){if(typeof e.starAction!="object")throw TypeError(".proto.SyncActionValue.starAction: object expected");a.starAction=E.proto.SyncActionValue.StarAction.fromObject(e.starAction)}if(e.contactAction!=null){if(typeof e.contactAction!="object")throw TypeError(".proto.SyncActionValue.contactAction: object expected");a.contactAction=E.proto.SyncActionValue.ContactAction.fromObject(e.contactAction)}if(e.muteAction!=null){if(typeof e.muteAction!="object")throw TypeError(".proto.SyncActionValue.muteAction: object expected");a.muteAction=E.proto.SyncActionValue.MuteAction.fromObject(e.muteAction)}if(e.pinAction!=null){if(typeof e.pinAction!="object")throw TypeError(".proto.SyncActionValue.pinAction: object expected");a.pinAction=E.proto.SyncActionValue.PinAction.fromObject(e.pinAction)}if(e.pushNameSetting!=null){if(typeof e.pushNameSetting!="object")throw TypeError(".proto.SyncActionValue.pushNameSetting: object expected");a.pushNameSetting=E.proto.SyncActionValue.PushNameSetting.fromObject(e.pushNameSetting)}if(e.quickReplyAction!=null){if(typeof e.quickReplyAction!="object")throw TypeError(".proto.SyncActionValue.quickReplyAction: object expected");a.quickReplyAction=E.proto.SyncActionValue.QuickReplyAction.fromObject(e.quickReplyAction)}if(e.recentEmojiWeightsAction!=null){if(typeof e.recentEmojiWeightsAction!="object")throw TypeError(".proto.SyncActionValue.recentEmojiWeightsAction: object expected");a.recentEmojiWeightsAction=E.proto.SyncActionValue.RecentEmojiWeightsAction.fromObject(e.recentEmojiWeightsAction)}if(e.labelEditAction!=null){if(typeof e.labelEditAction!="object")throw TypeError(".proto.SyncActionValue.labelEditAction: object expected");a.labelEditAction=E.proto.SyncActionValue.LabelEditAction.fromObject(e.labelEditAction)}if(e.labelAssociationAction!=null){if(typeof e.labelAssociationAction!="object")throw TypeError(".proto.SyncActionValue.labelAssociationAction: object expected");a.labelAssociationAction=E.proto.SyncActionValue.LabelAssociationAction.fromObject(e.labelAssociationAction)}if(e.localeSetting!=null){if(typeof e.localeSetting!="object")throw TypeError(".proto.SyncActionValue.localeSetting: object expected");a.localeSetting=E.proto.SyncActionValue.LocaleSetting.fromObject(e.localeSetting)}if(e.archiveChatAction!=null){if(typeof e.archiveChatAction!="object")throw TypeError(".proto.SyncActionValue.archiveChatAction: object expected");a.archiveChatAction=E.proto.SyncActionValue.ArchiveChatAction.fromObject(e.archiveChatAction)}if(e.deleteMessageForMeAction!=null){if(typeof e.deleteMessageForMeAction!="object")throw TypeError(".proto.SyncActionValue.deleteMessageForMeAction: object expected");a.deleteMessageForMeAction=E.proto.SyncActionValue.DeleteMessageForMeAction.fromObject(e.deleteMessageForMeAction)}if(e.keyExpiration!=null){if(typeof e.keyExpiration!="object")throw TypeError(".proto.SyncActionValue.keyExpiration: object expected");a.keyExpiration=E.proto.SyncActionValue.KeyExpiration.fromObject(e.keyExpiration)}if(e.markChatAsReadAction!=null){if(typeof e.markChatAsReadAction!="object")throw TypeError(".proto.SyncActionValue.markChatAsReadAction: object expected");a.markChatAsReadAction=E.proto.SyncActionValue.MarkChatAsReadAction.fromObject(e.markChatAsReadAction)}if(e.clearChatAction!=null){if(typeof e.clearChatAction!="object")throw TypeError(".proto.SyncActionValue.clearChatAction: object expected");a.clearChatAction=E.proto.SyncActionValue.ClearChatAction.fromObject(e.clearChatAction)}if(e.deleteChatAction!=null){if(typeof e.deleteChatAction!="object")throw TypeError(".proto.SyncActionValue.deleteChatAction: object expected");a.deleteChatAction=E.proto.SyncActionValue.DeleteChatAction.fromObject(e.deleteChatAction)}if(e.unarchiveChatsSetting!=null){if(typeof e.unarchiveChatsSetting!="object")throw TypeError(".proto.SyncActionValue.unarchiveChatsSetting: object expected");a.unarchiveChatsSetting=E.proto.SyncActionValue.UnarchiveChatsSetting.fromObject(e.unarchiveChatsSetting)}if(e.primaryFeature!=null){if(typeof e.primaryFeature!="object")throw TypeError(".proto.SyncActionValue.primaryFeature: object expected");a.primaryFeature=E.proto.SyncActionValue.PrimaryFeature.fromObject(e.primaryFeature)}if(e.androidUnsupportedActions!=null){if(typeof e.androidUnsupportedActions!="object")throw TypeError(".proto.SyncActionValue.androidUnsupportedActions: object expected");a.androidUnsupportedActions=E.proto.SyncActionValue.AndroidUnsupportedActions.fromObject(e.androidUnsupportedActions)}if(e.agentAction!=null){if(typeof e.agentAction!="object")throw TypeError(".proto.SyncActionValue.agentAction: object expected");a.agentAction=E.proto.SyncActionValue.AgentAction.fromObject(e.agentAction)}if(e.subscriptionAction!=null){if(typeof e.subscriptionAction!="object")throw TypeError(".proto.SyncActionValue.subscriptionAction: object expected");a.subscriptionAction=E.proto.SyncActionValue.SubscriptionAction.fromObject(e.subscriptionAction)}if(e.userStatusMuteAction!=null){if(typeof e.userStatusMuteAction!="object")throw TypeError(".proto.SyncActionValue.userStatusMuteAction: object expected");a.userStatusMuteAction=E.proto.SyncActionValue.UserStatusMuteAction.fromObject(e.userStatusMuteAction)}if(e.timeFormatAction!=null){if(typeof e.timeFormatAction!="object")throw TypeError(".proto.SyncActionValue.timeFormatAction: object expected");a.timeFormatAction=E.proto.SyncActionValue.TimeFormatAction.fromObject(e.timeFormatAction)}if(e.nuxAction!=null){if(typeof e.nuxAction!="object")throw TypeError(".proto.SyncActionValue.nuxAction: object expected");a.nuxAction=E.proto.SyncActionValue.NuxAction.fromObject(e.nuxAction)}if(e.primaryVersionAction!=null){if(typeof e.primaryVersionAction!="object")throw TypeError(".proto.SyncActionValue.primaryVersionAction: object expected");a.primaryVersionAction=E.proto.SyncActionValue.PrimaryVersionAction.fromObject(e.primaryVersionAction)}if(e.stickerAction!=null){if(typeof e.stickerAction!="object")throw TypeError(".proto.SyncActionValue.stickerAction: object expected");a.stickerAction=E.proto.SyncActionValue.StickerAction.fromObject(e.stickerAction)}if(e.removeRecentStickerAction!=null){if(typeof e.removeRecentStickerAction!="object")throw TypeError(".proto.SyncActionValue.removeRecentStickerAction: object expected");a.removeRecentStickerAction=E.proto.SyncActionValue.RemoveRecentStickerAction.fromObject(e.removeRecentStickerAction)}if(e.chatAssignment!=null){if(typeof e.chatAssignment!="object")throw TypeError(".proto.SyncActionValue.chatAssignment: object expected");a.chatAssignment=E.proto.SyncActionValue.ChatAssignmentAction.fromObject(e.chatAssignment)}if(e.chatAssignmentOpenedStatus!=null){if(typeof e.chatAssignmentOpenedStatus!="object")throw TypeError(".proto.SyncActionValue.chatAssignmentOpenedStatus: object expected");a.chatAssignmentOpenedStatus=E.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.fromObject(e.chatAssignmentOpenedStatus)}if(e.pnForLidChatAction!=null){if(typeof e.pnForLidChatAction!="object")throw TypeError(".proto.SyncActionValue.pnForLidChatAction: object expected");a.pnForLidChatAction=E.proto.SyncActionValue.PnForLidChatAction.fromObject(e.pnForLidChatAction)}if(e.marketingMessageAction!=null){if(typeof e.marketingMessageAction!="object")throw TypeError(".proto.SyncActionValue.marketingMessageAction: object expected");a.marketingMessageAction=E.proto.SyncActionValue.MarketingMessageAction.fromObject(e.marketingMessageAction)}if(e.marketingMessageBroadcastAction!=null){if(typeof e.marketingMessageBroadcastAction!="object")throw TypeError(".proto.SyncActionValue.marketingMessageBroadcastAction: object expected");a.marketingMessageBroadcastAction=E.proto.SyncActionValue.MarketingMessageBroadcastAction.fromObject(e.marketingMessageBroadcastAction)}if(e.externalWebBetaAction!=null){if(typeof e.externalWebBetaAction!="object")throw TypeError(".proto.SyncActionValue.externalWebBetaAction: object expected");a.externalWebBetaAction=E.proto.SyncActionValue.ExternalWebBetaAction.fromObject(e.externalWebBetaAction)}if(e.privacySettingRelayAllCalls!=null){if(typeof e.privacySettingRelayAllCalls!="object")throw TypeError(".proto.SyncActionValue.privacySettingRelayAllCalls: object expected");a.privacySettingRelayAllCalls=E.proto.SyncActionValue.PrivacySettingRelayAllCalls.fromObject(e.privacySettingRelayAllCalls)}if(e.callLogAction!=null){if(typeof e.callLogAction!="object")throw TypeError(".proto.SyncActionValue.callLogAction: object expected");a.callLogAction=E.proto.SyncActionValue.CallLogAction.fromObject(e.callLogAction)}if(e.ugcBot!=null){if(typeof e.ugcBot!="object")throw TypeError(".proto.SyncActionValue.ugcBot: object expected");a.ugcBot=E.proto.SyncActionValue.UGCBot.fromObject(e.ugcBot)}if(e.statusPrivacy!=null){if(typeof e.statusPrivacy!="object")throw TypeError(".proto.SyncActionValue.statusPrivacy: object expected");a.statusPrivacy=E.proto.SyncActionValue.StatusPrivacyAction.fromObject(e.statusPrivacy)}if(e.botWelcomeRequestAction!=null){if(typeof e.botWelcomeRequestAction!="object")throw TypeError(".proto.SyncActionValue.botWelcomeRequestAction: object expected");a.botWelcomeRequestAction=E.proto.SyncActionValue.BotWelcomeRequestAction.fromObject(e.botWelcomeRequestAction)}if(e.deleteIndividualCallLog!=null){if(typeof e.deleteIndividualCallLog!="object")throw TypeError(".proto.SyncActionValue.deleteIndividualCallLog: object expected");a.deleteIndividualCallLog=E.proto.SyncActionValue.DeleteIndividualCallLogAction.fromObject(e.deleteIndividualCallLog)}if(e.labelReorderingAction!=null){if(typeof e.labelReorderingAction!="object")throw TypeError(".proto.SyncActionValue.labelReorderingAction: object expected");a.labelReorderingAction=E.proto.SyncActionValue.LabelReorderingAction.fromObject(e.labelReorderingAction)}if(e.paymentInfoAction!=null){if(typeof e.paymentInfoAction!="object")throw TypeError(".proto.SyncActionValue.paymentInfoAction: object expected");a.paymentInfoAction=E.proto.SyncActionValue.PaymentInfoAction.fromObject(e.paymentInfoAction)}if(e.customPaymentMethodsAction!=null){if(typeof e.customPaymentMethodsAction!="object")throw TypeError(".proto.SyncActionValue.customPaymentMethodsAction: object expected");a.customPaymentMethodsAction=E.proto.SyncActionValue.CustomPaymentMethodsAction.fromObject(e.customPaymentMethodsAction)}if(e.lockChatAction!=null){if(typeof e.lockChatAction!="object")throw TypeError(".proto.SyncActionValue.lockChatAction: object expected");a.lockChatAction=E.proto.SyncActionValue.LockChatAction.fromObject(e.lockChatAction)}if(e.chatLockSettings!=null){if(typeof e.chatLockSettings!="object")throw TypeError(".proto.SyncActionValue.chatLockSettings: object expected");a.chatLockSettings=E.proto.ChatLockSettings.fromObject(e.chatLockSettings)}if(e.wamoUserIdentifierAction!=null){if(typeof e.wamoUserIdentifierAction!="object")throw TypeError(".proto.SyncActionValue.wamoUserIdentifierAction: object expected");a.wamoUserIdentifierAction=E.proto.SyncActionValue.WamoUserIdentifierAction.fromObject(e.wamoUserIdentifierAction)}if(e.privacySettingDisableLinkPreviewsAction!=null){if(typeof e.privacySettingDisableLinkPreviewsAction!="object")throw TypeError(".proto.SyncActionValue.privacySettingDisableLinkPreviewsAction: object expected");a.privacySettingDisableLinkPreviewsAction=E.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.fromObject(e.privacySettingDisableLinkPreviewsAction)}if(e.deviceCapabilities!=null){if(typeof e.deviceCapabilities!="object")throw TypeError(".proto.SyncActionValue.deviceCapabilities: object expected");a.deviceCapabilities=E.proto.DeviceCapabilities.fromObject(e.deviceCapabilities)}if(e.noteEditAction!=null){if(typeof e.noteEditAction!="object")throw TypeError(".proto.SyncActionValue.noteEditAction: object expected");a.noteEditAction=E.proto.SyncActionValue.NoteEditAction.fromObject(e.noteEditAction)}if(e.favoritesAction!=null){if(typeof e.favoritesAction!="object")throw TypeError(".proto.SyncActionValue.favoritesAction: object expected");a.favoritesAction=E.proto.SyncActionValue.FavoritesAction.fromObject(e.favoritesAction)}if(e.merchantPaymentPartnerAction!=null){if(typeof e.merchantPaymentPartnerAction!="object")throw TypeError(".proto.SyncActionValue.merchantPaymentPartnerAction: object expected");a.merchantPaymentPartnerAction=E.proto.SyncActionValue.MerchantPaymentPartnerAction.fromObject(e.merchantPaymentPartnerAction)}if(e.waffleAccountLinkStateAction!=null){if(typeof e.waffleAccountLinkStateAction!="object")throw TypeError(".proto.SyncActionValue.waffleAccountLinkStateAction: object expected");a.waffleAccountLinkStateAction=E.proto.SyncActionValue.WaffleAccountLinkStateAction.fromObject(e.waffleAccountLinkStateAction)}if(e.usernameChatStartMode!=null){if(typeof e.usernameChatStartMode!="object")throw TypeError(".proto.SyncActionValue.usernameChatStartMode: object expected");a.usernameChatStartMode=E.proto.SyncActionValue.UsernameChatStartModeAction.fromObject(e.usernameChatStartMode)}if(e.notificationActivitySettingAction!=null){if(typeof e.notificationActivitySettingAction!="object")throw TypeError(".proto.SyncActionValue.notificationActivitySettingAction: object expected");a.notificationActivitySettingAction=E.proto.SyncActionValue.NotificationActivitySettingAction.fromObject(e.notificationActivitySettingAction)}if(e.lidContactAction!=null){if(typeof e.lidContactAction!="object")throw TypeError(".proto.SyncActionValue.lidContactAction: object expected");a.lidContactAction=E.proto.SyncActionValue.LidContactAction.fromObject(e.lidContactAction)}if(e.ctwaPerCustomerDataSharingAction!=null){if(typeof e.ctwaPerCustomerDataSharingAction!="object")throw TypeError(".proto.SyncActionValue.ctwaPerCustomerDataSharingAction: object expected");a.ctwaPerCustomerDataSharingAction=E.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.fromObject(e.ctwaPerCustomerDataSharingAction)}if(e.paymentTosAction!=null){if(typeof e.paymentTosAction!="object")throw TypeError(".proto.SyncActionValue.paymentTosAction: object expected");a.paymentTosAction=E.proto.SyncActionValue.PaymentTosAction.fromObject(e.paymentTosAction)}if(e.privacySettingChannelsPersonalisedRecommendationAction!=null){if(typeof e.privacySettingChannelsPersonalisedRecommendationAction!="object")throw TypeError(".proto.SyncActionValue.privacySettingChannelsPersonalisedRecommendationAction: object expected");a.privacySettingChannelsPersonalisedRecommendationAction=E.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.fromObject(e.privacySettingChannelsPersonalisedRecommendationAction)}if(e.businessBroadcastAssociationAction!=null){if(typeof e.businessBroadcastAssociationAction!="object")throw TypeError(".proto.SyncActionValue.businessBroadcastAssociationAction: object expected");a.businessBroadcastAssociationAction=E.proto.SyncActionValue.BusinessBroadcastAssociationAction.fromObject(e.businessBroadcastAssociationAction)}if(e.detectedOutcomesStatusAction!=null){if(typeof e.detectedOutcomesStatusAction!="object")throw TypeError(".proto.SyncActionValue.detectedOutcomesStatusAction: object expected");a.detectedOutcomesStatusAction=E.proto.SyncActionValue.DetectedOutcomesStatusAction.fromObject(e.detectedOutcomesStatusAction)}if(e.maibaAiFeaturesControlAction!=null){if(typeof e.maibaAiFeaturesControlAction!="object")throw TypeError(".proto.SyncActionValue.maibaAiFeaturesControlAction: object expected");a.maibaAiFeaturesControlAction=E.proto.SyncActionValue.MaibaAIFeaturesControlAction.fromObject(e.maibaAiFeaturesControlAction)}if(e.businessBroadcastListAction!=null){if(typeof e.businessBroadcastListAction!="object")throw TypeError(".proto.SyncActionValue.businessBroadcastListAction: object expected");a.businessBroadcastListAction=E.proto.SyncActionValue.BusinessBroadcastListAction.fromObject(e.businessBroadcastListAction)}if(e.musicUserIdAction!=null){if(typeof e.musicUserIdAction!="object")throw TypeError(".proto.SyncActionValue.musicUserIdAction: object expected");a.musicUserIdAction=E.proto.SyncActionValue.MusicUserIdAction.fromObject(e.musicUserIdAction)}if(e.statusPostOptInNotificationPreferencesAction!=null){if(typeof e.statusPostOptInNotificationPreferencesAction!="object")throw TypeError(".proto.SyncActionValue.statusPostOptInNotificationPreferencesAction: object expected");a.statusPostOptInNotificationPreferencesAction=E.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.fromObject(e.statusPostOptInNotificationPreferencesAction)}if(e.avatarUpdatedAction!=null){if(typeof e.avatarUpdatedAction!="object")throw TypeError(".proto.SyncActionValue.avatarUpdatedAction: object expected");a.avatarUpdatedAction=E.proto.SyncActionValue.AvatarUpdatedAction.fromObject(e.avatarUpdatedAction)}if(e.privateProcessingSettingAction!=null){if(typeof e.privateProcessingSettingAction!="object")throw TypeError(".proto.SyncActionValue.privateProcessingSettingAction: object expected");a.privateProcessingSettingAction=E.proto.SyncActionValue.PrivateProcessingSettingAction.fromObject(e.privateProcessingSettingAction)}if(e.newsletterSavedInterestsAction!=null){if(typeof e.newsletterSavedInterestsAction!="object")throw TypeError(".proto.SyncActionValue.newsletterSavedInterestsAction: object expected");a.newsletterSavedInterestsAction=E.proto.SyncActionValue.NewsletterSavedInterestsAction.fromObject(e.newsletterSavedInterestsAction)}if(e.aiThreadRenameAction!=null){if(typeof e.aiThreadRenameAction!="object")throw TypeError(".proto.SyncActionValue.aiThreadRenameAction: object expected");a.aiThreadRenameAction=E.proto.SyncActionValue.AiThreadRenameAction.fromObject(e.aiThreadRenameAction)}if(e.interactiveMessageAction!=null){if(typeof e.interactiveMessageAction!="object")throw TypeError(".proto.SyncActionValue.interactiveMessageAction: object expected");a.interactiveMessageAction=E.proto.SyncActionValue.InteractiveMessageAction.fromObject(e.interactiveMessageAction)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?re(e.timestamp):a.longs===Number?ae(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.starAction!=null&&e.hasOwnProperty("starAction")&&(A.starAction=E.proto.SyncActionValue.StarAction.toObject(e.starAction,a),a.oneofs&&(A._starAction="starAction")),e.contactAction!=null&&e.hasOwnProperty("contactAction")&&(A.contactAction=E.proto.SyncActionValue.ContactAction.toObject(e.contactAction,a),a.oneofs&&(A._contactAction="contactAction")),e.muteAction!=null&&e.hasOwnProperty("muteAction")&&(A.muteAction=E.proto.SyncActionValue.MuteAction.toObject(e.muteAction,a),a.oneofs&&(A._muteAction="muteAction")),e.pinAction!=null&&e.hasOwnProperty("pinAction")&&(A.pinAction=E.proto.SyncActionValue.PinAction.toObject(e.pinAction,a),a.oneofs&&(A._pinAction="pinAction")),e.pushNameSetting!=null&&e.hasOwnProperty("pushNameSetting")&&(A.pushNameSetting=E.proto.SyncActionValue.PushNameSetting.toObject(e.pushNameSetting,a),a.oneofs&&(A._pushNameSetting="pushNameSetting")),e.quickReplyAction!=null&&e.hasOwnProperty("quickReplyAction")&&(A.quickReplyAction=E.proto.SyncActionValue.QuickReplyAction.toObject(e.quickReplyAction,a),a.oneofs&&(A._quickReplyAction="quickReplyAction")),e.recentEmojiWeightsAction!=null&&e.hasOwnProperty("recentEmojiWeightsAction")&&(A.recentEmojiWeightsAction=E.proto.SyncActionValue.RecentEmojiWeightsAction.toObject(e.recentEmojiWeightsAction,a),a.oneofs&&(A._recentEmojiWeightsAction="recentEmojiWeightsAction")),e.labelEditAction!=null&&e.hasOwnProperty("labelEditAction")&&(A.labelEditAction=E.proto.SyncActionValue.LabelEditAction.toObject(e.labelEditAction,a),a.oneofs&&(A._labelEditAction="labelEditAction")),e.labelAssociationAction!=null&&e.hasOwnProperty("labelAssociationAction")&&(A.labelAssociationAction=E.proto.SyncActionValue.LabelAssociationAction.toObject(e.labelAssociationAction,a),a.oneofs&&(A._labelAssociationAction="labelAssociationAction")),e.localeSetting!=null&&e.hasOwnProperty("localeSetting")&&(A.localeSetting=E.proto.SyncActionValue.LocaleSetting.toObject(e.localeSetting,a),a.oneofs&&(A._localeSetting="localeSetting")),e.archiveChatAction!=null&&e.hasOwnProperty("archiveChatAction")&&(A.archiveChatAction=E.proto.SyncActionValue.ArchiveChatAction.toObject(e.archiveChatAction,a),a.oneofs&&(A._archiveChatAction="archiveChatAction")),e.deleteMessageForMeAction!=null&&e.hasOwnProperty("deleteMessageForMeAction")&&(A.deleteMessageForMeAction=E.proto.SyncActionValue.DeleteMessageForMeAction.toObject(e.deleteMessageForMeAction,a),a.oneofs&&(A._deleteMessageForMeAction="deleteMessageForMeAction")),e.keyExpiration!=null&&e.hasOwnProperty("keyExpiration")&&(A.keyExpiration=E.proto.SyncActionValue.KeyExpiration.toObject(e.keyExpiration,a),a.oneofs&&(A._keyExpiration="keyExpiration")),e.markChatAsReadAction!=null&&e.hasOwnProperty("markChatAsReadAction")&&(A.markChatAsReadAction=E.proto.SyncActionValue.MarkChatAsReadAction.toObject(e.markChatAsReadAction,a),a.oneofs&&(A._markChatAsReadAction="markChatAsReadAction")),e.clearChatAction!=null&&e.hasOwnProperty("clearChatAction")&&(A.clearChatAction=E.proto.SyncActionValue.ClearChatAction.toObject(e.clearChatAction,a),a.oneofs&&(A._clearChatAction="clearChatAction")),e.deleteChatAction!=null&&e.hasOwnProperty("deleteChatAction")&&(A.deleteChatAction=E.proto.SyncActionValue.DeleteChatAction.toObject(e.deleteChatAction,a),a.oneofs&&(A._deleteChatAction="deleteChatAction")),e.unarchiveChatsSetting!=null&&e.hasOwnProperty("unarchiveChatsSetting")&&(A.unarchiveChatsSetting=E.proto.SyncActionValue.UnarchiveChatsSetting.toObject(e.unarchiveChatsSetting,a),a.oneofs&&(A._unarchiveChatsSetting="unarchiveChatsSetting")),e.primaryFeature!=null&&e.hasOwnProperty("primaryFeature")&&(A.primaryFeature=E.proto.SyncActionValue.PrimaryFeature.toObject(e.primaryFeature,a),a.oneofs&&(A._primaryFeature="primaryFeature")),e.androidUnsupportedActions!=null&&e.hasOwnProperty("androidUnsupportedActions")&&(A.androidUnsupportedActions=E.proto.SyncActionValue.AndroidUnsupportedActions.toObject(e.androidUnsupportedActions,a),a.oneofs&&(A._androidUnsupportedActions="androidUnsupportedActions")),e.agentAction!=null&&e.hasOwnProperty("agentAction")&&(A.agentAction=E.proto.SyncActionValue.AgentAction.toObject(e.agentAction,a),a.oneofs&&(A._agentAction="agentAction")),e.subscriptionAction!=null&&e.hasOwnProperty("subscriptionAction")&&(A.subscriptionAction=E.proto.SyncActionValue.SubscriptionAction.toObject(e.subscriptionAction,a),a.oneofs&&(A._subscriptionAction="subscriptionAction")),e.userStatusMuteAction!=null&&e.hasOwnProperty("userStatusMuteAction")&&(A.userStatusMuteAction=E.proto.SyncActionValue.UserStatusMuteAction.toObject(e.userStatusMuteAction,a),a.oneofs&&(A._userStatusMuteAction="userStatusMuteAction")),e.timeFormatAction!=null&&e.hasOwnProperty("timeFormatAction")&&(A.timeFormatAction=E.proto.SyncActionValue.TimeFormatAction.toObject(e.timeFormatAction,a),a.oneofs&&(A._timeFormatAction="timeFormatAction")),e.nuxAction!=null&&e.hasOwnProperty("nuxAction")&&(A.nuxAction=E.proto.SyncActionValue.NuxAction.toObject(e.nuxAction,a),a.oneofs&&(A._nuxAction="nuxAction")),e.primaryVersionAction!=null&&e.hasOwnProperty("primaryVersionAction")&&(A.primaryVersionAction=E.proto.SyncActionValue.PrimaryVersionAction.toObject(e.primaryVersionAction,a),a.oneofs&&(A._primaryVersionAction="primaryVersionAction")),e.stickerAction!=null&&e.hasOwnProperty("stickerAction")&&(A.stickerAction=E.proto.SyncActionValue.StickerAction.toObject(e.stickerAction,a),a.oneofs&&(A._stickerAction="stickerAction")),e.removeRecentStickerAction!=null&&e.hasOwnProperty("removeRecentStickerAction")&&(A.removeRecentStickerAction=E.proto.SyncActionValue.RemoveRecentStickerAction.toObject(e.removeRecentStickerAction,a),a.oneofs&&(A._removeRecentStickerAction="removeRecentStickerAction")),e.chatAssignment!=null&&e.hasOwnProperty("chatAssignment")&&(A.chatAssignment=E.proto.SyncActionValue.ChatAssignmentAction.toObject(e.chatAssignment,a),a.oneofs&&(A._chatAssignment="chatAssignment")),e.chatAssignmentOpenedStatus!=null&&e.hasOwnProperty("chatAssignmentOpenedStatus")&&(A.chatAssignmentOpenedStatus=E.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.toObject(e.chatAssignmentOpenedStatus,a),a.oneofs&&(A._chatAssignmentOpenedStatus="chatAssignmentOpenedStatus")),e.pnForLidChatAction!=null&&e.hasOwnProperty("pnForLidChatAction")&&(A.pnForLidChatAction=E.proto.SyncActionValue.PnForLidChatAction.toObject(e.pnForLidChatAction,a),a.oneofs&&(A._pnForLidChatAction="pnForLidChatAction")),e.marketingMessageAction!=null&&e.hasOwnProperty("marketingMessageAction")&&(A.marketingMessageAction=E.proto.SyncActionValue.MarketingMessageAction.toObject(e.marketingMessageAction,a),a.oneofs&&(A._marketingMessageAction="marketingMessageAction")),e.marketingMessageBroadcastAction!=null&&e.hasOwnProperty("marketingMessageBroadcastAction")&&(A.marketingMessageBroadcastAction=E.proto.SyncActionValue.MarketingMessageBroadcastAction.toObject(e.marketingMessageBroadcastAction,a),a.oneofs&&(A._marketingMessageBroadcastAction="marketingMessageBroadcastAction")),e.externalWebBetaAction!=null&&e.hasOwnProperty("externalWebBetaAction")&&(A.externalWebBetaAction=E.proto.SyncActionValue.ExternalWebBetaAction.toObject(e.externalWebBetaAction,a),a.oneofs&&(A._externalWebBetaAction="externalWebBetaAction")),e.privacySettingRelayAllCalls!=null&&e.hasOwnProperty("privacySettingRelayAllCalls")&&(A.privacySettingRelayAllCalls=E.proto.SyncActionValue.PrivacySettingRelayAllCalls.toObject(e.privacySettingRelayAllCalls,a),a.oneofs&&(A._privacySettingRelayAllCalls="privacySettingRelayAllCalls")),e.callLogAction!=null&&e.hasOwnProperty("callLogAction")&&(A.callLogAction=E.proto.SyncActionValue.CallLogAction.toObject(e.callLogAction,a),a.oneofs&&(A._callLogAction="callLogAction")),e.ugcBot!=null&&e.hasOwnProperty("ugcBot")&&(A.ugcBot=E.proto.SyncActionValue.UGCBot.toObject(e.ugcBot,a),a.oneofs&&(A._ugcBot="ugcBot")),e.statusPrivacy!=null&&e.hasOwnProperty("statusPrivacy")&&(A.statusPrivacy=E.proto.SyncActionValue.StatusPrivacyAction.toObject(e.statusPrivacy,a),a.oneofs&&(A._statusPrivacy="statusPrivacy")),e.botWelcomeRequestAction!=null&&e.hasOwnProperty("botWelcomeRequestAction")&&(A.botWelcomeRequestAction=E.proto.SyncActionValue.BotWelcomeRequestAction.toObject(e.botWelcomeRequestAction,a),a.oneofs&&(A._botWelcomeRequestAction="botWelcomeRequestAction")),e.deleteIndividualCallLog!=null&&e.hasOwnProperty("deleteIndividualCallLog")&&(A.deleteIndividualCallLog=E.proto.SyncActionValue.DeleteIndividualCallLogAction.toObject(e.deleteIndividualCallLog,a),a.oneofs&&(A._deleteIndividualCallLog="deleteIndividualCallLog")),e.labelReorderingAction!=null&&e.hasOwnProperty("labelReorderingAction")&&(A.labelReorderingAction=E.proto.SyncActionValue.LabelReorderingAction.toObject(e.labelReorderingAction,a),a.oneofs&&(A._labelReorderingAction="labelReorderingAction")),e.paymentInfoAction!=null&&e.hasOwnProperty("paymentInfoAction")&&(A.paymentInfoAction=E.proto.SyncActionValue.PaymentInfoAction.toObject(e.paymentInfoAction,a),a.oneofs&&(A._paymentInfoAction="paymentInfoAction")),e.customPaymentMethodsAction!=null&&e.hasOwnProperty("customPaymentMethodsAction")&&(A.customPaymentMethodsAction=E.proto.SyncActionValue.CustomPaymentMethodsAction.toObject(e.customPaymentMethodsAction,a),a.oneofs&&(A._customPaymentMethodsAction="customPaymentMethodsAction")),e.lockChatAction!=null&&e.hasOwnProperty("lockChatAction")&&(A.lockChatAction=E.proto.SyncActionValue.LockChatAction.toObject(e.lockChatAction,a),a.oneofs&&(A._lockChatAction="lockChatAction")),e.chatLockSettings!=null&&e.hasOwnProperty("chatLockSettings")&&(A.chatLockSettings=E.proto.ChatLockSettings.toObject(e.chatLockSettings,a),a.oneofs&&(A._chatLockSettings="chatLockSettings")),e.wamoUserIdentifierAction!=null&&e.hasOwnProperty("wamoUserIdentifierAction")&&(A.wamoUserIdentifierAction=E.proto.SyncActionValue.WamoUserIdentifierAction.toObject(e.wamoUserIdentifierAction,a),a.oneofs&&(A._wamoUserIdentifierAction="wamoUserIdentifierAction")),e.privacySettingDisableLinkPreviewsAction!=null&&e.hasOwnProperty("privacySettingDisableLinkPreviewsAction")&&(A.privacySettingDisableLinkPreviewsAction=E.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.toObject(e.privacySettingDisableLinkPreviewsAction,a),a.oneofs&&(A._privacySettingDisableLinkPreviewsAction="privacySettingDisableLinkPreviewsAction")),e.deviceCapabilities!=null&&e.hasOwnProperty("deviceCapabilities")&&(A.deviceCapabilities=E.proto.DeviceCapabilities.toObject(e.deviceCapabilities,a),a.oneofs&&(A._deviceCapabilities="deviceCapabilities")),e.noteEditAction!=null&&e.hasOwnProperty("noteEditAction")&&(A.noteEditAction=E.proto.SyncActionValue.NoteEditAction.toObject(e.noteEditAction,a),a.oneofs&&(A._noteEditAction="noteEditAction")),e.favoritesAction!=null&&e.hasOwnProperty("favoritesAction")&&(A.favoritesAction=E.proto.SyncActionValue.FavoritesAction.toObject(e.favoritesAction,a),a.oneofs&&(A._favoritesAction="favoritesAction")),e.merchantPaymentPartnerAction!=null&&e.hasOwnProperty("merchantPaymentPartnerAction")&&(A.merchantPaymentPartnerAction=E.proto.SyncActionValue.MerchantPaymentPartnerAction.toObject(e.merchantPaymentPartnerAction,a),a.oneofs&&(A._merchantPaymentPartnerAction="merchantPaymentPartnerAction")),e.waffleAccountLinkStateAction!=null&&e.hasOwnProperty("waffleAccountLinkStateAction")&&(A.waffleAccountLinkStateAction=E.proto.SyncActionValue.WaffleAccountLinkStateAction.toObject(e.waffleAccountLinkStateAction,a),a.oneofs&&(A._waffleAccountLinkStateAction="waffleAccountLinkStateAction")),e.usernameChatStartMode!=null&&e.hasOwnProperty("usernameChatStartMode")&&(A.usernameChatStartMode=E.proto.SyncActionValue.UsernameChatStartModeAction.toObject(e.usernameChatStartMode,a),a.oneofs&&(A._usernameChatStartMode="usernameChatStartMode")),e.notificationActivitySettingAction!=null&&e.hasOwnProperty("notificationActivitySettingAction")&&(A.notificationActivitySettingAction=E.proto.SyncActionValue.NotificationActivitySettingAction.toObject(e.notificationActivitySettingAction,a),a.oneofs&&(A._notificationActivitySettingAction="notificationActivitySettingAction")),e.lidContactAction!=null&&e.hasOwnProperty("lidContactAction")&&(A.lidContactAction=E.proto.SyncActionValue.LidContactAction.toObject(e.lidContactAction,a),a.oneofs&&(A._lidContactAction="lidContactAction")),e.ctwaPerCustomerDataSharingAction!=null&&e.hasOwnProperty("ctwaPerCustomerDataSharingAction")&&(A.ctwaPerCustomerDataSharingAction=E.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.toObject(e.ctwaPerCustomerDataSharingAction,a),a.oneofs&&(A._ctwaPerCustomerDataSharingAction="ctwaPerCustomerDataSharingAction")),e.paymentTosAction!=null&&e.hasOwnProperty("paymentTosAction")&&(A.paymentTosAction=E.proto.SyncActionValue.PaymentTosAction.toObject(e.paymentTosAction,a),a.oneofs&&(A._paymentTosAction="paymentTosAction")),e.privacySettingChannelsPersonalisedRecommendationAction!=null&&e.hasOwnProperty("privacySettingChannelsPersonalisedRecommendationAction")&&(A.privacySettingChannelsPersonalisedRecommendationAction=E.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.toObject(e.privacySettingChannelsPersonalisedRecommendationAction,a),a.oneofs&&(A._privacySettingChannelsPersonalisedRecommendationAction="privacySettingChannelsPersonalisedRecommendationAction")),e.businessBroadcastAssociationAction!=null&&e.hasOwnProperty("businessBroadcastAssociationAction")&&(A.businessBroadcastAssociationAction=E.proto.SyncActionValue.BusinessBroadcastAssociationAction.toObject(e.businessBroadcastAssociationAction,a),a.oneofs&&(A._businessBroadcastAssociationAction="businessBroadcastAssociationAction")),e.detectedOutcomesStatusAction!=null&&e.hasOwnProperty("detectedOutcomesStatusAction")&&(A.detectedOutcomesStatusAction=E.proto.SyncActionValue.DetectedOutcomesStatusAction.toObject(e.detectedOutcomesStatusAction,a),a.oneofs&&(A._detectedOutcomesStatusAction="detectedOutcomesStatusAction")),e.maibaAiFeaturesControlAction!=null&&e.hasOwnProperty("maibaAiFeaturesControlAction")&&(A.maibaAiFeaturesControlAction=E.proto.SyncActionValue.MaibaAIFeaturesControlAction.toObject(e.maibaAiFeaturesControlAction,a),a.oneofs&&(A._maibaAiFeaturesControlAction="maibaAiFeaturesControlAction")),e.businessBroadcastListAction!=null&&e.hasOwnProperty("businessBroadcastListAction")&&(A.businessBroadcastListAction=E.proto.SyncActionValue.BusinessBroadcastListAction.toObject(e.businessBroadcastListAction,a),a.oneofs&&(A._businessBroadcastListAction="businessBroadcastListAction")),e.musicUserIdAction!=null&&e.hasOwnProperty("musicUserIdAction")&&(A.musicUserIdAction=E.proto.SyncActionValue.MusicUserIdAction.toObject(e.musicUserIdAction,a),a.oneofs&&(A._musicUserIdAction="musicUserIdAction")),e.statusPostOptInNotificationPreferencesAction!=null&&e.hasOwnProperty("statusPostOptInNotificationPreferencesAction")&&(A.statusPostOptInNotificationPreferencesAction=E.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.toObject(e.statusPostOptInNotificationPreferencesAction,a),a.oneofs&&(A._statusPostOptInNotificationPreferencesAction="statusPostOptInNotificationPreferencesAction")),e.avatarUpdatedAction!=null&&e.hasOwnProperty("avatarUpdatedAction")&&(A.avatarUpdatedAction=E.proto.SyncActionValue.AvatarUpdatedAction.toObject(e.avatarUpdatedAction,a),a.oneofs&&(A._avatarUpdatedAction="avatarUpdatedAction")),e.privateProcessingSettingAction!=null&&e.hasOwnProperty("privateProcessingSettingAction")&&(A.privateProcessingSettingAction=E.proto.SyncActionValue.PrivateProcessingSettingAction.toObject(e.privateProcessingSettingAction,a),a.oneofs&&(A._privateProcessingSettingAction="privateProcessingSettingAction")),e.newsletterSavedInterestsAction!=null&&e.hasOwnProperty("newsletterSavedInterestsAction")&&(A.newsletterSavedInterestsAction=E.proto.SyncActionValue.NewsletterSavedInterestsAction.toObject(e.newsletterSavedInterestsAction,a),a.oneofs&&(A._newsletterSavedInterestsAction="newsletterSavedInterestsAction")),e.aiThreadRenameAction!=null&&e.hasOwnProperty("aiThreadRenameAction")&&(A.aiThreadRenameAction=E.proto.SyncActionValue.AiThreadRenameAction.toObject(e.aiThreadRenameAction,a),a.oneofs&&(A._aiThreadRenameAction="aiThreadRenameAction")),e.interactiveMessageAction!=null&&e.hasOwnProperty("interactiveMessageAction")&&(A.interactiveMessageAction=E.proto.SyncActionValue.InteractiveMessageAction.toObject(e.interactiveMessageAction,a),a.oneofs&&(A._interactiveMessageAction="interactiveMessageAction")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncActionValue"},r.AgentAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.name=A.string();break}case 2:{c.deviceID=A.int32();break}case 3:{c.isDeleted=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.AgentAction)return A;var t=new E.proto.SyncActionValue.AgentAction;return A.name!=null&&(t.name=String(A.name)),A.deviceID!=null&&(t.deviceID=A.deviceID|0),A.isDeleted!=null&&(t.isDeleted=!!A.isDeleted),t},i.toObject=function(A,t){t||(t={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.deviceID!=null&&A.hasOwnProperty("deviceID")&&(s.deviceID=A.deviceID,t.oneofs&&(s._deviceID="deviceID")),A.isDeleted!=null&&A.hasOwnProperty("isDeleted")&&(s.isDeleted=A.isDeleted,t.oneofs&&(s._isDeleted="isDeleted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AgentAction"},i})(),r.AiThreadRenameAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.newTitle=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.AiThreadRenameAction)return A;var t=new E.proto.SyncActionValue.AiThreadRenameAction;return A.newTitle!=null&&(t.newTitle=String(A.newTitle)),t},i.toObject=function(A,t){t||(t={});var s={};return A.newTitle!=null&&A.hasOwnProperty("newTitle")&&(s.newTitle=A.newTitle,t.oneofs&&(s._newTitle="newTitle")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AiThreadRenameAction"},i})(),r.AndroidUnsupportedActions=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.allowed=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.AndroidUnsupportedActions)return A;var t=new E.proto.SyncActionValue.AndroidUnsupportedActions;return A.allowed!=null&&(t.allowed=!!A.allowed),t},i.toObject=function(A,t){t||(t={});var s={};return A.allowed!=null&&A.hasOwnProperty("allowed")&&(s.allowed=A.allowed,t.oneofs&&(s._allowed="allowed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AndroidUnsupportedActions"},i})(),r.ArchiveChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.archived=A.bool();break}case 2:{c.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.ArchiveChatAction)return A;var t=new E.proto.SyncActionValue.ArchiveChatAction;if(A.archived!=null&&(t.archived=!!A.archived),A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.ArchiveChatAction.messageRange: object expected");t.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.archived!=null&&A.hasOwnProperty("archived")&&(s.archived=A.archived,t.oneofs&&(s._archived="archived")),A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,t),t.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ArchiveChatAction"},i})(),r.AvatarUpdatedAction=(function(){function i(a){if(this.recentAvatarStickers=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.eventType=A.int32();break}case 2:{c.recentAvatarStickers&&c.recentAvatarStickers.length||(c.recentAvatarStickers=[]),c.recentAvatarStickers.push(E.proto.SyncActionValue.StickerAction.decode(A,A.uint32()));break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.AvatarUpdatedAction)return A;var t=new E.proto.SyncActionValue.AvatarUpdatedAction;switch(A.eventType){default:if(typeof A.eventType=="number"){t.eventType=A.eventType;break}break;case"UPDATED":case 0:t.eventType=0;break;case"CREATED":case 1:t.eventType=1;break;case"DELETED":case 2:t.eventType=2;break}if(A.recentAvatarStickers){if(!Array.isArray(A.recentAvatarStickers))throw TypeError(".proto.SyncActionValue.AvatarUpdatedAction.recentAvatarStickers: array expected");t.recentAvatarStickers=[];for(var s=0;s>>3){case 1:{c.isSent=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.BotWelcomeRequestAction)return A;var t=new E.proto.SyncActionValue.BotWelcomeRequestAction;return A.isSent!=null&&(t.isSent=!!A.isSent),t},i.toObject=function(A,t){t||(t={});var s={};return A.isSent!=null&&A.hasOwnProperty("isSent")&&(s.isSent=A.isSent,t.oneofs&&(s._isSent="isSent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BotWelcomeRequestAction"},i})(),r.BroadcastListParticipant=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.lidJid=A.string();break}case 2:{c.pnJid=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.BroadcastListParticipant)return A;var t=new E.proto.SyncActionValue.BroadcastListParticipant;return A.lidJid!=null&&(t.lidJid=String(A.lidJid)),A.pnJid!=null&&(t.pnJid=String(A.pnJid)),t},i.toObject=function(A,t){t||(t={});var s={};return t.defaults&&(s.lidJid=""),A.lidJid!=null&&A.hasOwnProperty("lidJid")&&(s.lidJid=A.lidJid),A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,t.oneofs&&(s._pnJid="pnJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BroadcastListParticipant"},i})(),r.BusinessBroadcastAssociationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.deleted=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.BusinessBroadcastAssociationAction)return A;var t=new E.proto.SyncActionValue.BusinessBroadcastAssociationAction;return A.deleted!=null&&(t.deleted=!!A.deleted),t},i.toObject=function(A,t){t||(t={});var s={};return A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,t.oneofs&&(s._deleted="deleted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BusinessBroadcastAssociationAction"},i})(),r.BusinessBroadcastListAction=(function(){function i(a){if(this.participants=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.deleted=A.bool();break}case 2:{c.participants&&c.participants.length||(c.participants=[]),c.participants.push(E.proto.SyncActionValue.BroadcastListParticipant.decode(A,A.uint32()));break}case 3:{c.listName=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.BusinessBroadcastListAction)return A;var t=new E.proto.SyncActionValue.BusinessBroadcastListAction;if(A.deleted!=null&&(t.deleted=!!A.deleted),A.participants){if(!Array.isArray(A.participants))throw TypeError(".proto.SyncActionValue.BusinessBroadcastListAction.participants: array expected");t.participants=[];for(var s=0;s>>3){case 1:{c.callLogRecord=E.proto.CallLogRecord.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.CallLogAction)return A;var t=new E.proto.SyncActionValue.CallLogAction;if(A.callLogRecord!=null){if(typeof A.callLogRecord!="object")throw TypeError(".proto.SyncActionValue.CallLogAction.callLogRecord: object expected");t.callLogRecord=E.proto.CallLogRecord.fromObject(A.callLogRecord)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.callLogRecord!=null&&A.hasOwnProperty("callLogRecord")&&(s.callLogRecord=E.proto.CallLogRecord.toObject(A.callLogRecord,t),t.oneofs&&(s._callLogRecord="callLogRecord")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.CallLogAction"},i})(),r.ChatAssignmentAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.deviceAgentID=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.ChatAssignmentAction)return A;var t=new E.proto.SyncActionValue.ChatAssignmentAction;return A.deviceAgentID!=null&&(t.deviceAgentID=String(A.deviceAgentID)),t},i.toObject=function(A,t){t||(t={});var s={};return A.deviceAgentID!=null&&A.hasOwnProperty("deviceAgentID")&&(s.deviceAgentID=A.deviceAgentID,t.oneofs&&(s._deviceAgentID="deviceAgentID")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ChatAssignmentAction"},i})(),r.ChatAssignmentOpenedStatusAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.chatOpened=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.ChatAssignmentOpenedStatusAction)return A;var t=new E.proto.SyncActionValue.ChatAssignmentOpenedStatusAction;return A.chatOpened!=null&&(t.chatOpened=!!A.chatOpened),t},i.toObject=function(A,t){t||(t={});var s={};return A.chatOpened!=null&&A.hasOwnProperty("chatOpened")&&(s.chatOpened=A.chatOpened,t.oneofs&&(s._chatOpened="chatOpened")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ChatAssignmentOpenedStatusAction"},i})(),r.ClearChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.ClearChatAction)return A;var t=new E.proto.SyncActionValue.ClearChatAction;if(A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.ClearChatAction.messageRange: object expected");t.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,t),t.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ClearChatAction"},i})(),r.ContactAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.fullName=A.string();break}case 2:{c.firstName=A.string();break}case 3:{c.lidJid=A.string();break}case 4:{c.saveOnPrimaryAddressbook=A.bool();break}case 5:{c.pnJid=A.string();break}case 6:{c.username=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.ContactAction)return A;var t=new E.proto.SyncActionValue.ContactAction;return A.fullName!=null&&(t.fullName=String(A.fullName)),A.firstName!=null&&(t.firstName=String(A.firstName)),A.lidJid!=null&&(t.lidJid=String(A.lidJid)),A.saveOnPrimaryAddressbook!=null&&(t.saveOnPrimaryAddressbook=!!A.saveOnPrimaryAddressbook),A.pnJid!=null&&(t.pnJid=String(A.pnJid)),A.username!=null&&(t.username=String(A.username)),t},i.toObject=function(A,t){t||(t={});var s={};return A.fullName!=null&&A.hasOwnProperty("fullName")&&(s.fullName=A.fullName,t.oneofs&&(s._fullName="fullName")),A.firstName!=null&&A.hasOwnProperty("firstName")&&(s.firstName=A.firstName,t.oneofs&&(s._firstName="firstName")),A.lidJid!=null&&A.hasOwnProperty("lidJid")&&(s.lidJid=A.lidJid,t.oneofs&&(s._lidJid="lidJid")),A.saveOnPrimaryAddressbook!=null&&A.hasOwnProperty("saveOnPrimaryAddressbook")&&(s.saveOnPrimaryAddressbook=A.saveOnPrimaryAddressbook,t.oneofs&&(s._saveOnPrimaryAddressbook="saveOnPrimaryAddressbook")),A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,t.oneofs&&(s._pnJid="pnJid")),A.username!=null&&A.hasOwnProperty("username")&&(s.username=A.username,t.oneofs&&(s._username="username")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ContactAction"},i})(),r.CtwaPerCustomerDataSharingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isCtwaPerCustomerDataSharingEnabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.CtwaPerCustomerDataSharingAction)return A;var t=new E.proto.SyncActionValue.CtwaPerCustomerDataSharingAction;return A.isCtwaPerCustomerDataSharingEnabled!=null&&(t.isCtwaPerCustomerDataSharingEnabled=!!A.isCtwaPerCustomerDataSharingEnabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.isCtwaPerCustomerDataSharingEnabled!=null&&A.hasOwnProperty("isCtwaPerCustomerDataSharingEnabled")&&(s.isCtwaPerCustomerDataSharingEnabled=A.isCtwaPerCustomerDataSharingEnabled,t.oneofs&&(s._isCtwaPerCustomerDataSharingEnabled="isCtwaPerCustomerDataSharingEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.CtwaPerCustomerDataSharingAction"},i})(),r.CustomPaymentMethod=(function(){function i(e){if(this.metadata=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.credentialId=a.string();break}case 2:{g.country=a.string();break}case 3:{g.type=a.string();break}case 4:{g.metadata&&g.metadata.length||(g.metadata=[]),g.metadata.push(E.proto.SyncActionValue.CustomPaymentMethodMetadata.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.CustomPaymentMethod)return a;var A=new E.proto.SyncActionValue.CustomPaymentMethod;if(a.credentialId!=null&&(A.credentialId=String(a.credentialId)),a.country!=null&&(A.country=String(a.country)),a.type!=null&&(A.type=String(a.type)),a.metadata){if(!Array.isArray(a.metadata))throw TypeError(".proto.SyncActionValue.CustomPaymentMethod.metadata: array expected");A.metadata=[];for(var t=0;t>>3){case 1:{g.key=a.string();break}case 2:{g.value=a.string();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.CustomPaymentMethodMetadata)return a;var A=new E.proto.SyncActionValue.CustomPaymentMethodMetadata;return a.key!=null&&(A.key=String(a.key)),a.value!=null&&(A.value=String(a.value)),A},i.toObject=function(a,A){A||(A={});var t={};return A.defaults&&(t.key="",t.value=""),a.key!=null&&a.hasOwnProperty("key")&&(t.key=a.key),a.value!=null&&a.hasOwnProperty("value")&&(t.value=a.value),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.CustomPaymentMethodMetadata"},i})(),r.CustomPaymentMethodsAction=(function(){function i(e){if(this.customPaymentMethods=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.customPaymentMethods&&g.customPaymentMethods.length||(g.customPaymentMethods=[]),g.customPaymentMethods.push(E.proto.SyncActionValue.CustomPaymentMethod.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.CustomPaymentMethodsAction)return a;var A=new E.proto.SyncActionValue.CustomPaymentMethodsAction;if(a.customPaymentMethods){if(!Array.isArray(a.customPaymentMethods))throw TypeError(".proto.SyncActionValue.CustomPaymentMethodsAction.customPaymentMethods: array expected");A.customPaymentMethods=[];for(var t=0;t>>3){case 1:{c.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.DeleteChatAction)return A;var t=new E.proto.SyncActionValue.DeleteChatAction;if(A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.DeleteChatAction.messageRange: object expected");t.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,t),t.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteChatAction"},i})(),r.DeleteIndividualCallLogAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.peerJid=A.string();break}case 2:{c.isIncoming=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.DeleteIndividualCallLogAction)return A;var t=new E.proto.SyncActionValue.DeleteIndividualCallLogAction;return A.peerJid!=null&&(t.peerJid=String(A.peerJid)),A.isIncoming!=null&&(t.isIncoming=!!A.isIncoming),t},i.toObject=function(A,t){t||(t={});var s={};return A.peerJid!=null&&A.hasOwnProperty("peerJid")&&(s.peerJid=A.peerJid,t.oneofs&&(s._peerJid="peerJid")),A.isIncoming!=null&&A.hasOwnProperty("isIncoming")&&(s.isIncoming=A.isIncoming,t.oneofs&&(s._isIncoming="isIncoming")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteIndividualCallLogAction"},i})(),r.DeleteMessageForMeAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.deleteMedia=A.bool();break}case 2:{c.messageTimestamp=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.DeleteMessageForMeAction)return A;var t=new E.proto.SyncActionValue.DeleteMessageForMeAction;return A.deleteMedia!=null&&(t.deleteMedia=!!A.deleteMedia),A.messageTimestamp!=null&&(I.Long?(t.messageTimestamp=I.Long.fromValue(A.messageTimestamp)).unsigned=!1:typeof A.messageTimestamp=="string"?t.messageTimestamp=parseInt(A.messageTimestamp,10):typeof A.messageTimestamp=="number"?t.messageTimestamp=A.messageTimestamp:typeof A.messageTimestamp=="object"&&(t.messageTimestamp=new I.LongBits(A.messageTimestamp.low>>>0,A.messageTimestamp.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.deleteMedia!=null&&A.hasOwnProperty("deleteMedia")&&(s.deleteMedia=A.deleteMedia,t.oneofs&&(s._deleteMedia="deleteMedia")),A.messageTimestamp!=null&&A.hasOwnProperty("messageTimestamp")&&(typeof A.messageTimestamp=="number"?s.messageTimestamp=t.longs===String?String(A.messageTimestamp):A.messageTimestamp:s.messageTimestamp=t.longs===String?re(A.messageTimestamp):t.longs===Number?ae(A.messageTimestamp):A.messageTimestamp,t.oneofs&&(s._messageTimestamp="messageTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteMessageForMeAction"},i})(),r.DetectedOutcomesStatusAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isEnabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.DetectedOutcomesStatusAction)return A;var t=new E.proto.SyncActionValue.DetectedOutcomesStatusAction;return A.isEnabled!=null&&(t.isEnabled=!!A.isEnabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.isEnabled!=null&&A.hasOwnProperty("isEnabled")&&(s.isEnabled=A.isEnabled,t.oneofs&&(s._isEnabled="isEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DetectedOutcomesStatusAction"},i})(),r.ExternalWebBetaAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isOptIn=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.ExternalWebBetaAction)return A;var t=new E.proto.SyncActionValue.ExternalWebBetaAction;return A.isOptIn!=null&&(t.isOptIn=!!A.isOptIn),t},i.toObject=function(A,t){t||(t={});var s={};return A.isOptIn!=null&&A.hasOwnProperty("isOptIn")&&(s.isOptIn=A.isOptIn,t.oneofs&&(s._isOptIn="isOptIn")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ExternalWebBetaAction"},i})(),r.FavoritesAction=(function(){function i(e){if(this.favorites=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.favorites&&g.favorites.length||(g.favorites=[]),g.favorites.push(E.proto.SyncActionValue.FavoritesAction.Favorite.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.FavoritesAction)return a;var A=new E.proto.SyncActionValue.FavoritesAction;if(a.favorites){if(!Array.isArray(a.favorites))throw TypeError(".proto.SyncActionValue.FavoritesAction.favorites: array expected");A.favorites=[];for(var t=0;t>>3){case 1:{l.id=t.string();break}default:t.skipType(p&7);break}}return l},e.fromObject=function(t){if(t instanceof E.proto.SyncActionValue.FavoritesAction.Favorite)return t;var s=new E.proto.SyncActionValue.FavoritesAction.Favorite;return t.id!=null&&(s.id=String(t.id)),s},e.toObject=function(t,s){s||(s={});var g={};return t.id!=null&&t.hasOwnProperty("id")&&(g.id=t.id,s.oneofs&&(g._id="id")),g},e.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},e.getTypeUrl=function(t){return t===void 0&&(t="type.googleapis.com"),t+"/proto.SyncActionValue.FavoritesAction.Favorite"},e})(),i})(),r.InteractiveMessageAction=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.type=a.int32();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.InteractiveMessageAction)return a;var A=new E.proto.SyncActionValue.InteractiveMessageAction;switch(a.type){default:if(typeof a.type=="number"){A.type=a.type;break}break;case"DISABLE_CTA":case 1:A.type=1;break}return A},i.toObject=function(a,A){A||(A={});var t={};return A.defaults&&(t.type=A.enums===String?"DISABLE_CTA":1),a.type!=null&&a.hasOwnProperty("type")&&(t.type=A.enums===String?E.proto.SyncActionValue.InteractiveMessageAction.InteractiveMessageActionMode[a.type]===void 0?a.type:E.proto.SyncActionValue.InteractiveMessageAction.InteractiveMessageActionMode[a.type]:a.type),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.InteractiveMessageAction"},i.InteractiveMessageActionMode=(function(){let e={},a=Object.create(e);return a[e[1]="DISABLE_CTA"]=1,a})(),i})(),r.KeyExpiration=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.expiredKeyEpoch=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.KeyExpiration)return A;var t=new E.proto.SyncActionValue.KeyExpiration;return A.expiredKeyEpoch!=null&&(t.expiredKeyEpoch=A.expiredKeyEpoch|0),t},i.toObject=function(A,t){t||(t={});var s={};return A.expiredKeyEpoch!=null&&A.hasOwnProperty("expiredKeyEpoch")&&(s.expiredKeyEpoch=A.expiredKeyEpoch,t.oneofs&&(s._expiredKeyEpoch="expiredKeyEpoch")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.KeyExpiration"},i})(),r.LabelAssociationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.labeled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.LabelAssociationAction)return A;var t=new E.proto.SyncActionValue.LabelAssociationAction;return A.labeled!=null&&(t.labeled=!!A.labeled),t},i.toObject=function(A,t){t||(t={});var s={};return A.labeled!=null&&A.hasOwnProperty("labeled")&&(s.labeled=A.labeled,t.oneofs&&(s._labeled="labeled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LabelAssociationAction"},i})(),r.LabelEditAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.name=A.string();break}case 2:{c.color=A.int32();break}case 3:{c.predefinedId=A.int32();break}case 4:{c.deleted=A.bool();break}case 5:{c.orderIndex=A.int32();break}case 6:{c.isActive=A.bool();break}case 7:{c.type=A.int32();break}case 8:{c.isImmutable=A.bool();break}case 9:{c.muteEndTimeMs=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.LabelEditAction)return A;var t=new E.proto.SyncActionValue.LabelEditAction;switch(A.name!=null&&(t.name=String(A.name)),A.color!=null&&(t.color=A.color|0),A.predefinedId!=null&&(t.predefinedId=A.predefinedId|0),A.deleted!=null&&(t.deleted=!!A.deleted),A.orderIndex!=null&&(t.orderIndex=A.orderIndex|0),A.isActive!=null&&(t.isActive=!!A.isActive),A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"NONE":case 0:t.type=0;break;case"UNREAD":case 1:t.type=1;break;case"GROUPS":case 2:t.type=2;break;case"FAVORITES":case 3:t.type=3;break;case"PREDEFINED":case 4:t.type=4;break;case"CUSTOM":case 5:t.type=5;break;case"COMMUNITY":case 6:t.type=6;break;case"SERVER_ASSIGNED":case 7:t.type=7;break;case"DRAFTED":case 8:t.type=8;break;case"AI_HANDOFF":case 9:t.type=9;break}return A.isImmutable!=null&&(t.isImmutable=!!A.isImmutable),A.muteEndTimeMs!=null&&(I.Long?(t.muteEndTimeMs=I.Long.fromValue(A.muteEndTimeMs)).unsigned=!1:typeof A.muteEndTimeMs=="string"?t.muteEndTimeMs=parseInt(A.muteEndTimeMs,10):typeof A.muteEndTimeMs=="number"?t.muteEndTimeMs=A.muteEndTimeMs:typeof A.muteEndTimeMs=="object"&&(t.muteEndTimeMs=new I.LongBits(A.muteEndTimeMs.low>>>0,A.muteEndTimeMs.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.color!=null&&A.hasOwnProperty("color")&&(s.color=A.color,t.oneofs&&(s._color="color")),A.predefinedId!=null&&A.hasOwnProperty("predefinedId")&&(s.predefinedId=A.predefinedId,t.oneofs&&(s._predefinedId="predefinedId")),A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,t.oneofs&&(s._deleted="deleted")),A.orderIndex!=null&&A.hasOwnProperty("orderIndex")&&(s.orderIndex=A.orderIndex,t.oneofs&&(s._orderIndex="orderIndex")),A.isActive!=null&&A.hasOwnProperty("isActive")&&(s.isActive=A.isActive,t.oneofs&&(s._isActive="isActive")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.SyncActionValue.LabelEditAction.ListType[A.type]===void 0?A.type:E.proto.SyncActionValue.LabelEditAction.ListType[A.type]:A.type,t.oneofs&&(s._type="type")),A.isImmutable!=null&&A.hasOwnProperty("isImmutable")&&(s.isImmutable=A.isImmutable,t.oneofs&&(s._isImmutable="isImmutable")),A.muteEndTimeMs!=null&&A.hasOwnProperty("muteEndTimeMs")&&(typeof A.muteEndTimeMs=="number"?s.muteEndTimeMs=t.longs===String?String(A.muteEndTimeMs):A.muteEndTimeMs:s.muteEndTimeMs=t.longs===String?re(A.muteEndTimeMs):t.longs===Number?ae(A.muteEndTimeMs):A.muteEndTimeMs,t.oneofs&&(s._muteEndTimeMs="muteEndTimeMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LabelEditAction"},i.ListType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="UNREAD"]=1,A[a[2]="GROUPS"]=2,A[a[3]="FAVORITES"]=3,A[a[4]="PREDEFINED"]=4,A[a[5]="CUSTOM"]=5,A[a[6]="COMMUNITY"]=6,A[a[7]="SERVER_ASSIGNED"]=7,A[a[8]="DRAFTED"]=8,A[a[9]="AI_HANDOFF"]=9,A})(),i})(),r.LabelReorderingAction=(function(){function i(e){if(this.sortedLabelIds=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{if(g.sortedLabelIds&&g.sortedLabelIds.length||(g.sortedLabelIds=[]),(c&7)===2)for(var l=a.uint32()+a.pos;a.pos>>3){case 1:{c.fullName=A.string();break}case 2:{c.firstName=A.string();break}case 3:{c.username=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.LidContactAction)return A;var t=new E.proto.SyncActionValue.LidContactAction;return A.fullName!=null&&(t.fullName=String(A.fullName)),A.firstName!=null&&(t.firstName=String(A.firstName)),A.username!=null&&(t.username=String(A.username)),t},i.toObject=function(A,t){t||(t={});var s={};return A.fullName!=null&&A.hasOwnProperty("fullName")&&(s.fullName=A.fullName,t.oneofs&&(s._fullName="fullName")),A.firstName!=null&&A.hasOwnProperty("firstName")&&(s.firstName=A.firstName,t.oneofs&&(s._firstName="firstName")),A.username!=null&&A.hasOwnProperty("username")&&(s.username=A.username,t.oneofs&&(s._username="username")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LidContactAction"},i})(),r.LocaleSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.locale=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.LocaleSetting)return A;var t=new E.proto.SyncActionValue.LocaleSetting;return A.locale!=null&&(t.locale=String(A.locale)),t},i.toObject=function(A,t){t||(t={});var s={};return A.locale!=null&&A.hasOwnProperty("locale")&&(s.locale=A.locale,t.oneofs&&(s._locale="locale")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LocaleSetting"},i})(),r.LockChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.locked=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.LockChatAction)return A;var t=new E.proto.SyncActionValue.LockChatAction;return A.locked!=null&&(t.locked=!!A.locked),t},i.toObject=function(A,t){t||(t={});var s={};return A.locked!=null&&A.hasOwnProperty("locked")&&(s.locked=A.locked,t.oneofs&&(s._locked="locked")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LockChatAction"},i})(),r.MaibaAIFeaturesControlAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.aiFeatureStatus=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.MaibaAIFeaturesControlAction)return A;var t=new E.proto.SyncActionValue.MaibaAIFeaturesControlAction;switch(A.aiFeatureStatus){default:if(typeof A.aiFeatureStatus=="number"){t.aiFeatureStatus=A.aiFeatureStatus;break}break;case"ENABLED":case 0:t.aiFeatureStatus=0;break;case"ENABLED_HAS_LEARNING":case 1:t.aiFeatureStatus=1;break;case"DISABLED":case 2:t.aiFeatureStatus=2;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.aiFeatureStatus!=null&&A.hasOwnProperty("aiFeatureStatus")&&(s.aiFeatureStatus=t.enums===String?E.proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIFeatureStatus[A.aiFeatureStatus]===void 0?A.aiFeatureStatus:E.proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIFeatureStatus[A.aiFeatureStatus]:A.aiFeatureStatus,t.oneofs&&(s._aiFeatureStatus="aiFeatureStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MaibaAIFeaturesControlAction"},i.MaibaAIFeatureStatus=(function(){let a={},A=Object.create(a);return A[a[0]="ENABLED"]=0,A[a[1]="ENABLED_HAS_LEARNING"]=1,A[a[2]="DISABLED"]=2,A})(),i})(),r.MarkChatAsReadAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.read=A.bool();break}case 2:{c.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.MarkChatAsReadAction)return A;var t=new E.proto.SyncActionValue.MarkChatAsReadAction;if(A.read!=null&&(t.read=!!A.read),A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.MarkChatAsReadAction.messageRange: object expected");t.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.read!=null&&A.hasOwnProperty("read")&&(s.read=A.read,t.oneofs&&(s._read="read")),A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=E.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,t),t.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarkChatAsReadAction"},i})(),r.MarketingMessageAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.name=A.string();break}case 2:{c.message=A.string();break}case 3:{c.type=A.int32();break}case 4:{c.createdAt=A.int64();break}case 5:{c.lastSentAt=A.int64();break}case 6:{c.isDeleted=A.bool();break}case 7:{c.mediaId=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.MarketingMessageAction)return A;var t=new E.proto.SyncActionValue.MarketingMessageAction;switch(A.name!=null&&(t.name=String(A.name)),A.message!=null&&(t.message=String(A.message)),A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"PERSONALIZED":case 0:t.type=0;break}return A.createdAt!=null&&(I.Long?(t.createdAt=I.Long.fromValue(A.createdAt)).unsigned=!1:typeof A.createdAt=="string"?t.createdAt=parseInt(A.createdAt,10):typeof A.createdAt=="number"?t.createdAt=A.createdAt:typeof A.createdAt=="object"&&(t.createdAt=new I.LongBits(A.createdAt.low>>>0,A.createdAt.high>>>0).toNumber())),A.lastSentAt!=null&&(I.Long?(t.lastSentAt=I.Long.fromValue(A.lastSentAt)).unsigned=!1:typeof A.lastSentAt=="string"?t.lastSentAt=parseInt(A.lastSentAt,10):typeof A.lastSentAt=="number"?t.lastSentAt=A.lastSentAt:typeof A.lastSentAt=="object"&&(t.lastSentAt=new I.LongBits(A.lastSentAt.low>>>0,A.lastSentAt.high>>>0).toNumber())),A.isDeleted!=null&&(t.isDeleted=!!A.isDeleted),A.mediaId!=null&&(t.mediaId=String(A.mediaId)),t},i.toObject=function(A,t){t||(t={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=A.message,t.oneofs&&(s._message="message")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.SyncActionValue.MarketingMessageAction.MarketingMessagePrototypeType[A.type]===void 0?A.type:E.proto.SyncActionValue.MarketingMessageAction.MarketingMessagePrototypeType[A.type]:A.type,t.oneofs&&(s._type="type")),A.createdAt!=null&&A.hasOwnProperty("createdAt")&&(typeof A.createdAt=="number"?s.createdAt=t.longs===String?String(A.createdAt):A.createdAt:s.createdAt=t.longs===String?re(A.createdAt):t.longs===Number?ae(A.createdAt):A.createdAt,t.oneofs&&(s._createdAt="createdAt")),A.lastSentAt!=null&&A.hasOwnProperty("lastSentAt")&&(typeof A.lastSentAt=="number"?s.lastSentAt=t.longs===String?String(A.lastSentAt):A.lastSentAt:s.lastSentAt=t.longs===String?re(A.lastSentAt):t.longs===Number?ae(A.lastSentAt):A.lastSentAt,t.oneofs&&(s._lastSentAt="lastSentAt")),A.isDeleted!=null&&A.hasOwnProperty("isDeleted")&&(s.isDeleted=A.isDeleted,t.oneofs&&(s._isDeleted="isDeleted")),A.mediaId!=null&&A.hasOwnProperty("mediaId")&&(s.mediaId=A.mediaId,t.oneofs&&(s._mediaId="mediaId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarketingMessageAction"},i.MarketingMessagePrototypeType=(function(){let a={},A=Object.create(a);return A[a[0]="PERSONALIZED"]=0,A})(),i})(),r.MarketingMessageBroadcastAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.repliedCount=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.MarketingMessageBroadcastAction)return A;var t=new E.proto.SyncActionValue.MarketingMessageBroadcastAction;return A.repliedCount!=null&&(t.repliedCount=A.repliedCount|0),t},i.toObject=function(A,t){t||(t={});var s={};return A.repliedCount!=null&&A.hasOwnProperty("repliedCount")&&(s.repliedCount=A.repliedCount,t.oneofs&&(s._repliedCount="repliedCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarketingMessageBroadcastAction"},i})(),r.MerchantPaymentPartnerAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.status=A.int32();break}case 2:{c.country=A.string();break}case 3:{c.gatewayName=A.string();break}case 4:{c.credentialId=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.MerchantPaymentPartnerAction)return A;var t=new E.proto.SyncActionValue.MerchantPaymentPartnerAction;switch(A.status){default:if(typeof A.status=="number"){t.status=A.status;break}break;case"ACTIVE":case 0:t.status=0;break;case"INACTIVE":case 1:t.status=1;break}return A.country!=null&&(t.country=String(A.country)),A.gatewayName!=null&&(t.gatewayName=String(A.gatewayName)),A.credentialId!=null&&(t.credentialId=String(A.credentialId)),t},i.toObject=function(A,t){t||(t={});var s={};return t.defaults&&(s.status=t.enums===String?"ACTIVE":0,s.country=""),A.status!=null&&A.hasOwnProperty("status")&&(s.status=t.enums===String?E.proto.SyncActionValue.MerchantPaymentPartnerAction.Status[A.status]===void 0?A.status:E.proto.SyncActionValue.MerchantPaymentPartnerAction.Status[A.status]:A.status),A.country!=null&&A.hasOwnProperty("country")&&(s.country=A.country),A.gatewayName!=null&&A.hasOwnProperty("gatewayName")&&(s.gatewayName=A.gatewayName,t.oneofs&&(s._gatewayName="gatewayName")),A.credentialId!=null&&A.hasOwnProperty("credentialId")&&(s.credentialId=A.credentialId,t.oneofs&&(s._credentialId="credentialId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MerchantPaymentPartnerAction"},i.Status=(function(){let a={},A=Object.create(a);return A[a[0]="ACTIVE"]=0,A[a[1]="INACTIVE"]=1,A})(),i})(),r.MusicUserIdAction=(function(){function i(a){if(this.musicUserIdMap={},a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.musicUserId=A.string();break}case 2:{c.musicUserIdMap===I.emptyObject&&(c.musicUserIdMap={});var Q=A.uint32()+A.pos;for(l="",p="";A.pos>>3){case 1:l=A.string();break;case 2:p=A.string();break;default:A.skipType(f&7);break}}c.musicUserIdMap[l]=p;break}default:A.skipType(B&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.MusicUserIdAction)return A;var t=new E.proto.SyncActionValue.MusicUserIdAction;if(A.musicUserId!=null&&(t.musicUserId=String(A.musicUserId)),A.musicUserIdMap){if(typeof A.musicUserIdMap!="object")throw TypeError(".proto.SyncActionValue.MusicUserIdAction.musicUserIdMap: object expected");t.musicUserIdMap={};for(var s=Object.keys(A.musicUserIdMap),g=0;g>>3){case 1:{c.muted=A.bool();break}case 2:{c.muteEndTimestamp=A.int64();break}case 3:{c.autoMuted=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.MuteAction)return A;var t=new E.proto.SyncActionValue.MuteAction;return A.muted!=null&&(t.muted=!!A.muted),A.muteEndTimestamp!=null&&(I.Long?(t.muteEndTimestamp=I.Long.fromValue(A.muteEndTimestamp)).unsigned=!1:typeof A.muteEndTimestamp=="string"?t.muteEndTimestamp=parseInt(A.muteEndTimestamp,10):typeof A.muteEndTimestamp=="number"?t.muteEndTimestamp=A.muteEndTimestamp:typeof A.muteEndTimestamp=="object"&&(t.muteEndTimestamp=new I.LongBits(A.muteEndTimestamp.low>>>0,A.muteEndTimestamp.high>>>0).toNumber())),A.autoMuted!=null&&(t.autoMuted=!!A.autoMuted),t},i.toObject=function(A,t){t||(t={});var s={};return A.muted!=null&&A.hasOwnProperty("muted")&&(s.muted=A.muted,t.oneofs&&(s._muted="muted")),A.muteEndTimestamp!=null&&A.hasOwnProperty("muteEndTimestamp")&&(typeof A.muteEndTimestamp=="number"?s.muteEndTimestamp=t.longs===String?String(A.muteEndTimestamp):A.muteEndTimestamp:s.muteEndTimestamp=t.longs===String?re(A.muteEndTimestamp):t.longs===Number?ae(A.muteEndTimestamp):A.muteEndTimestamp,t.oneofs&&(s._muteEndTimestamp="muteEndTimestamp")),A.autoMuted!=null&&A.hasOwnProperty("autoMuted")&&(s.autoMuted=A.autoMuted,t.oneofs&&(s._autoMuted="autoMuted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MuteAction"},i})(),r.NewsletterSavedInterestsAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.newsletterSavedInterests=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.NewsletterSavedInterestsAction)return A;var t=new E.proto.SyncActionValue.NewsletterSavedInterestsAction;return A.newsletterSavedInterests!=null&&(t.newsletterSavedInterests=String(A.newsletterSavedInterests)),t},i.toObject=function(A,t){t||(t={});var s={};return A.newsletterSavedInterests!=null&&A.hasOwnProperty("newsletterSavedInterests")&&(s.newsletterSavedInterests=A.newsletterSavedInterests,t.oneofs&&(s._newsletterSavedInterests="newsletterSavedInterests")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NewsletterSavedInterestsAction"},i})(),r.NoteEditAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.type=A.int32();break}case 2:{c.chatJid=A.string();break}case 3:{c.createdAt=A.int64();break}case 4:{c.deleted=A.bool();break}case 5:{c.unstructuredContent=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.NoteEditAction)return A;var t=new E.proto.SyncActionValue.NoteEditAction;switch(A.type){default:if(typeof A.type=="number"){t.type=A.type;break}break;case"UNSTRUCTURED":case 1:t.type=1;break;case"STRUCTURED":case 2:t.type=2;break}return A.chatJid!=null&&(t.chatJid=String(A.chatJid)),A.createdAt!=null&&(I.Long?(t.createdAt=I.Long.fromValue(A.createdAt)).unsigned=!1:typeof A.createdAt=="string"?t.createdAt=parseInt(A.createdAt,10):typeof A.createdAt=="number"?t.createdAt=A.createdAt:typeof A.createdAt=="object"&&(t.createdAt=new I.LongBits(A.createdAt.low>>>0,A.createdAt.high>>>0).toNumber())),A.deleted!=null&&(t.deleted=!!A.deleted),A.unstructuredContent!=null&&(t.unstructuredContent=String(A.unstructuredContent)),t},i.toObject=function(A,t){t||(t={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=t.enums===String?E.proto.SyncActionValue.NoteEditAction.NoteType[A.type]===void 0?A.type:E.proto.SyncActionValue.NoteEditAction.NoteType[A.type]:A.type,t.oneofs&&(s._type="type")),A.chatJid!=null&&A.hasOwnProperty("chatJid")&&(s.chatJid=A.chatJid,t.oneofs&&(s._chatJid="chatJid")),A.createdAt!=null&&A.hasOwnProperty("createdAt")&&(typeof A.createdAt=="number"?s.createdAt=t.longs===String?String(A.createdAt):A.createdAt:s.createdAt=t.longs===String?re(A.createdAt):t.longs===Number?ae(A.createdAt):A.createdAt,t.oneofs&&(s._createdAt="createdAt")),A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,t.oneofs&&(s._deleted="deleted")),A.unstructuredContent!=null&&A.hasOwnProperty("unstructuredContent")&&(s.unstructuredContent=A.unstructuredContent,t.oneofs&&(s._unstructuredContent="unstructuredContent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NoteEditAction"},i.NoteType=(function(){let a={},A=Object.create(a);return A[a[1]="UNSTRUCTURED"]=1,A[a[2]="STRUCTURED"]=2,A})(),i})(),r.NotificationActivitySettingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.notificationActivitySetting=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.NotificationActivitySettingAction)return A;var t=new E.proto.SyncActionValue.NotificationActivitySettingAction;switch(A.notificationActivitySetting){default:if(typeof A.notificationActivitySetting=="number"){t.notificationActivitySetting=A.notificationActivitySetting;break}break;case"DEFAULT_ALL_MESSAGES":case 0:t.notificationActivitySetting=0;break;case"ALL_MESSAGES":case 1:t.notificationActivitySetting=1;break;case"HIGHLIGHTS":case 2:t.notificationActivitySetting=2;break;case"DEFAULT_HIGHLIGHTS":case 3:t.notificationActivitySetting=3;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.notificationActivitySetting!=null&&A.hasOwnProperty("notificationActivitySetting")&&(s.notificationActivitySetting=t.enums===String?E.proto.SyncActionValue.NotificationActivitySettingAction.NotificationActivitySetting[A.notificationActivitySetting]===void 0?A.notificationActivitySetting:E.proto.SyncActionValue.NotificationActivitySettingAction.NotificationActivitySetting[A.notificationActivitySetting]:A.notificationActivitySetting,t.oneofs&&(s._notificationActivitySetting="notificationActivitySetting")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NotificationActivitySettingAction"},i.NotificationActivitySetting=(function(){let a={},A=Object.create(a);return A[a[0]="DEFAULT_ALL_MESSAGES"]=0,A[a[1]="ALL_MESSAGES"]=1,A[a[2]="HIGHLIGHTS"]=2,A[a[3]="DEFAULT_HIGHLIGHTS"]=3,A})(),i})(),r.NuxAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.acknowledged=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.NuxAction)return A;var t=new E.proto.SyncActionValue.NuxAction;return A.acknowledged!=null&&(t.acknowledged=!!A.acknowledged),t},i.toObject=function(A,t){t||(t={});var s={};return A.acknowledged!=null&&A.hasOwnProperty("acknowledged")&&(s.acknowledged=A.acknowledged,t.oneofs&&(s._acknowledged="acknowledged")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NuxAction"},i})(),r.PaymentInfoAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.cpi=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PaymentInfoAction)return A;var t=new E.proto.SyncActionValue.PaymentInfoAction;return A.cpi!=null&&(t.cpi=String(A.cpi)),t},i.toObject=function(A,t){t||(t={});var s={};return A.cpi!=null&&A.hasOwnProperty("cpi")&&(s.cpi=A.cpi,t.oneofs&&(s._cpi="cpi")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PaymentInfoAction"},i})(),r.PaymentTosAction=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.paymentNotice=a.int32();break}case 2:{g.accepted=a.bool();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.PaymentTosAction)return a;var A=new E.proto.SyncActionValue.PaymentTosAction;switch(a.paymentNotice){default:if(typeof a.paymentNotice=="number"){A.paymentNotice=a.paymentNotice;break}break;case"BR_PAY_PRIVACY_POLICY":case 0:A.paymentNotice=0;break}return a.accepted!=null&&(A.accepted=!!a.accepted),A},i.toObject=function(a,A){A||(A={});var t={};return A.defaults&&(t.paymentNotice=A.enums===String?"BR_PAY_PRIVACY_POLICY":0,t.accepted=!1),a.paymentNotice!=null&&a.hasOwnProperty("paymentNotice")&&(t.paymentNotice=A.enums===String?E.proto.SyncActionValue.PaymentTosAction.PaymentNotice[a.paymentNotice]===void 0?a.paymentNotice:E.proto.SyncActionValue.PaymentTosAction.PaymentNotice[a.paymentNotice]:a.paymentNotice),a.accepted!=null&&a.hasOwnProperty("accepted")&&(t.accepted=a.accepted),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.PaymentTosAction"},i.PaymentNotice=(function(){let e={},a=Object.create(e);return a[e[0]="BR_PAY_PRIVACY_POLICY"]=0,a})(),i})(),r.PinAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.pinned=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PinAction)return A;var t=new E.proto.SyncActionValue.PinAction;return A.pinned!=null&&(t.pinned=!!A.pinned),t},i.toObject=function(A,t){t||(t={});var s={};return A.pinned!=null&&A.hasOwnProperty("pinned")&&(s.pinned=A.pinned,t.oneofs&&(s._pinned="pinned")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PinAction"},i})(),r.PnForLidChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.pnJid=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PnForLidChatAction)return A;var t=new E.proto.SyncActionValue.PnForLidChatAction;return A.pnJid!=null&&(t.pnJid=String(A.pnJid)),t},i.toObject=function(A,t){t||(t={});var s={};return A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,t.oneofs&&(s._pnJid="pnJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PnForLidChatAction"},i})(),r.PrimaryFeature=(function(){function i(e){if(this.flags=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.flags&&g.flags.length||(g.flags=[]),g.flags.push(a.string());break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.PrimaryFeature)return a;var A=new E.proto.SyncActionValue.PrimaryFeature;if(a.flags){if(!Array.isArray(a.flags))throw TypeError(".proto.SyncActionValue.PrimaryFeature.flags: array expected");A.flags=[];for(var t=0;t>>3){case 1:{c.version=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PrimaryVersionAction)return A;var t=new E.proto.SyncActionValue.PrimaryVersionAction;return A.version!=null&&(t.version=String(A.version)),t},i.toObject=function(A,t){t||(t={});var s={};return A.version!=null&&A.hasOwnProperty("version")&&(s.version=A.version,t.oneofs&&(s._version="version")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrimaryVersionAction"},i})(),r.PrivacySettingChannelsPersonalisedRecommendationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isUserOptedOut=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction)return A;var t=new E.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction;return A.isUserOptedOut!=null&&(t.isUserOptedOut=!!A.isUserOptedOut),t},i.toObject=function(A,t){t||(t={});var s={};return A.isUserOptedOut!=null&&A.hasOwnProperty("isUserOptedOut")&&(s.isUserOptedOut=A.isUserOptedOut,t.oneofs&&(s._isUserOptedOut="isUserOptedOut")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction"},i})(),r.PrivacySettingDisableLinkPreviewsAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isPreviewsDisabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction)return A;var t=new E.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction;return A.isPreviewsDisabled!=null&&(t.isPreviewsDisabled=!!A.isPreviewsDisabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.isPreviewsDisabled!=null&&A.hasOwnProperty("isPreviewsDisabled")&&(s.isPreviewsDisabled=A.isPreviewsDisabled,t.oneofs&&(s._isPreviewsDisabled="isPreviewsDisabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction"},i})(),r.PrivacySettingRelayAllCalls=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isEnabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PrivacySettingRelayAllCalls)return A;var t=new E.proto.SyncActionValue.PrivacySettingRelayAllCalls;return A.isEnabled!=null&&(t.isEnabled=!!A.isEnabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.isEnabled!=null&&A.hasOwnProperty("isEnabled")&&(s.isEnabled=A.isEnabled,t.oneofs&&(s._isEnabled="isEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingRelayAllCalls"},i})(),r.PrivateProcessingSettingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.privateProcessingStatus=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PrivateProcessingSettingAction)return A;var t=new E.proto.SyncActionValue.PrivateProcessingSettingAction;switch(A.privateProcessingStatus){default:if(typeof A.privateProcessingStatus=="number"){t.privateProcessingStatus=A.privateProcessingStatus;break}break;case"UNDEFINED":case 0:t.privateProcessingStatus=0;break;case"ENABLED":case 1:t.privateProcessingStatus=1;break;case"DISABLED":case 2:t.privateProcessingStatus=2;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.privateProcessingStatus!=null&&A.hasOwnProperty("privateProcessingStatus")&&(s.privateProcessingStatus=t.enums===String?E.proto.SyncActionValue.PrivateProcessingSettingAction.PrivateProcessingStatus[A.privateProcessingStatus]===void 0?A.privateProcessingStatus:E.proto.SyncActionValue.PrivateProcessingSettingAction.PrivateProcessingStatus[A.privateProcessingStatus]:A.privateProcessingStatus,t.oneofs&&(s._privateProcessingStatus="privateProcessingStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivateProcessingSettingAction"},i.PrivateProcessingStatus=(function(){let a={},A=Object.create(a);return A[a[0]="UNDEFINED"]=0,A[a[1]="ENABLED"]=1,A[a[2]="DISABLED"]=2,A})(),i})(),r.PushNameSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.name=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.PushNameSetting)return A;var t=new E.proto.SyncActionValue.PushNameSetting;return A.name!=null&&(t.name=String(A.name)),t},i.toObject=function(A,t){t||(t={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,t.oneofs&&(s._name="name")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PushNameSetting"},i})(),r.QuickReplyAction=(function(){function i(a){if(this.keywords=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.shortcut=A.string();break}case 2:{c.message=A.string();break}case 3:{c.keywords&&c.keywords.length||(c.keywords=[]),c.keywords.push(A.string());break}case 4:{c.count=A.int32();break}case 5:{c.deleted=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.QuickReplyAction)return A;var t=new E.proto.SyncActionValue.QuickReplyAction;if(A.shortcut!=null&&(t.shortcut=String(A.shortcut)),A.message!=null&&(t.message=String(A.message)),A.keywords){if(!Array.isArray(A.keywords))throw TypeError(".proto.SyncActionValue.QuickReplyAction.keywords: array expected");t.keywords=[];for(var s=0;s>>3){case 1:{g.weights&&g.weights.length||(g.weights=[]),g.weights.push(E.proto.RecentEmojiWeight.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof E.proto.SyncActionValue.RecentEmojiWeightsAction)return a;var A=new E.proto.SyncActionValue.RecentEmojiWeightsAction;if(a.weights){if(!Array.isArray(a.weights))throw TypeError(".proto.SyncActionValue.RecentEmojiWeightsAction.weights: array expected");A.weights=[];for(var t=0;t>>3){case 1:{c.lastStickerSentTs=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.RemoveRecentStickerAction)return A;var t=new E.proto.SyncActionValue.RemoveRecentStickerAction;return A.lastStickerSentTs!=null&&(I.Long?(t.lastStickerSentTs=I.Long.fromValue(A.lastStickerSentTs)).unsigned=!1:typeof A.lastStickerSentTs=="string"?t.lastStickerSentTs=parseInt(A.lastStickerSentTs,10):typeof A.lastStickerSentTs=="number"?t.lastStickerSentTs=A.lastStickerSentTs:typeof A.lastStickerSentTs=="object"&&(t.lastStickerSentTs=new I.LongBits(A.lastStickerSentTs.low>>>0,A.lastStickerSentTs.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.lastStickerSentTs!=null&&A.hasOwnProperty("lastStickerSentTs")&&(typeof A.lastStickerSentTs=="number"?s.lastStickerSentTs=t.longs===String?String(A.lastStickerSentTs):A.lastStickerSentTs:s.lastStickerSentTs=t.longs===String?re(A.lastStickerSentTs):t.longs===Number?ae(A.lastStickerSentTs):A.lastStickerSentTs,t.oneofs&&(s._lastStickerSentTs="lastStickerSentTs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.RemoveRecentStickerAction"},i})(),r.StarAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.starred=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.StarAction)return A;var t=new E.proto.SyncActionValue.StarAction;return A.starred!=null&&(t.starred=!!A.starred),t},i.toObject=function(A,t){t||(t={});var s={};return A.starred!=null&&A.hasOwnProperty("starred")&&(s.starred=A.starred,t.oneofs&&(s._starred="starred")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StarAction"},i})(),r.StatusPostOptInNotificationPreferencesAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.enabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction)return A;var t=new E.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction;return A.enabled!=null&&(t.enabled=!!A.enabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.enabled!=null&&A.hasOwnProperty("enabled")&&(s.enabled=A.enabled,t.oneofs&&(s._enabled="enabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction"},i})(),r.StatusPrivacyAction=(function(){function i(a){if(this.userJid=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.mode=A.int32();break}case 2:{c.userJid&&c.userJid.length||(c.userJid=[]),c.userJid.push(A.string());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.StatusPrivacyAction)return A;var t=new E.proto.SyncActionValue.StatusPrivacyAction;switch(A.mode){default:if(typeof A.mode=="number"){t.mode=A.mode;break}break;case"ALLOW_LIST":case 0:t.mode=0;break;case"DENY_LIST":case 1:t.mode=1;break;case"CONTACTS":case 2:t.mode=2;break;case"CLOSE_FRIENDS":case 3:t.mode=3;break}if(A.userJid){if(!Array.isArray(A.userJid))throw TypeError(".proto.SyncActionValue.StatusPrivacyAction.userJid: array expected");t.userJid=[];for(var s=0;s>>3){case 1:{c.url=A.string();break}case 2:{c.fileEncSha256=A.bytes();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.mimetype=A.string();break}case 5:{c.height=A.uint32();break}case 6:{c.width=A.uint32();break}case 7:{c.directPath=A.string();break}case 8:{c.fileLength=A.uint64();break}case 9:{c.isFavorite=A.bool();break}case 10:{c.deviceIdHint=A.uint32();break}case 11:{c.isLottie=A.bool();break}case 12:{c.imageHash=A.string();break}case 13:{c.isAvatarSticker=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.StickerAction)return A;var t=new E.proto.SyncActionValue.StickerAction;return A.url!=null&&(t.url=String(A.url)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?I.base64.decode(A.fileEncSha256,t.fileEncSha256=I.newBuffer(I.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(t.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?I.base64.decode(A.mediaKey,t.mediaKey=I.newBuffer(I.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(t.mediaKey=A.mediaKey)),A.mimetype!=null&&(t.mimetype=String(A.mimetype)),A.height!=null&&(t.height=A.height>>>0),A.width!=null&&(t.width=A.width>>>0),A.directPath!=null&&(t.directPath=String(A.directPath)),A.fileLength!=null&&(I.Long?(t.fileLength=I.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?t.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?t.fileLength=A.fileLength:typeof A.fileLength=="object"&&(t.fileLength=new I.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.isFavorite!=null&&(t.isFavorite=!!A.isFavorite),A.deviceIdHint!=null&&(t.deviceIdHint=A.deviceIdHint>>>0),A.isLottie!=null&&(t.isLottie=!!A.isLottie),A.imageHash!=null&&(t.imageHash=String(A.imageHash)),A.isAvatarSticker!=null&&(t.isAvatarSticker=!!A.isAvatarSticker),t},i.toObject=function(A,t){t||(t={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,t.oneofs&&(s._url="url")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=t.bytes===String?I.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):t.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,t.oneofs&&(s._fileEncSha256="fileEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=t.bytes===String?I.base64.encode(A.mediaKey,0,A.mediaKey.length):t.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,t.oneofs&&(s._mediaKey="mediaKey")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,t.oneofs&&(s._mimetype="mimetype")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,t.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,t.oneofs&&(s._width="width")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,t.oneofs&&(s._directPath="directPath")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=t.longs===String?String(A.fileLength):A.fileLength:s.fileLength=t.longs===String?re(A.fileLength,!0):t.longs===Number?ae(A.fileLength,!0):A.fileLength,t.oneofs&&(s._fileLength="fileLength")),A.isFavorite!=null&&A.hasOwnProperty("isFavorite")&&(s.isFavorite=A.isFavorite,t.oneofs&&(s._isFavorite="isFavorite")),A.deviceIdHint!=null&&A.hasOwnProperty("deviceIdHint")&&(s.deviceIdHint=A.deviceIdHint,t.oneofs&&(s._deviceIdHint="deviceIdHint")),A.isLottie!=null&&A.hasOwnProperty("isLottie")&&(s.isLottie=A.isLottie,t.oneofs&&(s._isLottie="isLottie")),A.imageHash!=null&&A.hasOwnProperty("imageHash")&&(s.imageHash=A.imageHash,t.oneofs&&(s._imageHash="imageHash")),A.isAvatarSticker!=null&&A.hasOwnProperty("isAvatarSticker")&&(s.isAvatarSticker=A.isAvatarSticker,t.oneofs&&(s._isAvatarSticker="isAvatarSticker")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StickerAction"},i})(),r.SubscriptionAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.isDeactivated=A.bool();break}case 2:{c.isAutoRenewing=A.bool();break}case 3:{c.expirationDate=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.SubscriptionAction)return A;var t=new E.proto.SyncActionValue.SubscriptionAction;return A.isDeactivated!=null&&(t.isDeactivated=!!A.isDeactivated),A.isAutoRenewing!=null&&(t.isAutoRenewing=!!A.isAutoRenewing),A.expirationDate!=null&&(I.Long?(t.expirationDate=I.Long.fromValue(A.expirationDate)).unsigned=!1:typeof A.expirationDate=="string"?t.expirationDate=parseInt(A.expirationDate,10):typeof A.expirationDate=="number"?t.expirationDate=A.expirationDate:typeof A.expirationDate=="object"&&(t.expirationDate=new I.LongBits(A.expirationDate.low>>>0,A.expirationDate.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.isDeactivated!=null&&A.hasOwnProperty("isDeactivated")&&(s.isDeactivated=A.isDeactivated,t.oneofs&&(s._isDeactivated="isDeactivated")),A.isAutoRenewing!=null&&A.hasOwnProperty("isAutoRenewing")&&(s.isAutoRenewing=A.isAutoRenewing,t.oneofs&&(s._isAutoRenewing="isAutoRenewing")),A.expirationDate!=null&&A.hasOwnProperty("expirationDate")&&(typeof A.expirationDate=="number"?s.expirationDate=t.longs===String?String(A.expirationDate):A.expirationDate:s.expirationDate=t.longs===String?re(A.expirationDate):t.longs===Number?ae(A.expirationDate):A.expirationDate,t.oneofs&&(s._expirationDate="expirationDate")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.SubscriptionAction"},i})(),r.SyncActionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.key=E.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.timestamp=A.int64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.SyncActionMessage)return A;var t=new E.proto.SyncActionValue.SyncActionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.SyncActionValue.SyncActionMessage.key: object expected");t.key=E.proto.MessageKey.fromObject(A.key)}return A.timestamp!=null&&(I.Long?(t.timestamp=I.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?t.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?t.timestamp=A.timestamp:typeof A.timestamp=="object"&&(t.timestamp=new I.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=E.proto.MessageKey.toObject(A.key,t),t.oneofs&&(s._key="key")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=t.longs===String?String(A.timestamp):A.timestamp:s.timestamp=t.longs===String?re(A.timestamp):t.longs===Number?ae(A.timestamp):A.timestamp,t.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.SyncActionMessage"},i})(),r.SyncActionMessageRange=(function(){function i(a){if(this.messages=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.lastMessageTimestamp=A.int64();break}case 2:{c.lastSystemMessageTimestamp=A.int64();break}case 3:{c.messages&&c.messages.length||(c.messages=[]),c.messages.push(E.proto.SyncActionValue.SyncActionMessage.decode(A,A.uint32()));break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.SyncActionMessageRange)return A;var t=new E.proto.SyncActionValue.SyncActionMessageRange;if(A.lastMessageTimestamp!=null&&(I.Long?(t.lastMessageTimestamp=I.Long.fromValue(A.lastMessageTimestamp)).unsigned=!1:typeof A.lastMessageTimestamp=="string"?t.lastMessageTimestamp=parseInt(A.lastMessageTimestamp,10):typeof A.lastMessageTimestamp=="number"?t.lastMessageTimestamp=A.lastMessageTimestamp:typeof A.lastMessageTimestamp=="object"&&(t.lastMessageTimestamp=new I.LongBits(A.lastMessageTimestamp.low>>>0,A.lastMessageTimestamp.high>>>0).toNumber())),A.lastSystemMessageTimestamp!=null&&(I.Long?(t.lastSystemMessageTimestamp=I.Long.fromValue(A.lastSystemMessageTimestamp)).unsigned=!1:typeof A.lastSystemMessageTimestamp=="string"?t.lastSystemMessageTimestamp=parseInt(A.lastSystemMessageTimestamp,10):typeof A.lastSystemMessageTimestamp=="number"?t.lastSystemMessageTimestamp=A.lastSystemMessageTimestamp:typeof A.lastSystemMessageTimestamp=="object"&&(t.lastSystemMessageTimestamp=new I.LongBits(A.lastSystemMessageTimestamp.low>>>0,A.lastSystemMessageTimestamp.high>>>0).toNumber())),A.messages){if(!Array.isArray(A.messages))throw TypeError(".proto.SyncActionValue.SyncActionMessageRange.messages: array expected");t.messages=[];for(var s=0;s>>3){case 1:{c.isTwentyFourHourFormatEnabled=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.TimeFormatAction)return A;var t=new E.proto.SyncActionValue.TimeFormatAction;return A.isTwentyFourHourFormatEnabled!=null&&(t.isTwentyFourHourFormatEnabled=!!A.isTwentyFourHourFormatEnabled),t},i.toObject=function(A,t){t||(t={});var s={};return A.isTwentyFourHourFormatEnabled!=null&&A.hasOwnProperty("isTwentyFourHourFormatEnabled")&&(s.isTwentyFourHourFormatEnabled=A.isTwentyFourHourFormatEnabled,t.oneofs&&(s._isTwentyFourHourFormatEnabled="isTwentyFourHourFormatEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.TimeFormatAction"},i})(),r.UGCBot=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.definition=A.bytes();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.UGCBot)return A;var t=new E.proto.SyncActionValue.UGCBot;return A.definition!=null&&(typeof A.definition=="string"?I.base64.decode(A.definition,t.definition=I.newBuffer(I.base64.length(A.definition)),0):A.definition.length>=0&&(t.definition=A.definition)),t},i.toObject=function(A,t){t||(t={});var s={};return A.definition!=null&&A.hasOwnProperty("definition")&&(s.definition=t.bytes===String?I.base64.encode(A.definition,0,A.definition.length):t.bytes===Array?Array.prototype.slice.call(A.definition):A.definition,t.oneofs&&(s._definition="definition")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UGCBot"},i})(),r.UnarchiveChatsSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.unarchiveChats=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.UnarchiveChatsSetting)return A;var t=new E.proto.SyncActionValue.UnarchiveChatsSetting;return A.unarchiveChats!=null&&(t.unarchiveChats=!!A.unarchiveChats),t},i.toObject=function(A,t){t||(t={});var s={};return A.unarchiveChats!=null&&A.hasOwnProperty("unarchiveChats")&&(s.unarchiveChats=A.unarchiveChats,t.oneofs&&(s._unarchiveChats="unarchiveChats")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UnarchiveChatsSetting"},i})(),r.UserStatusMuteAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.muted=A.bool();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.UserStatusMuteAction)return A;var t=new E.proto.SyncActionValue.UserStatusMuteAction;return A.muted!=null&&(t.muted=!!A.muted),t},i.toObject=function(A,t){t||(t={});var s={};return A.muted!=null&&A.hasOwnProperty("muted")&&(s.muted=A.muted,t.oneofs&&(s._muted="muted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UserStatusMuteAction"},i})(),r.UsernameChatStartModeAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.chatStartMode=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.UsernameChatStartModeAction)return A;var t=new E.proto.SyncActionValue.UsernameChatStartModeAction;switch(A.chatStartMode){default:if(typeof A.chatStartMode=="number"){t.chatStartMode=A.chatStartMode;break}break;case"LID":case 1:t.chatStartMode=1;break;case"PN":case 2:t.chatStartMode=2;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.chatStartMode!=null&&A.hasOwnProperty("chatStartMode")&&(s.chatStartMode=t.enums===String?E.proto.SyncActionValue.UsernameChatStartModeAction.ChatStartMode[A.chatStartMode]===void 0?A.chatStartMode:E.proto.SyncActionValue.UsernameChatStartModeAction.ChatStartMode[A.chatStartMode]:A.chatStartMode,t.oneofs&&(s._chatStartMode="chatStartMode")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UsernameChatStartModeAction"},i.ChatStartMode=(function(){let a={},A=Object.create(a);return A[a[1]="LID"]=1,A[a[2]="PN"]=2,A})(),i})(),r.WaffleAccountLinkStateAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 2:{c.linkState=A.int32();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.WaffleAccountLinkStateAction)return A;var t=new E.proto.SyncActionValue.WaffleAccountLinkStateAction;switch(A.linkState){default:if(typeof A.linkState=="number"){t.linkState=A.linkState;break}break;case"ACTIVE":case 0:t.linkState=0;break;case"PAUSED":case 1:t.linkState=1;break;case"UNLINKED":case 2:t.linkState=2;break}return t},i.toObject=function(A,t){t||(t={});var s={};return A.linkState!=null&&A.hasOwnProperty("linkState")&&(s.linkState=t.enums===String?E.proto.SyncActionValue.WaffleAccountLinkStateAction.AccountLinkState[A.linkState]===void 0?A.linkState:E.proto.SyncActionValue.WaffleAccountLinkStateAction.AccountLinkState[A.linkState]:A.linkState,t.oneofs&&(s._linkState="linkState")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.WaffleAccountLinkStateAction"},i.AccountLinkState=(function(){let a={},A=Object.create(a);return A[a[0]="ACTIVE"]=0,A[a[1]="PAUSED"]=1,A[a[2]="UNLINKED"]=2,A})(),i})(),r.WamoUserIdentifierAction=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.identifier=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.SyncActionValue.WamoUserIdentifierAction)return A;var t=new E.proto.SyncActionValue.WamoUserIdentifierAction;return A.identifier!=null&&(t.identifier=String(A.identifier)),t},i.toObject=function(A,t){t||(t={});var s={};return A.identifier!=null&&A.hasOwnProperty("identifier")&&(s.identifier=A.identifier,t.oneofs&&(s._identifier="identifier")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.WamoUserIdentifierAction"},i})(),r})(),n.SyncdIndex=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.blob=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncdIndex)return e;var a=new E.proto.SyncdIndex;return e.blob!=null&&(typeof e.blob=="string"?I.base64.decode(e.blob,a.blob=I.newBuffer(I.base64.length(e.blob)),0):e.blob.length>=0&&(a.blob=e.blob)),a},r.toObject=function(e,a){a||(a={});var A={};return e.blob!=null&&e.hasOwnProperty("blob")&&(A.blob=a.bytes===String?I.base64.encode(e.blob,0,e.blob.length):a.bytes===Array?Array.prototype.slice.call(e.blob):e.blob,a.oneofs&&(A._blob="blob")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdIndex"},r})(),n.SyncdMutation=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.operation=e.int32();break}case 2:{s.record=E.proto.SyncdRecord.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncdMutation)return e;var a=new E.proto.SyncdMutation;switch(e.operation){default:if(typeof e.operation=="number"){a.operation=e.operation;break}break;case"SET":case 0:a.operation=0;break;case"REMOVE":case 1:a.operation=1;break}if(e.record!=null){if(typeof e.record!="object")throw TypeError(".proto.SyncdMutation.record: object expected");a.record=E.proto.SyncdRecord.fromObject(e.record)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.operation!=null&&e.hasOwnProperty("operation")&&(A.operation=a.enums===String?E.proto.SyncdMutation.SyncdOperation[e.operation]===void 0?e.operation:E.proto.SyncdMutation.SyncdOperation[e.operation]:e.operation,a.oneofs&&(A._operation="operation")),e.record!=null&&e.hasOwnProperty("record")&&(A.record=E.proto.SyncdRecord.toObject(e.record,a),a.oneofs&&(A._record="record")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdMutation"},r.SyncdOperation=(function(){let i={},e=Object.create(i);return e[i[0]="SET"]=0,e[i[1]="REMOVE"]=1,e})(),r})(),n.SyncdMutations=(function(){function r(o){if(this.mutations=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.mutations&&t.mutations.length||(t.mutations=[]),t.mutations.push(E.proto.SyncdMutation.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.SyncdMutations)return i;var e=new E.proto.SyncdMutations;if(i.mutations){if(!Array.isArray(i.mutations))throw TypeError(".proto.SyncdMutations.mutations: array expected");e.mutations=[];for(var a=0;a>>3){case 1:{s.version=E.proto.SyncdVersion.decode(e,e.uint32());break}case 2:{s.mutations&&s.mutations.length||(s.mutations=[]),s.mutations.push(E.proto.SyncdMutation.decode(e,e.uint32()));break}case 3:{s.externalMutations=E.proto.ExternalBlobReference.decode(e,e.uint32());break}case 4:{s.snapshotMac=e.bytes();break}case 5:{s.patchMac=e.bytes();break}case 6:{s.keyId=E.proto.KeyId.decode(e,e.uint32());break}case 7:{s.exitCode=E.proto.ExitCode.decode(e,e.uint32());break}case 8:{s.deviceIndex=e.uint32();break}case 9:{s.clientDebugData=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncdPatch)return e;var a=new E.proto.SyncdPatch;if(e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.SyncdPatch.version: object expected");a.version=E.proto.SyncdVersion.fromObject(e.version)}if(e.mutations){if(!Array.isArray(e.mutations))throw TypeError(".proto.SyncdPatch.mutations: array expected");a.mutations=[];for(var A=0;A=0&&(a.snapshotMac=e.snapshotMac)),e.patchMac!=null&&(typeof e.patchMac=="string"?I.base64.decode(e.patchMac,a.patchMac=I.newBuffer(I.base64.length(e.patchMac)),0):e.patchMac.length>=0&&(a.patchMac=e.patchMac)),e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdPatch.keyId: object expected");a.keyId=E.proto.KeyId.fromObject(e.keyId)}if(e.exitCode!=null){if(typeof e.exitCode!="object")throw TypeError(".proto.SyncdPatch.exitCode: object expected");a.exitCode=E.proto.ExitCode.fromObject(e.exitCode)}return e.deviceIndex!=null&&(a.deviceIndex=e.deviceIndex>>>0),e.clientDebugData!=null&&(typeof e.clientDebugData=="string"?I.base64.decode(e.clientDebugData,a.clientDebugData=I.newBuffer(I.base64.length(e.clientDebugData)),0):e.clientDebugData.length>=0&&(a.clientDebugData=e.clientDebugData)),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.mutations=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=E.proto.SyncdVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.mutations&&e.mutations.length){A.mutations=[];for(var t=0;t>>3){case 1:{s.index=E.proto.SyncdIndex.decode(e,e.uint32());break}case 2:{s.value=E.proto.SyncdValue.decode(e,e.uint32());break}case 3:{s.keyId=E.proto.KeyId.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncdRecord)return e;var a=new E.proto.SyncdRecord;if(e.index!=null){if(typeof e.index!="object")throw TypeError(".proto.SyncdRecord.index: object expected");a.index=E.proto.SyncdIndex.fromObject(e.index)}if(e.value!=null){if(typeof e.value!="object")throw TypeError(".proto.SyncdRecord.value: object expected");a.value=E.proto.SyncdValue.fromObject(e.value)}if(e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdRecord.keyId: object expected");a.keyId=E.proto.KeyId.fromObject(e.keyId)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.index!=null&&e.hasOwnProperty("index")&&(A.index=E.proto.SyncdIndex.toObject(e.index,a),a.oneofs&&(A._index="index")),e.value!=null&&e.hasOwnProperty("value")&&(A.value=E.proto.SyncdValue.toObject(e.value,a),a.oneofs&&(A._value="value")),e.keyId!=null&&e.hasOwnProperty("keyId")&&(A.keyId=E.proto.KeyId.toObject(e.keyId,a),a.oneofs&&(A._keyId="keyId")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdRecord"},r})(),n.SyncdSnapshot=(function(){function r(i){if(this.records=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=E.proto.SyncdVersion.decode(e,e.uint32());break}case 2:{s.records&&s.records.length||(s.records=[]),s.records.push(E.proto.SyncdRecord.decode(e,e.uint32()));break}case 3:{s.mac=e.bytes();break}case 4:{s.keyId=E.proto.KeyId.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncdSnapshot)return e;var a=new E.proto.SyncdSnapshot;if(e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.SyncdSnapshot.version: object expected");a.version=E.proto.SyncdVersion.fromObject(e.version)}if(e.records){if(!Array.isArray(e.records))throw TypeError(".proto.SyncdSnapshot.records: array expected");a.records=[];for(var A=0;A=0&&(a.mac=e.mac)),e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdSnapshot.keyId: object expected");a.keyId=E.proto.KeyId.fromObject(e.keyId)}return a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.records=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=E.proto.SyncdVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.records&&e.records.length){A.records=[];for(var t=0;t>>3){case 1:{s.blob=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncdValue)return e;var a=new E.proto.SyncdValue;return e.blob!=null&&(typeof e.blob=="string"?I.base64.decode(e.blob,a.blob=I.newBuffer(I.base64.length(e.blob)),0):e.blob.length>=0&&(a.blob=e.blob)),a},r.toObject=function(e,a){a||(a={});var A={};return e.blob!=null&&e.hasOwnProperty("blob")&&(A.blob=a.bytes===String?I.base64.encode(e.blob,0,e.blob.length):a.bytes===Array?Array.prototype.slice.call(e.blob):e.blob,a.oneofs&&(A._blob="blob")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdValue"},r})(),n.SyncdVersion=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=e.uint64();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.SyncdVersion)return e;var a=new E.proto.SyncdVersion;return e.version!=null&&(I.Long?(a.version=I.Long.fromValue(e.version)).unsigned=!0:typeof e.version=="string"?a.version=parseInt(e.version,10):typeof e.version=="number"?a.version=e.version:typeof e.version=="object"&&(a.version=new I.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber(!0))),a},r.toObject=function(e,a){a||(a={});var A={};return e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?A.version=a.longs===String?String(e.version):e.version:A.version=a.longs===String?re(e.version,!0):a.longs===Number?ae(e.version,!0):e.version,a.oneofs&&(A._version="version")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdVersion"},r})(),n.TapLinkAction=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.title=e.string();break}case 2:{s.tapUrl=e.string();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.TapLinkAction)return e;var a=new E.proto.TapLinkAction;return e.title!=null&&(a.title=String(e.title)),e.tapUrl!=null&&(a.tapUrl=String(e.tapUrl)),a},r.toObject=function(e,a){a||(a={});var A={};return e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.tapUrl!=null&&e.hasOwnProperty("tapUrl")&&(A.tapUrl=e.tapUrl,a.oneofs&&(A._tapUrl="tapUrl")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.TapLinkAction"},r})(),n.TemplateButton=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 4:{s.index=e.uint32();break}case 1:{s.quickReplyButton=E.proto.TemplateButton.QuickReplyButton.decode(e,e.uint32());break}case 2:{s.urlButton=E.proto.TemplateButton.URLButton.decode(e,e.uint32());break}case 3:{s.callButton=E.proto.TemplateButton.CallButton.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.TemplateButton)return e;var a=new E.proto.TemplateButton;if(e.index!=null&&(a.index=e.index>>>0),e.quickReplyButton!=null){if(typeof e.quickReplyButton!="object")throw TypeError(".proto.TemplateButton.quickReplyButton: object expected");a.quickReplyButton=E.proto.TemplateButton.QuickReplyButton.fromObject(e.quickReplyButton)}if(e.urlButton!=null){if(typeof e.urlButton!="object")throw TypeError(".proto.TemplateButton.urlButton: object expected");a.urlButton=E.proto.TemplateButton.URLButton.fromObject(e.urlButton)}if(e.callButton!=null){if(typeof e.callButton!="object")throw TypeError(".proto.TemplateButton.callButton: object expected");a.callButton=E.proto.TemplateButton.CallButton.fromObject(e.callButton)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.quickReplyButton!=null&&e.hasOwnProperty("quickReplyButton")&&(A.quickReplyButton=E.proto.TemplateButton.QuickReplyButton.toObject(e.quickReplyButton,a),a.oneofs&&(A.button="quickReplyButton")),e.urlButton!=null&&e.hasOwnProperty("urlButton")&&(A.urlButton=E.proto.TemplateButton.URLButton.toObject(e.urlButton,a),a.oneofs&&(A.button="urlButton")),e.callButton!=null&&e.hasOwnProperty("callButton")&&(A.callButton=E.proto.TemplateButton.CallButton.toObject(e.callButton,a),a.oneofs&&(A.button="callButton")),e.index!=null&&e.hasOwnProperty("index")&&(A.index=e.index,a.oneofs&&(A._index="index")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.TemplateButton"},r.CallButton=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayText=E.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.phoneNumber=E.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.TemplateButton.CallButton)return A;var t=new E.proto.TemplateButton.CallButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.CallButton.displayText: object expected");t.displayText=E.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}if(A.phoneNumber!=null){if(typeof A.phoneNumber!="object")throw TypeError(".proto.TemplateButton.CallButton.phoneNumber: object expected");t.phoneNumber=E.proto.Message.HighlyStructuredMessage.fromObject(A.phoneNumber)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=E.proto.Message.HighlyStructuredMessage.toObject(A.displayText,t),t.oneofs&&(s._displayText="displayText")),A.phoneNumber!=null&&A.hasOwnProperty("phoneNumber")&&(s.phoneNumber=E.proto.Message.HighlyStructuredMessage.toObject(A.phoneNumber,t),t.oneofs&&(s._phoneNumber="phoneNumber")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.CallButton"},i})(),r.QuickReplyButton=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayText=E.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.id=A.string();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.TemplateButton.QuickReplyButton)return A;var t=new E.proto.TemplateButton.QuickReplyButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.QuickReplyButton.displayText: object expected");t.displayText=E.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}return A.id!=null&&(t.id=String(A.id)),t},i.toObject=function(A,t){t||(t={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=E.proto.Message.HighlyStructuredMessage.toObject(A.displayText,t),t.oneofs&&(s._displayText="displayText")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,t.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.QuickReplyButton"},i})(),r.URLButton=(function(){function i(a){if(a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.displayText=E.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.url=E.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.TemplateButton.URLButton)return A;var t=new E.proto.TemplateButton.URLButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.URLButton.displayText: object expected");t.displayText=E.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}if(A.url!=null){if(typeof A.url!="object")throw TypeError(".proto.TemplateButton.URLButton.url: object expected");t.url=E.proto.Message.HighlyStructuredMessage.fromObject(A.url)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=E.proto.Message.HighlyStructuredMessage.toObject(A.displayText,t),t.oneofs&&(s._displayText="displayText")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=E.proto.Message.HighlyStructuredMessage.toObject(A.url,t),t.oneofs&&(s._url="url")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.URLButton"},i})(),r})(),n.ThreadID=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.threadType=e.int32();break}case 2:{s.threadKey=E.proto.MessageKey.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.ThreadID)return e;var a=new E.proto.ThreadID;switch(e.threadType){default:if(typeof e.threadType=="number"){a.threadType=e.threadType;break}break;case"UNKNOWN":case 0:a.threadType=0;break;case"VIEW_REPLIES":case 1:a.threadType=1;break;case"AI_THREAD":case 2:a.threadType=2;break}if(e.threadKey!=null){if(typeof e.threadKey!="object")throw TypeError(".proto.ThreadID.threadKey: object expected");a.threadKey=E.proto.MessageKey.fromObject(e.threadKey)}return a},r.toObject=function(e,a){a||(a={});var A={};return e.threadType!=null&&e.hasOwnProperty("threadType")&&(A.threadType=a.enums===String?E.proto.ThreadID.ThreadType[e.threadType]===void 0?e.threadType:E.proto.ThreadID.ThreadType[e.threadType]:e.threadType,a.oneofs&&(A._threadType="threadType")),e.threadKey!=null&&e.hasOwnProperty("threadKey")&&(A.threadKey=E.proto.MessageKey.toObject(e.threadKey,a),a.oneofs&&(A._threadKey="threadKey")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ThreadID"},r.ThreadType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="VIEW_REPLIES"]=1,e[i[2]="AI_THREAD"]=2,e})(),r})(),n.UrlTrackingMap=(function(){function r(o){if(this.urlTrackingMapElements=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{t.urlTrackingMapElements&&t.urlTrackingMapElements.length||(t.urlTrackingMapElements=[]),t.urlTrackingMapElements.push(E.proto.UrlTrackingMap.UrlTrackingMapElement.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return t},r.fromObject=function(i){if(i instanceof E.proto.UrlTrackingMap)return i;var e=new E.proto.UrlTrackingMap;if(i.urlTrackingMapElements){if(!Array.isArray(i.urlTrackingMapElements))throw TypeError(".proto.UrlTrackingMap.urlTrackingMapElements: array expected");e.urlTrackingMapElements=[];for(var a=0;a>>3){case 1:{g.originalUrl=a.string();break}case 2:{g.unconsentedUsersUrl=a.string();break}case 3:{g.consentedUsersUrl=a.string();break}case 4:{g.cardIndex=a.uint32();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof E.proto.UrlTrackingMap.UrlTrackingMapElement)return a;var A=new E.proto.UrlTrackingMap.UrlTrackingMapElement;return a.originalUrl!=null&&(A.originalUrl=String(a.originalUrl)),a.unconsentedUsersUrl!=null&&(A.unconsentedUsersUrl=String(a.unconsentedUsersUrl)),a.consentedUsersUrl!=null&&(A.consentedUsersUrl=String(a.consentedUsersUrl)),a.cardIndex!=null&&(A.cardIndex=a.cardIndex>>>0),A},o.toObject=function(a,A){A||(A={});var t={};return a.originalUrl!=null&&a.hasOwnProperty("originalUrl")&&(t.originalUrl=a.originalUrl,A.oneofs&&(t._originalUrl="originalUrl")),a.unconsentedUsersUrl!=null&&a.hasOwnProperty("unconsentedUsersUrl")&&(t.unconsentedUsersUrl=a.unconsentedUsersUrl,A.oneofs&&(t._unconsentedUsersUrl="unconsentedUsersUrl")),a.consentedUsersUrl!=null&&a.hasOwnProperty("consentedUsersUrl")&&(t.consentedUsersUrl=a.consentedUsersUrl,A.oneofs&&(t._consentedUsersUrl="consentedUsersUrl")),a.cardIndex!=null&&a.hasOwnProperty("cardIndex")&&(t.cardIndex=a.cardIndex,A.oneofs&&(t._cardIndex="cardIndex")),t},o.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.UrlTrackingMap.UrlTrackingMapElement"},o})(),r})(),n.UserPassword=(function(){function r(i){if(this.transformerArg=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encoding=e.int32();break}case 2:{s.transformer=e.int32();break}case 3:{s.transformerArg&&s.transformerArg.length||(s.transformerArg=[]),s.transformerArg.push(E.proto.UserPassword.TransformerArg.decode(e,e.uint32()));break}case 4:{s.transformedData=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.UserPassword)return e;var a=new E.proto.UserPassword;switch(e.encoding){default:if(typeof e.encoding=="number"){a.encoding=e.encoding;break}break;case"UTF8":case 0:a.encoding=0;break;case"UTF8_BROKEN":case 1:a.encoding=1;break}switch(e.transformer){default:if(typeof e.transformer=="number"){a.transformer=e.transformer;break}break;case"NONE":case 0:a.transformer=0;break;case"PBKDF2_HMAC_SHA512":case 1:a.transformer=1;break;case"PBKDF2_HMAC_SHA384":case 2:a.transformer=2;break}if(e.transformerArg){if(!Array.isArray(e.transformerArg))throw TypeError(".proto.UserPassword.transformerArg: array expected");a.transformerArg=[];for(var A=0;A=0&&(a.transformedData=e.transformedData)),a},r.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.transformerArg=[]),e.encoding!=null&&e.hasOwnProperty("encoding")&&(A.encoding=a.enums===String?E.proto.UserPassword.Encoding[e.encoding]===void 0?e.encoding:E.proto.UserPassword.Encoding[e.encoding]:e.encoding,a.oneofs&&(A._encoding="encoding")),e.transformer!=null&&e.hasOwnProperty("transformer")&&(A.transformer=a.enums===String?E.proto.UserPassword.Transformer[e.transformer]===void 0?e.transformer:E.proto.UserPassword.Transformer[e.transformer]:e.transformer,a.oneofs&&(A._transformer="transformer")),e.transformerArg&&e.transformerArg.length){A.transformerArg=[];for(var t=0;t>>3){case 1:{c.key=A.string();break}case 2:{c.value=E.proto.UserPassword.TransformerArg.Value.decode(A,A.uint32());break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.UserPassword.TransformerArg)return A;var t=new E.proto.UserPassword.TransformerArg;if(A.key!=null&&(t.key=String(A.key)),A.value!=null){if(typeof A.value!="object")throw TypeError(".proto.UserPassword.TransformerArg.value: object expected");t.value=E.proto.UserPassword.TransformerArg.Value.fromObject(A.value)}return t},i.toObject=function(A,t){t||(t={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=A.key,t.oneofs&&(s._key="key")),A.value!=null&&A.hasOwnProperty("value")&&(s.value=E.proto.UserPassword.TransformerArg.Value.toObject(A.value,t),t.oneofs&&(s._value="value")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.UserPassword.TransformerArg"},i.Value=(function(){function a(t){if(t)for(var s=Object.keys(t),g=0;g>>3){case 1:{p.asBlob=s.bytes();break}case 2:{p.asUnsignedInteger=s.uint32();break}default:s.skipType(B&7);break}}return p},a.fromObject=function(s){if(s instanceof E.proto.UserPassword.TransformerArg.Value)return s;var g=new E.proto.UserPassword.TransformerArg.Value;return s.asBlob!=null&&(typeof s.asBlob=="string"?I.base64.decode(s.asBlob,g.asBlob=I.newBuffer(I.base64.length(s.asBlob)),0):s.asBlob.length>=0&&(g.asBlob=s.asBlob)),s.asUnsignedInteger!=null&&(g.asUnsignedInteger=s.asUnsignedInteger>>>0),g},a.toObject=function(s,g){g||(g={});var c={};return s.asBlob!=null&&s.hasOwnProperty("asBlob")&&(c.asBlob=g.bytes===String?I.base64.encode(s.asBlob,0,s.asBlob.length):g.bytes===Array?Array.prototype.slice.call(s.asBlob):s.asBlob,g.oneofs&&(c.value="asBlob")),s.asUnsignedInteger!=null&&s.hasOwnProperty("asUnsignedInteger")&&(c.asUnsignedInteger=s.asUnsignedInteger,g.oneofs&&(c.value="asUnsignedInteger")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.UserPassword.TransformerArg.Value"},a})(),i})(),r})(),n.UserReceipt=(function(){function r(i){if(this.pendingDeviceJid=[],this.deliveredDeviceJid=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.receiptTimestamp=e.int64();break}case 3:{s.readTimestamp=e.int64();break}case 4:{s.playedTimestamp=e.int64();break}case 5:{s.pendingDeviceJid&&s.pendingDeviceJid.length||(s.pendingDeviceJid=[]),s.pendingDeviceJid.push(e.string());break}case 6:{s.deliveredDeviceJid&&s.deliveredDeviceJid.length||(s.deliveredDeviceJid=[]),s.deliveredDeviceJid.push(e.string());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.UserReceipt)return e;var a=new E.proto.UserReceipt;if(e.userJid!=null&&(a.userJid=String(e.userJid)),e.receiptTimestamp!=null&&(I.Long?(a.receiptTimestamp=I.Long.fromValue(e.receiptTimestamp)).unsigned=!1:typeof e.receiptTimestamp=="string"?a.receiptTimestamp=parseInt(e.receiptTimestamp,10):typeof e.receiptTimestamp=="number"?a.receiptTimestamp=e.receiptTimestamp:typeof e.receiptTimestamp=="object"&&(a.receiptTimestamp=new I.LongBits(e.receiptTimestamp.low>>>0,e.receiptTimestamp.high>>>0).toNumber())),e.readTimestamp!=null&&(I.Long?(a.readTimestamp=I.Long.fromValue(e.readTimestamp)).unsigned=!1:typeof e.readTimestamp=="string"?a.readTimestamp=parseInt(e.readTimestamp,10):typeof e.readTimestamp=="number"?a.readTimestamp=e.readTimestamp:typeof e.readTimestamp=="object"&&(a.readTimestamp=new I.LongBits(e.readTimestamp.low>>>0,e.readTimestamp.high>>>0).toNumber())),e.playedTimestamp!=null&&(I.Long?(a.playedTimestamp=I.Long.fromValue(e.playedTimestamp)).unsigned=!1:typeof e.playedTimestamp=="string"?a.playedTimestamp=parseInt(e.playedTimestamp,10):typeof e.playedTimestamp=="number"?a.playedTimestamp=e.playedTimestamp:typeof e.playedTimestamp=="object"&&(a.playedTimestamp=new I.LongBits(e.playedTimestamp.low>>>0,e.playedTimestamp.high>>>0).toNumber())),e.pendingDeviceJid){if(!Array.isArray(e.pendingDeviceJid))throw TypeError(".proto.UserReceipt.pendingDeviceJid: array expected");a.pendingDeviceJid=[];for(var A=0;A>>3){case 1:{s.details=e.bytes();break}case 2:{s.signature=e.bytes();break}case 3:{s.serverSignature=e.bytes();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.VerifiedNameCertificate)return e;var a=new E.proto.VerifiedNameCertificate;return e.details!=null&&(typeof e.details=="string"?I.base64.decode(e.details,a.details=I.newBuffer(I.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.signature!=null&&(typeof e.signature=="string"?I.base64.decode(e.signature,a.signature=I.newBuffer(I.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.serverSignature!=null&&(typeof e.serverSignature=="string"?I.base64.decode(e.serverSignature,a.serverSignature=I.newBuffer(I.base64.length(e.serverSignature)),0):e.serverSignature.length>=0&&(a.serverSignature=e.serverSignature)),a},r.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?I.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?I.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.serverSignature!=null&&e.hasOwnProperty("serverSignature")&&(A.serverSignature=a.bytes===String?I.base64.encode(e.serverSignature,0,e.serverSignature.length):a.bytes===Array?Array.prototype.slice.call(e.serverSignature):e.serverSignature,a.oneofs&&(A._serverSignature="serverSignature")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.VerifiedNameCertificate"},r.Details=(function(){function i(a){if(this.localizedNames=[],a)for(var A=Object.keys(a),t=0;t>>3){case 1:{c.serial=A.uint64();break}case 2:{c.issuer=A.string();break}case 4:{c.verifiedName=A.string();break}case 8:{c.localizedNames&&c.localizedNames.length||(c.localizedNames=[]),c.localizedNames.push(E.proto.LocalizedName.decode(A,A.uint32()));break}case 10:{c.issueTime=A.uint64();break}default:A.skipType(l&7);break}}return c},i.fromObject=function(A){if(A instanceof E.proto.VerifiedNameCertificate.Details)return A;var t=new E.proto.VerifiedNameCertificate.Details;if(A.serial!=null&&(I.Long?(t.serial=I.Long.fromValue(A.serial)).unsigned=!0:typeof A.serial=="string"?t.serial=parseInt(A.serial,10):typeof A.serial=="number"?t.serial=A.serial:typeof A.serial=="object"&&(t.serial=new I.LongBits(A.serial.low>>>0,A.serial.high>>>0).toNumber(!0))),A.issuer!=null&&(t.issuer=String(A.issuer)),A.verifiedName!=null&&(t.verifiedName=String(A.verifiedName)),A.localizedNames){if(!Array.isArray(A.localizedNames))throw TypeError(".proto.VerifiedNameCertificate.Details.localizedNames: array expected");t.localizedNames=[];for(var s=0;s>>0,A.issueTime.high>>>0).toNumber(!0))),t},i.toObject=function(A,t){t||(t={});var s={};if((t.arrays||t.defaults)&&(s.localizedNames=[]),A.serial!=null&&A.hasOwnProperty("serial")&&(typeof A.serial=="number"?s.serial=t.longs===String?String(A.serial):A.serial:s.serial=t.longs===String?re(A.serial,!0):t.longs===Number?ae(A.serial,!0):A.serial,t.oneofs&&(s._serial="serial")),A.issuer!=null&&A.hasOwnProperty("issuer")&&(s.issuer=A.issuer,t.oneofs&&(s._issuer="issuer")),A.verifiedName!=null&&A.hasOwnProperty("verifiedName")&&(s.verifiedName=A.verifiedName,t.oneofs&&(s._verifiedName="verifiedName")),A.localizedNames&&A.localizedNames.length){s.localizedNames=[];for(var g=0;g>>3){case 1:{s.filename=e.string();break}case 2:{s.opacity=e.uint32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.WallpaperSettings)return e;var a=new E.proto.WallpaperSettings;return e.filename!=null&&(a.filename=String(e.filename)),e.opacity!=null&&(a.opacity=e.opacity>>>0),a},r.toObject=function(e,a){a||(a={});var A={};return e.filename!=null&&e.hasOwnProperty("filename")&&(A.filename=e.filename,a.oneofs&&(A._filename="filename")),e.opacity!=null&&e.hasOwnProperty("opacity")&&(A.opacity=e.opacity,a.oneofs&&(A._opacity="opacity")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.WallpaperSettings"},r})(),n.WebFeatures=(function(){function r(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.labelsDisplay=e.int32();break}case 2:{s.voipIndividualOutgoing=e.int32();break}case 3:{s.groupsV3=e.int32();break}case 4:{s.groupsV3Create=e.int32();break}case 5:{s.changeNumberV2=e.int32();break}case 6:{s.queryStatusV3Thumbnail=e.int32();break}case 7:{s.liveLocations=e.int32();break}case 8:{s.queryVname=e.int32();break}case 9:{s.voipIndividualIncoming=e.int32();break}case 10:{s.quickRepliesQuery=e.int32();break}case 11:{s.payments=e.int32();break}case 12:{s.stickerPackQuery=e.int32();break}case 13:{s.liveLocationsFinal=e.int32();break}case 14:{s.labelsEdit=e.int32();break}case 15:{s.mediaUpload=e.int32();break}case 18:{s.mediaUploadRichQuickReplies=e.int32();break}case 19:{s.vnameV2=e.int32();break}case 20:{s.videoPlaybackUrl=e.int32();break}case 21:{s.statusRanking=e.int32();break}case 22:{s.voipIndividualVideo=e.int32();break}case 23:{s.thirdPartyStickers=e.int32();break}case 24:{s.frequentlyForwardedSetting=e.int32();break}case 25:{s.groupsV4JoinPermission=e.int32();break}case 26:{s.recentStickers=e.int32();break}case 27:{s.catalog=e.int32();break}case 28:{s.starredStickers=e.int32();break}case 29:{s.voipGroupCall=e.int32();break}case 30:{s.templateMessage=e.int32();break}case 31:{s.templateMessageInteractivity=e.int32();break}case 32:{s.ephemeralMessages=e.int32();break}case 33:{s.e2ENotificationSync=e.int32();break}case 34:{s.recentStickersV2=e.int32();break}case 36:{s.recentStickersV3=e.int32();break}case 37:{s.userNotice=e.int32();break}case 39:{s.support=e.int32();break}case 40:{s.groupUiiCleanup=e.int32();break}case 41:{s.groupDogfoodingInternalOnly=e.int32();break}case 42:{s.settingsSync=e.int32();break}case 43:{s.archiveV2=e.int32();break}case 44:{s.ephemeralAllowGroupMembers=e.int32();break}case 45:{s.ephemeral24HDuration=e.int32();break}case 46:{s.mdForceUpgrade=e.int32();break}case 47:{s.disappearingMode=e.int32();break}case 48:{s.externalMdOptInAvailable=e.int32();break}case 49:{s.noDeleteMessageTimeLimit=e.int32();break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.WebFeatures)return e;var a=new E.proto.WebFeatures;switch(e.labelsDisplay){default:if(typeof e.labelsDisplay=="number"){a.labelsDisplay=e.labelsDisplay;break}break;case"NOT_STARTED":case 0:a.labelsDisplay=0;break;case"FORCE_UPGRADE":case 1:a.labelsDisplay=1;break;case"DEVELOPMENT":case 2:a.labelsDisplay=2;break;case"PRODUCTION":case 3:a.labelsDisplay=3;break}switch(e.voipIndividualOutgoing){default:if(typeof e.voipIndividualOutgoing=="number"){a.voipIndividualOutgoing=e.voipIndividualOutgoing;break}break;case"NOT_STARTED":case 0:a.voipIndividualOutgoing=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualOutgoing=1;break;case"DEVELOPMENT":case 2:a.voipIndividualOutgoing=2;break;case"PRODUCTION":case 3:a.voipIndividualOutgoing=3;break}switch(e.groupsV3){default:if(typeof e.groupsV3=="number"){a.groupsV3=e.groupsV3;break}break;case"NOT_STARTED":case 0:a.groupsV3=0;break;case"FORCE_UPGRADE":case 1:a.groupsV3=1;break;case"DEVELOPMENT":case 2:a.groupsV3=2;break;case"PRODUCTION":case 3:a.groupsV3=3;break}switch(e.groupsV3Create){default:if(typeof e.groupsV3Create=="number"){a.groupsV3Create=e.groupsV3Create;break}break;case"NOT_STARTED":case 0:a.groupsV3Create=0;break;case"FORCE_UPGRADE":case 1:a.groupsV3Create=1;break;case"DEVELOPMENT":case 2:a.groupsV3Create=2;break;case"PRODUCTION":case 3:a.groupsV3Create=3;break}switch(e.changeNumberV2){default:if(typeof e.changeNumberV2=="number"){a.changeNumberV2=e.changeNumberV2;break}break;case"NOT_STARTED":case 0:a.changeNumberV2=0;break;case"FORCE_UPGRADE":case 1:a.changeNumberV2=1;break;case"DEVELOPMENT":case 2:a.changeNumberV2=2;break;case"PRODUCTION":case 3:a.changeNumberV2=3;break}switch(e.queryStatusV3Thumbnail){default:if(typeof e.queryStatusV3Thumbnail=="number"){a.queryStatusV3Thumbnail=e.queryStatusV3Thumbnail;break}break;case"NOT_STARTED":case 0:a.queryStatusV3Thumbnail=0;break;case"FORCE_UPGRADE":case 1:a.queryStatusV3Thumbnail=1;break;case"DEVELOPMENT":case 2:a.queryStatusV3Thumbnail=2;break;case"PRODUCTION":case 3:a.queryStatusV3Thumbnail=3;break}switch(e.liveLocations){default:if(typeof e.liveLocations=="number"){a.liveLocations=e.liveLocations;break}break;case"NOT_STARTED":case 0:a.liveLocations=0;break;case"FORCE_UPGRADE":case 1:a.liveLocations=1;break;case"DEVELOPMENT":case 2:a.liveLocations=2;break;case"PRODUCTION":case 3:a.liveLocations=3;break}switch(e.queryVname){default:if(typeof e.queryVname=="number"){a.queryVname=e.queryVname;break}break;case"NOT_STARTED":case 0:a.queryVname=0;break;case"FORCE_UPGRADE":case 1:a.queryVname=1;break;case"DEVELOPMENT":case 2:a.queryVname=2;break;case"PRODUCTION":case 3:a.queryVname=3;break}switch(e.voipIndividualIncoming){default:if(typeof e.voipIndividualIncoming=="number"){a.voipIndividualIncoming=e.voipIndividualIncoming;break}break;case"NOT_STARTED":case 0:a.voipIndividualIncoming=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualIncoming=1;break;case"DEVELOPMENT":case 2:a.voipIndividualIncoming=2;break;case"PRODUCTION":case 3:a.voipIndividualIncoming=3;break}switch(e.quickRepliesQuery){default:if(typeof e.quickRepliesQuery=="number"){a.quickRepliesQuery=e.quickRepliesQuery;break}break;case"NOT_STARTED":case 0:a.quickRepliesQuery=0;break;case"FORCE_UPGRADE":case 1:a.quickRepliesQuery=1;break;case"DEVELOPMENT":case 2:a.quickRepliesQuery=2;break;case"PRODUCTION":case 3:a.quickRepliesQuery=3;break}switch(e.payments){default:if(typeof e.payments=="number"){a.payments=e.payments;break}break;case"NOT_STARTED":case 0:a.payments=0;break;case"FORCE_UPGRADE":case 1:a.payments=1;break;case"DEVELOPMENT":case 2:a.payments=2;break;case"PRODUCTION":case 3:a.payments=3;break}switch(e.stickerPackQuery){default:if(typeof e.stickerPackQuery=="number"){a.stickerPackQuery=e.stickerPackQuery;break}break;case"NOT_STARTED":case 0:a.stickerPackQuery=0;break;case"FORCE_UPGRADE":case 1:a.stickerPackQuery=1;break;case"DEVELOPMENT":case 2:a.stickerPackQuery=2;break;case"PRODUCTION":case 3:a.stickerPackQuery=3;break}switch(e.liveLocationsFinal){default:if(typeof e.liveLocationsFinal=="number"){a.liveLocationsFinal=e.liveLocationsFinal;break}break;case"NOT_STARTED":case 0:a.liveLocationsFinal=0;break;case"FORCE_UPGRADE":case 1:a.liveLocationsFinal=1;break;case"DEVELOPMENT":case 2:a.liveLocationsFinal=2;break;case"PRODUCTION":case 3:a.liveLocationsFinal=3;break}switch(e.labelsEdit){default:if(typeof e.labelsEdit=="number"){a.labelsEdit=e.labelsEdit;break}break;case"NOT_STARTED":case 0:a.labelsEdit=0;break;case"FORCE_UPGRADE":case 1:a.labelsEdit=1;break;case"DEVELOPMENT":case 2:a.labelsEdit=2;break;case"PRODUCTION":case 3:a.labelsEdit=3;break}switch(e.mediaUpload){default:if(typeof e.mediaUpload=="number"){a.mediaUpload=e.mediaUpload;break}break;case"NOT_STARTED":case 0:a.mediaUpload=0;break;case"FORCE_UPGRADE":case 1:a.mediaUpload=1;break;case"DEVELOPMENT":case 2:a.mediaUpload=2;break;case"PRODUCTION":case 3:a.mediaUpload=3;break}switch(e.mediaUploadRichQuickReplies){default:if(typeof e.mediaUploadRichQuickReplies=="number"){a.mediaUploadRichQuickReplies=e.mediaUploadRichQuickReplies;break}break;case"NOT_STARTED":case 0:a.mediaUploadRichQuickReplies=0;break;case"FORCE_UPGRADE":case 1:a.mediaUploadRichQuickReplies=1;break;case"DEVELOPMENT":case 2:a.mediaUploadRichQuickReplies=2;break;case"PRODUCTION":case 3:a.mediaUploadRichQuickReplies=3;break}switch(e.vnameV2){default:if(typeof e.vnameV2=="number"){a.vnameV2=e.vnameV2;break}break;case"NOT_STARTED":case 0:a.vnameV2=0;break;case"FORCE_UPGRADE":case 1:a.vnameV2=1;break;case"DEVELOPMENT":case 2:a.vnameV2=2;break;case"PRODUCTION":case 3:a.vnameV2=3;break}switch(e.videoPlaybackUrl){default:if(typeof e.videoPlaybackUrl=="number"){a.videoPlaybackUrl=e.videoPlaybackUrl;break}break;case"NOT_STARTED":case 0:a.videoPlaybackUrl=0;break;case"FORCE_UPGRADE":case 1:a.videoPlaybackUrl=1;break;case"DEVELOPMENT":case 2:a.videoPlaybackUrl=2;break;case"PRODUCTION":case 3:a.videoPlaybackUrl=3;break}switch(e.statusRanking){default:if(typeof e.statusRanking=="number"){a.statusRanking=e.statusRanking;break}break;case"NOT_STARTED":case 0:a.statusRanking=0;break;case"FORCE_UPGRADE":case 1:a.statusRanking=1;break;case"DEVELOPMENT":case 2:a.statusRanking=2;break;case"PRODUCTION":case 3:a.statusRanking=3;break}switch(e.voipIndividualVideo){default:if(typeof e.voipIndividualVideo=="number"){a.voipIndividualVideo=e.voipIndividualVideo;break}break;case"NOT_STARTED":case 0:a.voipIndividualVideo=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualVideo=1;break;case"DEVELOPMENT":case 2:a.voipIndividualVideo=2;break;case"PRODUCTION":case 3:a.voipIndividualVideo=3;break}switch(e.thirdPartyStickers){default:if(typeof e.thirdPartyStickers=="number"){a.thirdPartyStickers=e.thirdPartyStickers;break}break;case"NOT_STARTED":case 0:a.thirdPartyStickers=0;break;case"FORCE_UPGRADE":case 1:a.thirdPartyStickers=1;break;case"DEVELOPMENT":case 2:a.thirdPartyStickers=2;break;case"PRODUCTION":case 3:a.thirdPartyStickers=3;break}switch(e.frequentlyForwardedSetting){default:if(typeof e.frequentlyForwardedSetting=="number"){a.frequentlyForwardedSetting=e.frequentlyForwardedSetting;break}break;case"NOT_STARTED":case 0:a.frequentlyForwardedSetting=0;break;case"FORCE_UPGRADE":case 1:a.frequentlyForwardedSetting=1;break;case"DEVELOPMENT":case 2:a.frequentlyForwardedSetting=2;break;case"PRODUCTION":case 3:a.frequentlyForwardedSetting=3;break}switch(e.groupsV4JoinPermission){default:if(typeof e.groupsV4JoinPermission=="number"){a.groupsV4JoinPermission=e.groupsV4JoinPermission;break}break;case"NOT_STARTED":case 0:a.groupsV4JoinPermission=0;break;case"FORCE_UPGRADE":case 1:a.groupsV4JoinPermission=1;break;case"DEVELOPMENT":case 2:a.groupsV4JoinPermission=2;break;case"PRODUCTION":case 3:a.groupsV4JoinPermission=3;break}switch(e.recentStickers){default:if(typeof e.recentStickers=="number"){a.recentStickers=e.recentStickers;break}break;case"NOT_STARTED":case 0:a.recentStickers=0;break;case"FORCE_UPGRADE":case 1:a.recentStickers=1;break;case"DEVELOPMENT":case 2:a.recentStickers=2;break;case"PRODUCTION":case 3:a.recentStickers=3;break}switch(e.catalog){default:if(typeof e.catalog=="number"){a.catalog=e.catalog;break}break;case"NOT_STARTED":case 0:a.catalog=0;break;case"FORCE_UPGRADE":case 1:a.catalog=1;break;case"DEVELOPMENT":case 2:a.catalog=2;break;case"PRODUCTION":case 3:a.catalog=3;break}switch(e.starredStickers){default:if(typeof e.starredStickers=="number"){a.starredStickers=e.starredStickers;break}break;case"NOT_STARTED":case 0:a.starredStickers=0;break;case"FORCE_UPGRADE":case 1:a.starredStickers=1;break;case"DEVELOPMENT":case 2:a.starredStickers=2;break;case"PRODUCTION":case 3:a.starredStickers=3;break}switch(e.voipGroupCall){default:if(typeof e.voipGroupCall=="number"){a.voipGroupCall=e.voipGroupCall;break}break;case"NOT_STARTED":case 0:a.voipGroupCall=0;break;case"FORCE_UPGRADE":case 1:a.voipGroupCall=1;break;case"DEVELOPMENT":case 2:a.voipGroupCall=2;break;case"PRODUCTION":case 3:a.voipGroupCall=3;break}switch(e.templateMessage){default:if(typeof e.templateMessage=="number"){a.templateMessage=e.templateMessage;break}break;case"NOT_STARTED":case 0:a.templateMessage=0;break;case"FORCE_UPGRADE":case 1:a.templateMessage=1;break;case"DEVELOPMENT":case 2:a.templateMessage=2;break;case"PRODUCTION":case 3:a.templateMessage=3;break}switch(e.templateMessageInteractivity){default:if(typeof e.templateMessageInteractivity=="number"){a.templateMessageInteractivity=e.templateMessageInteractivity;break}break;case"NOT_STARTED":case 0:a.templateMessageInteractivity=0;break;case"FORCE_UPGRADE":case 1:a.templateMessageInteractivity=1;break;case"DEVELOPMENT":case 2:a.templateMessageInteractivity=2;break;case"PRODUCTION":case 3:a.templateMessageInteractivity=3;break}switch(e.ephemeralMessages){default:if(typeof e.ephemeralMessages=="number"){a.ephemeralMessages=e.ephemeralMessages;break}break;case"NOT_STARTED":case 0:a.ephemeralMessages=0;break;case"FORCE_UPGRADE":case 1:a.ephemeralMessages=1;break;case"DEVELOPMENT":case 2:a.ephemeralMessages=2;break;case"PRODUCTION":case 3:a.ephemeralMessages=3;break}switch(e.e2ENotificationSync){default:if(typeof e.e2ENotificationSync=="number"){a.e2ENotificationSync=e.e2ENotificationSync;break}break;case"NOT_STARTED":case 0:a.e2ENotificationSync=0;break;case"FORCE_UPGRADE":case 1:a.e2ENotificationSync=1;break;case"DEVELOPMENT":case 2:a.e2ENotificationSync=2;break;case"PRODUCTION":case 3:a.e2ENotificationSync=3;break}switch(e.recentStickersV2){default:if(typeof e.recentStickersV2=="number"){a.recentStickersV2=e.recentStickersV2;break}break;case"NOT_STARTED":case 0:a.recentStickersV2=0;break;case"FORCE_UPGRADE":case 1:a.recentStickersV2=1;break;case"DEVELOPMENT":case 2:a.recentStickersV2=2;break;case"PRODUCTION":case 3:a.recentStickersV2=3;break}switch(e.recentStickersV3){default:if(typeof e.recentStickersV3=="number"){a.recentStickersV3=e.recentStickersV3;break}break;case"NOT_STARTED":case 0:a.recentStickersV3=0;break;case"FORCE_UPGRADE":case 1:a.recentStickersV3=1;break;case"DEVELOPMENT":case 2:a.recentStickersV3=2;break;case"PRODUCTION":case 3:a.recentStickersV3=3;break}switch(e.userNotice){default:if(typeof e.userNotice=="number"){a.userNotice=e.userNotice;break}break;case"NOT_STARTED":case 0:a.userNotice=0;break;case"FORCE_UPGRADE":case 1:a.userNotice=1;break;case"DEVELOPMENT":case 2:a.userNotice=2;break;case"PRODUCTION":case 3:a.userNotice=3;break}switch(e.support){default:if(typeof e.support=="number"){a.support=e.support;break}break;case"NOT_STARTED":case 0:a.support=0;break;case"FORCE_UPGRADE":case 1:a.support=1;break;case"DEVELOPMENT":case 2:a.support=2;break;case"PRODUCTION":case 3:a.support=3;break}switch(e.groupUiiCleanup){default:if(typeof e.groupUiiCleanup=="number"){a.groupUiiCleanup=e.groupUiiCleanup;break}break;case"NOT_STARTED":case 0:a.groupUiiCleanup=0;break;case"FORCE_UPGRADE":case 1:a.groupUiiCleanup=1;break;case"DEVELOPMENT":case 2:a.groupUiiCleanup=2;break;case"PRODUCTION":case 3:a.groupUiiCleanup=3;break}switch(e.groupDogfoodingInternalOnly){default:if(typeof e.groupDogfoodingInternalOnly=="number"){a.groupDogfoodingInternalOnly=e.groupDogfoodingInternalOnly;break}break;case"NOT_STARTED":case 0:a.groupDogfoodingInternalOnly=0;break;case"FORCE_UPGRADE":case 1:a.groupDogfoodingInternalOnly=1;break;case"DEVELOPMENT":case 2:a.groupDogfoodingInternalOnly=2;break;case"PRODUCTION":case 3:a.groupDogfoodingInternalOnly=3;break}switch(e.settingsSync){default:if(typeof e.settingsSync=="number"){a.settingsSync=e.settingsSync;break}break;case"NOT_STARTED":case 0:a.settingsSync=0;break;case"FORCE_UPGRADE":case 1:a.settingsSync=1;break;case"DEVELOPMENT":case 2:a.settingsSync=2;break;case"PRODUCTION":case 3:a.settingsSync=3;break}switch(e.archiveV2){default:if(typeof e.archiveV2=="number"){a.archiveV2=e.archiveV2;break}break;case"NOT_STARTED":case 0:a.archiveV2=0;break;case"FORCE_UPGRADE":case 1:a.archiveV2=1;break;case"DEVELOPMENT":case 2:a.archiveV2=2;break;case"PRODUCTION":case 3:a.archiveV2=3;break}switch(e.ephemeralAllowGroupMembers){default:if(typeof e.ephemeralAllowGroupMembers=="number"){a.ephemeralAllowGroupMembers=e.ephemeralAllowGroupMembers;break}break;case"NOT_STARTED":case 0:a.ephemeralAllowGroupMembers=0;break;case"FORCE_UPGRADE":case 1:a.ephemeralAllowGroupMembers=1;break;case"DEVELOPMENT":case 2:a.ephemeralAllowGroupMembers=2;break;case"PRODUCTION":case 3:a.ephemeralAllowGroupMembers=3;break}switch(e.ephemeral24HDuration){default:if(typeof e.ephemeral24HDuration=="number"){a.ephemeral24HDuration=e.ephemeral24HDuration;break}break;case"NOT_STARTED":case 0:a.ephemeral24HDuration=0;break;case"FORCE_UPGRADE":case 1:a.ephemeral24HDuration=1;break;case"DEVELOPMENT":case 2:a.ephemeral24HDuration=2;break;case"PRODUCTION":case 3:a.ephemeral24HDuration=3;break}switch(e.mdForceUpgrade){default:if(typeof e.mdForceUpgrade=="number"){a.mdForceUpgrade=e.mdForceUpgrade;break}break;case"NOT_STARTED":case 0:a.mdForceUpgrade=0;break;case"FORCE_UPGRADE":case 1:a.mdForceUpgrade=1;break;case"DEVELOPMENT":case 2:a.mdForceUpgrade=2;break;case"PRODUCTION":case 3:a.mdForceUpgrade=3;break}switch(e.disappearingMode){default:if(typeof e.disappearingMode=="number"){a.disappearingMode=e.disappearingMode;break}break;case"NOT_STARTED":case 0:a.disappearingMode=0;break;case"FORCE_UPGRADE":case 1:a.disappearingMode=1;break;case"DEVELOPMENT":case 2:a.disappearingMode=2;break;case"PRODUCTION":case 3:a.disappearingMode=3;break}switch(e.externalMdOptInAvailable){default:if(typeof e.externalMdOptInAvailable=="number"){a.externalMdOptInAvailable=e.externalMdOptInAvailable;break}break;case"NOT_STARTED":case 0:a.externalMdOptInAvailable=0;break;case"FORCE_UPGRADE":case 1:a.externalMdOptInAvailable=1;break;case"DEVELOPMENT":case 2:a.externalMdOptInAvailable=2;break;case"PRODUCTION":case 3:a.externalMdOptInAvailable=3;break}switch(e.noDeleteMessageTimeLimit){default:if(typeof e.noDeleteMessageTimeLimit=="number"){a.noDeleteMessageTimeLimit=e.noDeleteMessageTimeLimit;break}break;case"NOT_STARTED":case 0:a.noDeleteMessageTimeLimit=0;break;case"FORCE_UPGRADE":case 1:a.noDeleteMessageTimeLimit=1;break;case"DEVELOPMENT":case 2:a.noDeleteMessageTimeLimit=2;break;case"PRODUCTION":case 3:a.noDeleteMessageTimeLimit=3;break}return a},r.toObject=function(e,a){a||(a={});var A={};return e.labelsDisplay!=null&&e.hasOwnProperty("labelsDisplay")&&(A.labelsDisplay=a.enums===String?E.proto.WebFeatures.Flag[e.labelsDisplay]===void 0?e.labelsDisplay:E.proto.WebFeatures.Flag[e.labelsDisplay]:e.labelsDisplay,a.oneofs&&(A._labelsDisplay="labelsDisplay")),e.voipIndividualOutgoing!=null&&e.hasOwnProperty("voipIndividualOutgoing")&&(A.voipIndividualOutgoing=a.enums===String?E.proto.WebFeatures.Flag[e.voipIndividualOutgoing]===void 0?e.voipIndividualOutgoing:E.proto.WebFeatures.Flag[e.voipIndividualOutgoing]:e.voipIndividualOutgoing,a.oneofs&&(A._voipIndividualOutgoing="voipIndividualOutgoing")),e.groupsV3!=null&&e.hasOwnProperty("groupsV3")&&(A.groupsV3=a.enums===String?E.proto.WebFeatures.Flag[e.groupsV3]===void 0?e.groupsV3:E.proto.WebFeatures.Flag[e.groupsV3]:e.groupsV3,a.oneofs&&(A._groupsV3="groupsV3")),e.groupsV3Create!=null&&e.hasOwnProperty("groupsV3Create")&&(A.groupsV3Create=a.enums===String?E.proto.WebFeatures.Flag[e.groupsV3Create]===void 0?e.groupsV3Create:E.proto.WebFeatures.Flag[e.groupsV3Create]:e.groupsV3Create,a.oneofs&&(A._groupsV3Create="groupsV3Create")),e.changeNumberV2!=null&&e.hasOwnProperty("changeNumberV2")&&(A.changeNumberV2=a.enums===String?E.proto.WebFeatures.Flag[e.changeNumberV2]===void 0?e.changeNumberV2:E.proto.WebFeatures.Flag[e.changeNumberV2]:e.changeNumberV2,a.oneofs&&(A._changeNumberV2="changeNumberV2")),e.queryStatusV3Thumbnail!=null&&e.hasOwnProperty("queryStatusV3Thumbnail")&&(A.queryStatusV3Thumbnail=a.enums===String?E.proto.WebFeatures.Flag[e.queryStatusV3Thumbnail]===void 0?e.queryStatusV3Thumbnail:E.proto.WebFeatures.Flag[e.queryStatusV3Thumbnail]:e.queryStatusV3Thumbnail,a.oneofs&&(A._queryStatusV3Thumbnail="queryStatusV3Thumbnail")),e.liveLocations!=null&&e.hasOwnProperty("liveLocations")&&(A.liveLocations=a.enums===String?E.proto.WebFeatures.Flag[e.liveLocations]===void 0?e.liveLocations:E.proto.WebFeatures.Flag[e.liveLocations]:e.liveLocations,a.oneofs&&(A._liveLocations="liveLocations")),e.queryVname!=null&&e.hasOwnProperty("queryVname")&&(A.queryVname=a.enums===String?E.proto.WebFeatures.Flag[e.queryVname]===void 0?e.queryVname:E.proto.WebFeatures.Flag[e.queryVname]:e.queryVname,a.oneofs&&(A._queryVname="queryVname")),e.voipIndividualIncoming!=null&&e.hasOwnProperty("voipIndividualIncoming")&&(A.voipIndividualIncoming=a.enums===String?E.proto.WebFeatures.Flag[e.voipIndividualIncoming]===void 0?e.voipIndividualIncoming:E.proto.WebFeatures.Flag[e.voipIndividualIncoming]:e.voipIndividualIncoming,a.oneofs&&(A._voipIndividualIncoming="voipIndividualIncoming")),e.quickRepliesQuery!=null&&e.hasOwnProperty("quickRepliesQuery")&&(A.quickRepliesQuery=a.enums===String?E.proto.WebFeatures.Flag[e.quickRepliesQuery]===void 0?e.quickRepliesQuery:E.proto.WebFeatures.Flag[e.quickRepliesQuery]:e.quickRepliesQuery,a.oneofs&&(A._quickRepliesQuery="quickRepliesQuery")),e.payments!=null&&e.hasOwnProperty("payments")&&(A.payments=a.enums===String?E.proto.WebFeatures.Flag[e.payments]===void 0?e.payments:E.proto.WebFeatures.Flag[e.payments]:e.payments,a.oneofs&&(A._payments="payments")),e.stickerPackQuery!=null&&e.hasOwnProperty("stickerPackQuery")&&(A.stickerPackQuery=a.enums===String?E.proto.WebFeatures.Flag[e.stickerPackQuery]===void 0?e.stickerPackQuery:E.proto.WebFeatures.Flag[e.stickerPackQuery]:e.stickerPackQuery,a.oneofs&&(A._stickerPackQuery="stickerPackQuery")),e.liveLocationsFinal!=null&&e.hasOwnProperty("liveLocationsFinal")&&(A.liveLocationsFinal=a.enums===String?E.proto.WebFeatures.Flag[e.liveLocationsFinal]===void 0?e.liveLocationsFinal:E.proto.WebFeatures.Flag[e.liveLocationsFinal]:e.liveLocationsFinal,a.oneofs&&(A._liveLocationsFinal="liveLocationsFinal")),e.labelsEdit!=null&&e.hasOwnProperty("labelsEdit")&&(A.labelsEdit=a.enums===String?E.proto.WebFeatures.Flag[e.labelsEdit]===void 0?e.labelsEdit:E.proto.WebFeatures.Flag[e.labelsEdit]:e.labelsEdit,a.oneofs&&(A._labelsEdit="labelsEdit")),e.mediaUpload!=null&&e.hasOwnProperty("mediaUpload")&&(A.mediaUpload=a.enums===String?E.proto.WebFeatures.Flag[e.mediaUpload]===void 0?e.mediaUpload:E.proto.WebFeatures.Flag[e.mediaUpload]:e.mediaUpload,a.oneofs&&(A._mediaUpload="mediaUpload")),e.mediaUploadRichQuickReplies!=null&&e.hasOwnProperty("mediaUploadRichQuickReplies")&&(A.mediaUploadRichQuickReplies=a.enums===String?E.proto.WebFeatures.Flag[e.mediaUploadRichQuickReplies]===void 0?e.mediaUploadRichQuickReplies:E.proto.WebFeatures.Flag[e.mediaUploadRichQuickReplies]:e.mediaUploadRichQuickReplies,a.oneofs&&(A._mediaUploadRichQuickReplies="mediaUploadRichQuickReplies")),e.vnameV2!=null&&e.hasOwnProperty("vnameV2")&&(A.vnameV2=a.enums===String?E.proto.WebFeatures.Flag[e.vnameV2]===void 0?e.vnameV2:E.proto.WebFeatures.Flag[e.vnameV2]:e.vnameV2,a.oneofs&&(A._vnameV2="vnameV2")),e.videoPlaybackUrl!=null&&e.hasOwnProperty("videoPlaybackUrl")&&(A.videoPlaybackUrl=a.enums===String?E.proto.WebFeatures.Flag[e.videoPlaybackUrl]===void 0?e.videoPlaybackUrl:E.proto.WebFeatures.Flag[e.videoPlaybackUrl]:e.videoPlaybackUrl,a.oneofs&&(A._videoPlaybackUrl="videoPlaybackUrl")),e.statusRanking!=null&&e.hasOwnProperty("statusRanking")&&(A.statusRanking=a.enums===String?E.proto.WebFeatures.Flag[e.statusRanking]===void 0?e.statusRanking:E.proto.WebFeatures.Flag[e.statusRanking]:e.statusRanking,a.oneofs&&(A._statusRanking="statusRanking")),e.voipIndividualVideo!=null&&e.hasOwnProperty("voipIndividualVideo")&&(A.voipIndividualVideo=a.enums===String?E.proto.WebFeatures.Flag[e.voipIndividualVideo]===void 0?e.voipIndividualVideo:E.proto.WebFeatures.Flag[e.voipIndividualVideo]:e.voipIndividualVideo,a.oneofs&&(A._voipIndividualVideo="voipIndividualVideo")),e.thirdPartyStickers!=null&&e.hasOwnProperty("thirdPartyStickers")&&(A.thirdPartyStickers=a.enums===String?E.proto.WebFeatures.Flag[e.thirdPartyStickers]===void 0?e.thirdPartyStickers:E.proto.WebFeatures.Flag[e.thirdPartyStickers]:e.thirdPartyStickers,a.oneofs&&(A._thirdPartyStickers="thirdPartyStickers")),e.frequentlyForwardedSetting!=null&&e.hasOwnProperty("frequentlyForwardedSetting")&&(A.frequentlyForwardedSetting=a.enums===String?E.proto.WebFeatures.Flag[e.frequentlyForwardedSetting]===void 0?e.frequentlyForwardedSetting:E.proto.WebFeatures.Flag[e.frequentlyForwardedSetting]:e.frequentlyForwardedSetting,a.oneofs&&(A._frequentlyForwardedSetting="frequentlyForwardedSetting")),e.groupsV4JoinPermission!=null&&e.hasOwnProperty("groupsV4JoinPermission")&&(A.groupsV4JoinPermission=a.enums===String?E.proto.WebFeatures.Flag[e.groupsV4JoinPermission]===void 0?e.groupsV4JoinPermission:E.proto.WebFeatures.Flag[e.groupsV4JoinPermission]:e.groupsV4JoinPermission,a.oneofs&&(A._groupsV4JoinPermission="groupsV4JoinPermission")),e.recentStickers!=null&&e.hasOwnProperty("recentStickers")&&(A.recentStickers=a.enums===String?E.proto.WebFeatures.Flag[e.recentStickers]===void 0?e.recentStickers:E.proto.WebFeatures.Flag[e.recentStickers]:e.recentStickers,a.oneofs&&(A._recentStickers="recentStickers")),e.catalog!=null&&e.hasOwnProperty("catalog")&&(A.catalog=a.enums===String?E.proto.WebFeatures.Flag[e.catalog]===void 0?e.catalog:E.proto.WebFeatures.Flag[e.catalog]:e.catalog,a.oneofs&&(A._catalog="catalog")),e.starredStickers!=null&&e.hasOwnProperty("starredStickers")&&(A.starredStickers=a.enums===String?E.proto.WebFeatures.Flag[e.starredStickers]===void 0?e.starredStickers:E.proto.WebFeatures.Flag[e.starredStickers]:e.starredStickers,a.oneofs&&(A._starredStickers="starredStickers")),e.voipGroupCall!=null&&e.hasOwnProperty("voipGroupCall")&&(A.voipGroupCall=a.enums===String?E.proto.WebFeatures.Flag[e.voipGroupCall]===void 0?e.voipGroupCall:E.proto.WebFeatures.Flag[e.voipGroupCall]:e.voipGroupCall,a.oneofs&&(A._voipGroupCall="voipGroupCall")),e.templateMessage!=null&&e.hasOwnProperty("templateMessage")&&(A.templateMessage=a.enums===String?E.proto.WebFeatures.Flag[e.templateMessage]===void 0?e.templateMessage:E.proto.WebFeatures.Flag[e.templateMessage]:e.templateMessage,a.oneofs&&(A._templateMessage="templateMessage")),e.templateMessageInteractivity!=null&&e.hasOwnProperty("templateMessageInteractivity")&&(A.templateMessageInteractivity=a.enums===String?E.proto.WebFeatures.Flag[e.templateMessageInteractivity]===void 0?e.templateMessageInteractivity:E.proto.WebFeatures.Flag[e.templateMessageInteractivity]:e.templateMessageInteractivity,a.oneofs&&(A._templateMessageInteractivity="templateMessageInteractivity")),e.ephemeralMessages!=null&&e.hasOwnProperty("ephemeralMessages")&&(A.ephemeralMessages=a.enums===String?E.proto.WebFeatures.Flag[e.ephemeralMessages]===void 0?e.ephemeralMessages:E.proto.WebFeatures.Flag[e.ephemeralMessages]:e.ephemeralMessages,a.oneofs&&(A._ephemeralMessages="ephemeralMessages")),e.e2ENotificationSync!=null&&e.hasOwnProperty("e2ENotificationSync")&&(A.e2ENotificationSync=a.enums===String?E.proto.WebFeatures.Flag[e.e2ENotificationSync]===void 0?e.e2ENotificationSync:E.proto.WebFeatures.Flag[e.e2ENotificationSync]:e.e2ENotificationSync,a.oneofs&&(A._e2ENotificationSync="e2ENotificationSync")),e.recentStickersV2!=null&&e.hasOwnProperty("recentStickersV2")&&(A.recentStickersV2=a.enums===String?E.proto.WebFeatures.Flag[e.recentStickersV2]===void 0?e.recentStickersV2:E.proto.WebFeatures.Flag[e.recentStickersV2]:e.recentStickersV2,a.oneofs&&(A._recentStickersV2="recentStickersV2")),e.recentStickersV3!=null&&e.hasOwnProperty("recentStickersV3")&&(A.recentStickersV3=a.enums===String?E.proto.WebFeatures.Flag[e.recentStickersV3]===void 0?e.recentStickersV3:E.proto.WebFeatures.Flag[e.recentStickersV3]:e.recentStickersV3,a.oneofs&&(A._recentStickersV3="recentStickersV3")),e.userNotice!=null&&e.hasOwnProperty("userNotice")&&(A.userNotice=a.enums===String?E.proto.WebFeatures.Flag[e.userNotice]===void 0?e.userNotice:E.proto.WebFeatures.Flag[e.userNotice]:e.userNotice,a.oneofs&&(A._userNotice="userNotice")),e.support!=null&&e.hasOwnProperty("support")&&(A.support=a.enums===String?E.proto.WebFeatures.Flag[e.support]===void 0?e.support:E.proto.WebFeatures.Flag[e.support]:e.support,a.oneofs&&(A._support="support")),e.groupUiiCleanup!=null&&e.hasOwnProperty("groupUiiCleanup")&&(A.groupUiiCleanup=a.enums===String?E.proto.WebFeatures.Flag[e.groupUiiCleanup]===void 0?e.groupUiiCleanup:E.proto.WebFeatures.Flag[e.groupUiiCleanup]:e.groupUiiCleanup,a.oneofs&&(A._groupUiiCleanup="groupUiiCleanup")),e.groupDogfoodingInternalOnly!=null&&e.hasOwnProperty("groupDogfoodingInternalOnly")&&(A.groupDogfoodingInternalOnly=a.enums===String?E.proto.WebFeatures.Flag[e.groupDogfoodingInternalOnly]===void 0?e.groupDogfoodingInternalOnly:E.proto.WebFeatures.Flag[e.groupDogfoodingInternalOnly]:e.groupDogfoodingInternalOnly,a.oneofs&&(A._groupDogfoodingInternalOnly="groupDogfoodingInternalOnly")),e.settingsSync!=null&&e.hasOwnProperty("settingsSync")&&(A.settingsSync=a.enums===String?E.proto.WebFeatures.Flag[e.settingsSync]===void 0?e.settingsSync:E.proto.WebFeatures.Flag[e.settingsSync]:e.settingsSync,a.oneofs&&(A._settingsSync="settingsSync")),e.archiveV2!=null&&e.hasOwnProperty("archiveV2")&&(A.archiveV2=a.enums===String?E.proto.WebFeatures.Flag[e.archiveV2]===void 0?e.archiveV2:E.proto.WebFeatures.Flag[e.archiveV2]:e.archiveV2,a.oneofs&&(A._archiveV2="archiveV2")),e.ephemeralAllowGroupMembers!=null&&e.hasOwnProperty("ephemeralAllowGroupMembers")&&(A.ephemeralAllowGroupMembers=a.enums===String?E.proto.WebFeatures.Flag[e.ephemeralAllowGroupMembers]===void 0?e.ephemeralAllowGroupMembers:E.proto.WebFeatures.Flag[e.ephemeralAllowGroupMembers]:e.ephemeralAllowGroupMembers,a.oneofs&&(A._ephemeralAllowGroupMembers="ephemeralAllowGroupMembers")),e.ephemeral24HDuration!=null&&e.hasOwnProperty("ephemeral24HDuration")&&(A.ephemeral24HDuration=a.enums===String?E.proto.WebFeatures.Flag[e.ephemeral24HDuration]===void 0?e.ephemeral24HDuration:E.proto.WebFeatures.Flag[e.ephemeral24HDuration]:e.ephemeral24HDuration,a.oneofs&&(A._ephemeral24HDuration="ephemeral24HDuration")),e.mdForceUpgrade!=null&&e.hasOwnProperty("mdForceUpgrade")&&(A.mdForceUpgrade=a.enums===String?E.proto.WebFeatures.Flag[e.mdForceUpgrade]===void 0?e.mdForceUpgrade:E.proto.WebFeatures.Flag[e.mdForceUpgrade]:e.mdForceUpgrade,a.oneofs&&(A._mdForceUpgrade="mdForceUpgrade")),e.disappearingMode!=null&&e.hasOwnProperty("disappearingMode")&&(A.disappearingMode=a.enums===String?E.proto.WebFeatures.Flag[e.disappearingMode]===void 0?e.disappearingMode:E.proto.WebFeatures.Flag[e.disappearingMode]:e.disappearingMode,a.oneofs&&(A._disappearingMode="disappearingMode")),e.externalMdOptInAvailable!=null&&e.hasOwnProperty("externalMdOptInAvailable")&&(A.externalMdOptInAvailable=a.enums===String?E.proto.WebFeatures.Flag[e.externalMdOptInAvailable]===void 0?e.externalMdOptInAvailable:E.proto.WebFeatures.Flag[e.externalMdOptInAvailable]:e.externalMdOptInAvailable,a.oneofs&&(A._externalMdOptInAvailable="externalMdOptInAvailable")),e.noDeleteMessageTimeLimit!=null&&e.hasOwnProperty("noDeleteMessageTimeLimit")&&(A.noDeleteMessageTimeLimit=a.enums===String?E.proto.WebFeatures.Flag[e.noDeleteMessageTimeLimit]===void 0?e.noDeleteMessageTimeLimit:E.proto.WebFeatures.Flag[e.noDeleteMessageTimeLimit]:e.noDeleteMessageTimeLimit,a.oneofs&&(A._noDeleteMessageTimeLimit="noDeleteMessageTimeLimit")),A},r.prototype.toJSON=function(){return this.constructor.toObject(this,_.default.util.toJSONOptions)},r.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.WebFeatures"},r.Flag=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_STARTED"]=0,e[i[1]="FORCE_UPGRADE"]=1,e[i[2]="DEVELOPMENT"]=2,e[i[3]="PRODUCTION"]=3,e})(),r})(),n.WebLinkRenderConfig=(function(){let r={},o=Object.create(r);return o[r[0]="WEBVIEW"]=0,o[r[1]="SYSTEM"]=1,o})(),n.WebMessageInfo=(function(){function r(i){if(this.messageStubParameters=[],this.labels=[],this.userReceipt=[],this.reactions=[],this.pollUpdates=[],this.eventResponses=[],this.statusMentions=[],this.messageAddOns=[],this.statusMentionSources=[],this.supportAiCitations=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=E.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=E.proto.Message.decode(e,e.uint32());break}case 3:{s.messageTimestamp=e.uint64();break}case 4:{s.status=e.int32();break}case 5:{s.participant=e.string();break}case 6:{s.messageC2STimestamp=e.uint64();break}case 16:{s.ignore=e.bool();break}case 17:{s.starred=e.bool();break}case 18:{s.broadcast=e.bool();break}case 19:{s.pushName=e.string();break}case 20:{s.mediaCiphertextSha256=e.bytes();break}case 21:{s.multicast=e.bool();break}case 22:{s.urlText=e.bool();break}case 23:{s.urlNumber=e.bool();break}case 24:{s.messageStubType=e.int32();break}case 25:{s.clearMedia=e.bool();break}case 26:{s.messageStubParameters&&s.messageStubParameters.length||(s.messageStubParameters=[]),s.messageStubParameters.push(e.string());break}case 27:{s.duration=e.uint32();break}case 28:{s.labels&&s.labels.length||(s.labels=[]),s.labels.push(e.string());break}case 29:{s.paymentInfo=E.proto.PaymentInfo.decode(e,e.uint32());break}case 30:{s.finalLiveLocation=E.proto.Message.LiveLocationMessage.decode(e,e.uint32());break}case 31:{s.quotedPaymentInfo=E.proto.PaymentInfo.decode(e,e.uint32());break}case 32:{s.ephemeralStartTimestamp=e.uint64();break}case 33:{s.ephemeralDuration=e.uint32();break}case 34:{s.ephemeralOffToOn=e.bool();break}case 35:{s.ephemeralOutOfSync=e.bool();break}case 36:{s.bizPrivacyStatus=e.int32();break}case 37:{s.verifiedBizName=e.string();break}case 38:{s.mediaData=E.proto.MediaData.decode(e,e.uint32());break}case 39:{s.photoChange=E.proto.PhotoChange.decode(e,e.uint32());break}case 40:{s.userReceipt&&s.userReceipt.length||(s.userReceipt=[]),s.userReceipt.push(E.proto.UserReceipt.decode(e,e.uint32()));break}case 41:{s.reactions&&s.reactions.length||(s.reactions=[]),s.reactions.push(E.proto.Reaction.decode(e,e.uint32()));break}case 42:{s.quotedStickerData=E.proto.MediaData.decode(e,e.uint32());break}case 43:{s.futureproofData=e.bytes();break}case 44:{s.statusPsa=E.proto.StatusPSA.decode(e,e.uint32());break}case 45:{s.pollUpdates&&s.pollUpdates.length||(s.pollUpdates=[]),s.pollUpdates.push(E.proto.PollUpdate.decode(e,e.uint32()));break}case 46:{s.pollAdditionalMetadata=E.proto.PollAdditionalMetadata.decode(e,e.uint32());break}case 47:{s.agentId=e.string();break}case 48:{s.statusAlreadyViewed=e.bool();break}case 49:{s.messageSecret=e.bytes();break}case 50:{s.keepInChat=E.proto.KeepInChat.decode(e,e.uint32());break}case 51:{s.originalSelfAuthorUserJidString=e.string();break}case 52:{s.revokeMessageTimestamp=e.uint64();break}case 54:{s.pinInChat=E.proto.PinInChat.decode(e,e.uint32());break}case 55:{s.premiumMessageInfo=E.proto.PremiumMessageInfo.decode(e,e.uint32());break}case 56:{s.is1PBizBotMessage=e.bool();break}case 57:{s.isGroupHistoryMessage=e.bool();break}case 58:{s.botMessageInvokerJid=e.string();break}case 59:{s.commentMetadata=E.proto.CommentMetadata.decode(e,e.uint32());break}case 61:{s.eventResponses&&s.eventResponses.length||(s.eventResponses=[]),s.eventResponses.push(E.proto.EventResponse.decode(e,e.uint32()));break}case 62:{s.reportingTokenInfo=E.proto.ReportingTokenInfo.decode(e,e.uint32());break}case 63:{s.newsletterServerId=e.uint64();break}case 64:{s.eventAdditionalMetadata=E.proto.EventAdditionalMetadata.decode(e,e.uint32());break}case 65:{s.isMentionedInStatus=e.bool();break}case 66:{s.statusMentions&&s.statusMentions.length||(s.statusMentions=[]),s.statusMentions.push(e.string());break}case 67:{s.targetMessageId=E.proto.MessageKey.decode(e,e.uint32());break}case 68:{s.messageAddOns&&s.messageAddOns.length||(s.messageAddOns=[]),s.messageAddOns.push(E.proto.MessageAddOn.decode(e,e.uint32()));break}case 69:{s.statusMentionMessageInfo=E.proto.StatusMentionMessage.decode(e,e.uint32());break}case 70:{s.isSupportAiMessage=e.bool();break}case 71:{s.statusMentionSources&&s.statusMentionSources.length||(s.statusMentionSources=[]),s.statusMentionSources.push(e.string());break}case 72:{s.supportAiCitations&&s.supportAiCitations.length||(s.supportAiCitations=[]),s.supportAiCitations.push(E.proto.Citation.decode(e,e.uint32()));break}case 73:{s.botTargetId=e.string();break}case 74:{s.groupHistoryIndividualMessageInfo=E.proto.GroupHistoryIndividualMessageInfo.decode(e,e.uint32());break}case 75:{s.groupHistoryBundleInfo=E.proto.GroupHistoryBundleInfo.decode(e,e.uint32());break}case 76:{s.interactiveMessageAdditionalMetadata=E.proto.InteractiveMessageAdditionalMetadata.decode(e,e.uint32());break}case 77:{s.quarantinedMessage=E.proto.QuarantinedMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.WebMessageInfo)return e;var a=new E.proto.WebMessageInfo;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.WebMessageInfo.key: object expected");a.key=E.proto.MessageKey.fromObject(e.key)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.WebMessageInfo.message: object expected");a.message=E.proto.Message.fromObject(e.message)}switch(e.messageTimestamp!=null&&(I.Long?(a.messageTimestamp=I.Long.fromValue(e.messageTimestamp)).unsigned=!0:typeof e.messageTimestamp=="string"?a.messageTimestamp=parseInt(e.messageTimestamp,10):typeof e.messageTimestamp=="number"?a.messageTimestamp=e.messageTimestamp:typeof e.messageTimestamp=="object"&&(a.messageTimestamp=new I.LongBits(e.messageTimestamp.low>>>0,e.messageTimestamp.high>>>0).toNumber(!0))),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"ERROR":case 0:a.status=0;break;case"PENDING":case 1:a.status=1;break;case"SERVER_ACK":case 2:a.status=2;break;case"DELIVERY_ACK":case 3:a.status=3;break;case"READ":case 4:a.status=4;break;case"PLAYED":case 5:a.status=5;break}switch(e.participant!=null&&(a.participant=String(e.participant)),e.messageC2STimestamp!=null&&(I.Long?(a.messageC2STimestamp=I.Long.fromValue(e.messageC2STimestamp)).unsigned=!0:typeof e.messageC2STimestamp=="string"?a.messageC2STimestamp=parseInt(e.messageC2STimestamp,10):typeof e.messageC2STimestamp=="number"?a.messageC2STimestamp=e.messageC2STimestamp:typeof e.messageC2STimestamp=="object"&&(a.messageC2STimestamp=new I.LongBits(e.messageC2STimestamp.low>>>0,e.messageC2STimestamp.high>>>0).toNumber(!0))),e.ignore!=null&&(a.ignore=!!e.ignore),e.starred!=null&&(a.starred=!!e.starred),e.broadcast!=null&&(a.broadcast=!!e.broadcast),e.pushName!=null&&(a.pushName=String(e.pushName)),e.mediaCiphertextSha256!=null&&(typeof e.mediaCiphertextSha256=="string"?I.base64.decode(e.mediaCiphertextSha256,a.mediaCiphertextSha256=I.newBuffer(I.base64.length(e.mediaCiphertextSha256)),0):e.mediaCiphertextSha256.length>=0&&(a.mediaCiphertextSha256=e.mediaCiphertextSha256)),e.multicast!=null&&(a.multicast=!!e.multicast),e.urlText!=null&&(a.urlText=!!e.urlText),e.urlNumber!=null&&(a.urlNumber=!!e.urlNumber),e.messageStubType){default:if(typeof e.messageStubType=="number"){a.messageStubType=e.messageStubType;break}break;case"UNKNOWN":case 0:a.messageStubType=0;break;case"REVOKE":case 1:a.messageStubType=1;break;case"CIPHERTEXT":case 2:a.messageStubType=2;break;case"FUTUREPROOF":case 3:a.messageStubType=3;break;case"NON_VERIFIED_TRANSITION":case 4:a.messageStubType=4;break;case"UNVERIFIED_TRANSITION":case 5:a.messageStubType=5;break;case"VERIFIED_TRANSITION":case 6:a.messageStubType=6;break;case"VERIFIED_LOW_UNKNOWN":case 7:a.messageStubType=7;break;case"VERIFIED_HIGH":case 8:a.messageStubType=8;break;case"VERIFIED_INITIAL_UNKNOWN":case 9:a.messageStubType=9;break;case"VERIFIED_INITIAL_LOW":case 10:a.messageStubType=10;break;case"VERIFIED_INITIAL_HIGH":case 11:a.messageStubType=11;break;case"VERIFIED_TRANSITION_ANY_TO_NONE":case 12:a.messageStubType=12;break;case"VERIFIED_TRANSITION_ANY_TO_HIGH":case 13:a.messageStubType=13;break;case"VERIFIED_TRANSITION_HIGH_TO_LOW":case 14:a.messageStubType=14;break;case"VERIFIED_TRANSITION_HIGH_TO_UNKNOWN":case 15:a.messageStubType=15;break;case"VERIFIED_TRANSITION_UNKNOWN_TO_LOW":case 16:a.messageStubType=16;break;case"VERIFIED_TRANSITION_LOW_TO_UNKNOWN":case 17:a.messageStubType=17;break;case"VERIFIED_TRANSITION_NONE_TO_LOW":case 18:a.messageStubType=18;break;case"VERIFIED_TRANSITION_NONE_TO_UNKNOWN":case 19:a.messageStubType=19;break;case"GROUP_CREATE":case 20:a.messageStubType=20;break;case"GROUP_CHANGE_SUBJECT":case 21:a.messageStubType=21;break;case"GROUP_CHANGE_ICON":case 22:a.messageStubType=22;break;case"GROUP_CHANGE_INVITE_LINK":case 23:a.messageStubType=23;break;case"GROUP_CHANGE_DESCRIPTION":case 24:a.messageStubType=24;break;case"GROUP_CHANGE_RESTRICT":case 25:a.messageStubType=25;break;case"GROUP_CHANGE_ANNOUNCE":case 26:a.messageStubType=26;break;case"GROUP_PARTICIPANT_ADD":case 27:a.messageStubType=27;break;case"GROUP_PARTICIPANT_REMOVE":case 28:a.messageStubType=28;break;case"GROUP_PARTICIPANT_PROMOTE":case 29:a.messageStubType=29;break;case"GROUP_PARTICIPANT_DEMOTE":case 30:a.messageStubType=30;break;case"GROUP_PARTICIPANT_INVITE":case 31:a.messageStubType=31;break;case"GROUP_PARTICIPANT_LEAVE":case 32:a.messageStubType=32;break;case"GROUP_PARTICIPANT_CHANGE_NUMBER":case 33:a.messageStubType=33;break;case"BROADCAST_CREATE":case 34:a.messageStubType=34;break;case"BROADCAST_ADD":case 35:a.messageStubType=35;break;case"BROADCAST_REMOVE":case 36:a.messageStubType=36;break;case"GENERIC_NOTIFICATION":case 37:a.messageStubType=37;break;case"E2E_IDENTITY_CHANGED":case 38:a.messageStubType=38;break;case"E2E_ENCRYPTED":case 39:a.messageStubType=39;break;case"CALL_MISSED_VOICE":case 40:a.messageStubType=40;break;case"CALL_MISSED_VIDEO":case 41:a.messageStubType=41;break;case"INDIVIDUAL_CHANGE_NUMBER":case 42:a.messageStubType=42;break;case"GROUP_DELETE":case 43:a.messageStubType=43;break;case"GROUP_ANNOUNCE_MODE_MESSAGE_BOUNCE":case 44:a.messageStubType=44;break;case"CALL_MISSED_GROUP_VOICE":case 45:a.messageStubType=45;break;case"CALL_MISSED_GROUP_VIDEO":case 46:a.messageStubType=46;break;case"PAYMENT_CIPHERTEXT":case 47:a.messageStubType=47;break;case"PAYMENT_FUTUREPROOF":case 48:a.messageStubType=48;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_FAILED":case 49:a.messageStubType=49;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_REFUNDED":case 50:a.messageStubType=50;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_REFUND_FAILED":case 51:a.messageStubType=51;break;case"PAYMENT_TRANSACTION_STATUS_RECEIVER_PENDING_SETUP":case 52:a.messageStubType=52;break;case"PAYMENT_TRANSACTION_STATUS_RECEIVER_SUCCESS_AFTER_HICCUP":case 53:a.messageStubType=53;break;case"PAYMENT_ACTION_ACCOUNT_SETUP_REMINDER":case 54:a.messageStubType=54;break;case"PAYMENT_ACTION_SEND_PAYMENT_REMINDER":case 55:a.messageStubType=55;break;case"PAYMENT_ACTION_SEND_PAYMENT_INVITATION":case 56:a.messageStubType=56;break;case"PAYMENT_ACTION_REQUEST_DECLINED":case 57:a.messageStubType=57;break;case"PAYMENT_ACTION_REQUEST_EXPIRED":case 58:a.messageStubType=58;break;case"PAYMENT_ACTION_REQUEST_CANCELLED":case 59:a.messageStubType=59;break;case"BIZ_VERIFIED_TRANSITION_TOP_TO_BOTTOM":case 60:a.messageStubType=60;break;case"BIZ_VERIFIED_TRANSITION_BOTTOM_TO_TOP":case 61:a.messageStubType=61;break;case"BIZ_INTRO_TOP":case 62:a.messageStubType=62;break;case"BIZ_INTRO_BOTTOM":case 63:a.messageStubType=63;break;case"BIZ_NAME_CHANGE":case 64:a.messageStubType=64;break;case"BIZ_MOVE_TO_CONSUMER_APP":case 65:a.messageStubType=65;break;case"BIZ_TWO_TIER_MIGRATION_TOP":case 66:a.messageStubType=66;break;case"BIZ_TWO_TIER_MIGRATION_BOTTOM":case 67:a.messageStubType=67;break;case"OVERSIZED":case 68:a.messageStubType=68;break;case"GROUP_CHANGE_NO_FREQUENTLY_FORWARDED":case 69:a.messageStubType=69;break;case"GROUP_V4_ADD_INVITE_SENT":case 70:a.messageStubType=70;break;case"GROUP_PARTICIPANT_ADD_REQUEST_JOIN":case 71:a.messageStubType=71;break;case"CHANGE_EPHEMERAL_SETTING":case 72:a.messageStubType=72;break;case"E2E_DEVICE_CHANGED":case 73:a.messageStubType=73;break;case"VIEWED_ONCE":case 74:a.messageStubType=74;break;case"E2E_ENCRYPTED_NOW":case 75:a.messageStubType=75;break;case"BLUE_MSG_BSP_FB_TO_BSP_PREMISE":case 76:a.messageStubType=76;break;case"BLUE_MSG_BSP_FB_TO_SELF_FB":case 77:a.messageStubType=77;break;case"BLUE_MSG_BSP_FB_TO_SELF_PREMISE":case 78:a.messageStubType=78;break;case"BLUE_MSG_BSP_FB_UNVERIFIED":case 79:a.messageStubType=79;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 80:a.messageStubType=80;break;case"BLUE_MSG_BSP_FB_VERIFIED":case 81:a.messageStubType=81;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 82:a.messageStubType=82;break;case"BLUE_MSG_BSP_PREMISE_TO_SELF_PREMISE":case 83:a.messageStubType=83;break;case"BLUE_MSG_BSP_PREMISE_UNVERIFIED":case 84:a.messageStubType=84;break;case"BLUE_MSG_BSP_PREMISE_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 85:a.messageStubType=85;break;case"BLUE_MSG_BSP_PREMISE_VERIFIED":case 86:a.messageStubType=86;break;case"BLUE_MSG_BSP_PREMISE_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 87:a.messageStubType=87;break;case"BLUE_MSG_CONSUMER_TO_BSP_FB_UNVERIFIED":case 88:a.messageStubType=88;break;case"BLUE_MSG_CONSUMER_TO_BSP_PREMISE_UNVERIFIED":case 89:a.messageStubType=89;break;case"BLUE_MSG_CONSUMER_TO_SELF_FB_UNVERIFIED":case 90:a.messageStubType=90;break;case"BLUE_MSG_CONSUMER_TO_SELF_PREMISE_UNVERIFIED":case 91:a.messageStubType=91;break;case"BLUE_MSG_SELF_FB_TO_BSP_PREMISE":case 92:a.messageStubType=92;break;case"BLUE_MSG_SELF_FB_TO_SELF_PREMISE":case 93:a.messageStubType=93;break;case"BLUE_MSG_SELF_FB_UNVERIFIED":case 94:a.messageStubType=94;break;case"BLUE_MSG_SELF_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 95:a.messageStubType=95;break;case"BLUE_MSG_SELF_FB_VERIFIED":case 96:a.messageStubType=96;break;case"BLUE_MSG_SELF_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 97:a.messageStubType=97;break;case"BLUE_MSG_SELF_PREMISE_TO_BSP_PREMISE":case 98:a.messageStubType=98;break;case"BLUE_MSG_SELF_PREMISE_UNVERIFIED":case 99:a.messageStubType=99;break;case"BLUE_MSG_SELF_PREMISE_VERIFIED":case 100:a.messageStubType=100;break;case"BLUE_MSG_TO_BSP_FB":case 101:a.messageStubType=101;break;case"BLUE_MSG_TO_CONSUMER":case 102:a.messageStubType=102;break;case"BLUE_MSG_TO_SELF_FB":case 103:a.messageStubType=103;break;case"BLUE_MSG_UNVERIFIED_TO_BSP_FB_VERIFIED":case 104:a.messageStubType=104;break;case"BLUE_MSG_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 105:a.messageStubType=105;break;case"BLUE_MSG_UNVERIFIED_TO_SELF_FB_VERIFIED":case 106:a.messageStubType=106;break;case"BLUE_MSG_UNVERIFIED_TO_VERIFIED":case 107:a.messageStubType=107;break;case"BLUE_MSG_VERIFIED_TO_BSP_FB_UNVERIFIED":case 108:a.messageStubType=108;break;case"BLUE_MSG_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 109:a.messageStubType=109;break;case"BLUE_MSG_VERIFIED_TO_SELF_FB_UNVERIFIED":case 110:a.messageStubType=110;break;case"BLUE_MSG_VERIFIED_TO_UNVERIFIED":case 111:a.messageStubType=111;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 112:a.messageStubType=112;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_FB_VERIFIED":case 113:a.messageStubType=113;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 114:a.messageStubType=114;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_FB_UNVERIFIED":case 115:a.messageStubType=115;break;case"BLUE_MSG_SELF_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 116:a.messageStubType=116;break;case"BLUE_MSG_SELF_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 117:a.messageStubType=117;break;case"E2E_IDENTITY_UNAVAILABLE":case 118:a.messageStubType=118;break;case"GROUP_CREATING":case 119:a.messageStubType=119;break;case"GROUP_CREATE_FAILED":case 120:a.messageStubType=120;break;case"GROUP_BOUNCED":case 121:a.messageStubType=121;break;case"BLOCK_CONTACT":case 122:a.messageStubType=122;break;case"EPHEMERAL_SETTING_NOT_APPLIED":case 123:a.messageStubType=123;break;case"SYNC_FAILED":case 124:a.messageStubType=124;break;case"SYNCING":case 125:a.messageStubType=125;break;case"BIZ_PRIVACY_MODE_INIT_FB":case 126:a.messageStubType=126;break;case"BIZ_PRIVACY_MODE_INIT_BSP":case 127:a.messageStubType=127;break;case"BIZ_PRIVACY_MODE_TO_FB":case 128:a.messageStubType=128;break;case"BIZ_PRIVACY_MODE_TO_BSP":case 129:a.messageStubType=129;break;case"DISAPPEARING_MODE":case 130:a.messageStubType=130;break;case"E2E_DEVICE_FETCH_FAILED":case 131:a.messageStubType=131;break;case"ADMIN_REVOKE":case 132:a.messageStubType=132;break;case"GROUP_INVITE_LINK_GROWTH_LOCKED":case 133:a.messageStubType=133;break;case"COMMUNITY_LINK_PARENT_GROUP":case 134:a.messageStubType=134;break;case"COMMUNITY_LINK_SIBLING_GROUP":case 135:a.messageStubType=135;break;case"COMMUNITY_LINK_SUB_GROUP":case 136:a.messageStubType=136;break;case"COMMUNITY_UNLINK_PARENT_GROUP":case 137:a.messageStubType=137;break;case"COMMUNITY_UNLINK_SIBLING_GROUP":case 138:a.messageStubType=138;break;case"COMMUNITY_UNLINK_SUB_GROUP":case 139:a.messageStubType=139;break;case"GROUP_PARTICIPANT_ACCEPT":case 140:a.messageStubType=140;break;case"GROUP_PARTICIPANT_LINKED_GROUP_JOIN":case 141:a.messageStubType=141;break;case"COMMUNITY_CREATE":case 142:a.messageStubType=142;break;case"EPHEMERAL_KEEP_IN_CHAT":case 143:a.messageStubType=143;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST":case 144:a.messageStubType=144;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE":case 145:a.messageStubType=145;break;case"INTEGRITY_UNLINK_PARENT_GROUP":case 146:a.messageStubType=146;break;case"COMMUNITY_PARTICIPANT_PROMOTE":case 147:a.messageStubType=147;break;case"COMMUNITY_PARTICIPANT_DEMOTE":case 148:a.messageStubType=148;break;case"COMMUNITY_PARENT_GROUP_DELETED":case 149:a.messageStubType=149;break;case"COMMUNITY_LINK_PARENT_GROUP_MEMBERSHIP_APPROVAL":case 150:a.messageStubType=150;break;case"GROUP_PARTICIPANT_JOINED_GROUP_AND_PARENT_GROUP":case 151:a.messageStubType=151;break;case"MASKED_THREAD_CREATED":case 152:a.messageStubType=152;break;case"MASKED_THREAD_UNMASKED":case 153:a.messageStubType=153;break;case"BIZ_CHAT_ASSIGNMENT":case 154:a.messageStubType=154;break;case"CHAT_PSA":case 155:a.messageStubType=155;break;case"CHAT_POLL_CREATION_MESSAGE":case 156:a.messageStubType=156;break;case"CAG_MASKED_THREAD_CREATED":case 157:a.messageStubType=157;break;case"COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED":case 158:a.messageStubType=158;break;case"CAG_INVITE_AUTO_ADD":case 159:a.messageStubType=159;break;case"BIZ_CHAT_ASSIGNMENT_UNASSIGN":case 160:a.messageStubType=160;break;case"CAG_INVITE_AUTO_JOINED":case 161:a.messageStubType=161;break;case"SCHEDULED_CALL_START_MESSAGE":case 162:a.messageStubType=162;break;case"COMMUNITY_INVITE_RICH":case 163:a.messageStubType=163;break;case"COMMUNITY_INVITE_AUTO_ADD_RICH":case 164:a.messageStubType=164;break;case"SUB_GROUP_INVITE_RICH":case 165:a.messageStubType=165;break;case"SUB_GROUP_PARTICIPANT_ADD_RICH":case 166:a.messageStubType=166;break;case"COMMUNITY_LINK_PARENT_GROUP_RICH":case 167:a.messageStubType=167;break;case"COMMUNITY_PARTICIPANT_ADD_RICH":case 168:a.messageStubType=168;break;case"SILENCED_UNKNOWN_CALLER_AUDIO":case 169:a.messageStubType=169;break;case"SILENCED_UNKNOWN_CALLER_VIDEO":case 170:a.messageStubType=170;break;case"GROUP_MEMBER_ADD_MODE":case 171:a.messageStubType=171;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD":case 172:a.messageStubType=172;break;case"COMMUNITY_CHANGE_DESCRIPTION":case 173:a.messageStubType=173;break;case"SENDER_INVITE":case 174:a.messageStubType=174;break;case"RECEIVER_INVITE":case 175:a.messageStubType=175;break;case"COMMUNITY_ALLOW_MEMBER_ADDED_GROUPS":case 176:a.messageStubType=176;break;case"PINNED_MESSAGE_IN_CHAT":case 177:a.messageStubType=177;break;case"PAYMENT_INVITE_SETUP_INVITER":case 178:a.messageStubType=178;break;case"PAYMENT_INVITE_SETUP_INVITEE_RECEIVE_ONLY":case 179:a.messageStubType=179;break;case"PAYMENT_INVITE_SETUP_INVITEE_SEND_AND_RECEIVE":case 180:a.messageStubType=180;break;case"LINKED_GROUP_CALL_START":case 181:a.messageStubType=181;break;case"REPORT_TO_ADMIN_ENABLED_STATUS":case 182:a.messageStubType=182;break;case"EMPTY_SUBGROUP_CREATE":case 183:a.messageStubType=183;break;case"SCHEDULED_CALL_CANCEL":case 184:a.messageStubType=184;break;case"SUBGROUP_ADMIN_TRIGGERED_AUTO_ADD_RICH":case 185:a.messageStubType=185;break;case"GROUP_CHANGE_RECENT_HISTORY_SHARING":case 186:a.messageStubType=186;break;case"PAID_MESSAGE_SERVER_CAMPAIGN_ID":case 187:a.messageStubType=187;break;case"GENERAL_CHAT_CREATE":case 188:a.messageStubType=188;break;case"GENERAL_CHAT_ADD":case 189:a.messageStubType=189;break;case"GENERAL_CHAT_AUTO_ADD_DISABLED":case 190:a.messageStubType=190;break;case"SUGGESTED_SUBGROUP_ANNOUNCE":case 191:a.messageStubType=191;break;case"BIZ_BOT_1P_MESSAGING_ENABLED":case 192:a.messageStubType=192;break;case"CHANGE_USERNAME":case 193:a.messageStubType=193;break;case"BIZ_COEX_PRIVACY_INIT_SELF":case 194:a.messageStubType=194;break;case"BIZ_COEX_PRIVACY_TRANSITION_SELF":case 195:a.messageStubType=195;break;case"SUPPORT_AI_EDUCATION":case 196:a.messageStubType=196;break;case"BIZ_BOT_3P_MESSAGING_ENABLED":case 197:a.messageStubType=197;break;case"REMINDER_SETUP_MESSAGE":case 198:a.messageStubType=198;break;case"REMINDER_SENT_MESSAGE":case 199:a.messageStubType=199;break;case"REMINDER_CANCEL_MESSAGE":case 200:a.messageStubType=200;break;case"BIZ_COEX_PRIVACY_INIT":case 201:a.messageStubType=201;break;case"BIZ_COEX_PRIVACY_TRANSITION":case 202:a.messageStubType=202;break;case"GROUP_DEACTIVATED":case 203:a.messageStubType=203;break;case"COMMUNITY_DEACTIVATE_SIBLING_GROUP":case 204:a.messageStubType=204;break;case"EVENT_UPDATED":case 205:a.messageStubType=205;break;case"EVENT_CANCELED":case 206:a.messageStubType=206;break;case"COMMUNITY_OWNER_UPDATED":case 207:a.messageStubType=207;break;case"COMMUNITY_SUB_GROUP_VISIBILITY_HIDDEN":case 208:a.messageStubType=208;break;case"CAPI_GROUP_NE2EE_SYSTEM_MESSAGE":case 209:a.messageStubType=209;break;case"STATUS_MENTION":case 210:a.messageStubType=210;break;case"USER_CONTROLS_SYSTEM_MESSAGE":case 211:a.messageStubType=211;break;case"SUPPORT_SYSTEM_MESSAGE":case 212:a.messageStubType=212;break;case"CHANGE_LID":case 213:a.messageStubType=213;break;case"BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_IN_MESSAGE":case 214:a.messageStubType=214;break;case"BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_OUT_MESSAGE":case 215:a.messageStubType=215;break;case"CHANGE_LIMIT_SHARING":case 216:a.messageStubType=216;break;case"GROUP_MEMBER_LINK_MODE":case 217:a.messageStubType=217;break;case"BIZ_AUTOMATICALLY_LABELED_CHAT_SYSTEM_MESSAGE":case 218:a.messageStubType=218;break;case"PHONE_NUMBER_HIDING_CHAT_DEPRECATED_MESSAGE":case 219:a.messageStubType=219;break;case"QUARANTINED_MESSAGE":case 220:a.messageStubType=220;break;case"GROUP_MEMBER_SHARE_GROUP_HISTORY_MODE":case 221:a.messageStubType=221;break}if(e.clearMedia!=null&&(a.clearMedia=!!e.clearMedia),e.messageStubParameters){if(!Array.isArray(e.messageStubParameters))throw TypeError(".proto.WebMessageInfo.messageStubParameters: array expected");a.messageStubParameters=[];for(var A=0;A>>0),e.labels){if(!Array.isArray(e.labels))throw TypeError(".proto.WebMessageInfo.labels: array expected");a.labels=[];for(var A=0;A>>0,e.ephemeralStartTimestamp.high>>>0).toNumber(!0))),e.ephemeralDuration!=null&&(a.ephemeralDuration=e.ephemeralDuration>>>0),e.ephemeralOffToOn!=null&&(a.ephemeralOffToOn=!!e.ephemeralOffToOn),e.ephemeralOutOfSync!=null&&(a.ephemeralOutOfSync=!!e.ephemeralOutOfSync),e.bizPrivacyStatus){default:if(typeof e.bizPrivacyStatus=="number"){a.bizPrivacyStatus=e.bizPrivacyStatus;break}break;case"E2EE":case 0:a.bizPrivacyStatus=0;break;case"FB":case 2:a.bizPrivacyStatus=2;break;case"BSP":case 1:a.bizPrivacyStatus=1;break;case"BSP_AND_FB":case 3:a.bizPrivacyStatus=3;break}if(e.verifiedBizName!=null&&(a.verifiedBizName=String(e.verifiedBizName)),e.mediaData!=null){if(typeof e.mediaData!="object")throw TypeError(".proto.WebMessageInfo.mediaData: object expected");a.mediaData=E.proto.MediaData.fromObject(e.mediaData)}if(e.photoChange!=null){if(typeof e.photoChange!="object")throw TypeError(".proto.WebMessageInfo.photoChange: object expected");a.photoChange=E.proto.PhotoChange.fromObject(e.photoChange)}if(e.userReceipt){if(!Array.isArray(e.userReceipt))throw TypeError(".proto.WebMessageInfo.userReceipt: array expected");a.userReceipt=[];for(var A=0;A=0&&(a.futureproofData=e.futureproofData)),e.statusPsa!=null){if(typeof e.statusPsa!="object")throw TypeError(".proto.WebMessageInfo.statusPsa: object expected");a.statusPsa=E.proto.StatusPSA.fromObject(e.statusPsa)}if(e.pollUpdates){if(!Array.isArray(e.pollUpdates))throw TypeError(".proto.WebMessageInfo.pollUpdates: array expected");a.pollUpdates=[];for(var A=0;A=0&&(a.messageSecret=e.messageSecret)),e.keepInChat!=null){if(typeof e.keepInChat!="object")throw TypeError(".proto.WebMessageInfo.keepInChat: object expected");a.keepInChat=E.proto.KeepInChat.fromObject(e.keepInChat)}if(e.originalSelfAuthorUserJidString!=null&&(a.originalSelfAuthorUserJidString=String(e.originalSelfAuthorUserJidString)),e.revokeMessageTimestamp!=null&&(I.Long?(a.revokeMessageTimestamp=I.Long.fromValue(e.revokeMessageTimestamp)).unsigned=!0:typeof e.revokeMessageTimestamp=="string"?a.revokeMessageTimestamp=parseInt(e.revokeMessageTimestamp,10):typeof e.revokeMessageTimestamp=="number"?a.revokeMessageTimestamp=e.revokeMessageTimestamp:typeof e.revokeMessageTimestamp=="object"&&(a.revokeMessageTimestamp=new I.LongBits(e.revokeMessageTimestamp.low>>>0,e.revokeMessageTimestamp.high>>>0).toNumber(!0))),e.pinInChat!=null){if(typeof e.pinInChat!="object")throw TypeError(".proto.WebMessageInfo.pinInChat: object expected");a.pinInChat=E.proto.PinInChat.fromObject(e.pinInChat)}if(e.premiumMessageInfo!=null){if(typeof e.premiumMessageInfo!="object")throw TypeError(".proto.WebMessageInfo.premiumMessageInfo: object expected");a.premiumMessageInfo=E.proto.PremiumMessageInfo.fromObject(e.premiumMessageInfo)}if(e.is1PBizBotMessage!=null&&(a.is1PBizBotMessage=!!e.is1PBizBotMessage),e.isGroupHistoryMessage!=null&&(a.isGroupHistoryMessage=!!e.isGroupHistoryMessage),e.botMessageInvokerJid!=null&&(a.botMessageInvokerJid=String(e.botMessageInvokerJid)),e.commentMetadata!=null){if(typeof e.commentMetadata!="object")throw TypeError(".proto.WebMessageInfo.commentMetadata: object expected");a.commentMetadata=E.proto.CommentMetadata.fromObject(e.commentMetadata)}if(e.eventResponses){if(!Array.isArray(e.eventResponses))throw TypeError(".proto.WebMessageInfo.eventResponses: array expected");a.eventResponses=[];for(var A=0;A>>0,e.newsletterServerId.high>>>0).toNumber(!0))),e.eventAdditionalMetadata!=null){if(typeof e.eventAdditionalMetadata!="object")throw TypeError(".proto.WebMessageInfo.eventAdditionalMetadata: object expected");a.eventAdditionalMetadata=E.proto.EventAdditionalMetadata.fromObject(e.eventAdditionalMetadata)}if(e.isMentionedInStatus!=null&&(a.isMentionedInStatus=!!e.isMentionedInStatus),e.statusMentions){if(!Array.isArray(e.statusMentions))throw TypeError(".proto.WebMessageInfo.statusMentions: array expected");a.statusMentions=[];for(var A=0;A>>3){case 2:{s.timestamp=e.uint64();break}case 3:{s.unreadChats=e.uint32();break}case 4:{s.notifyMessageCount=e.uint32();break}case 5:{s.notifyMessages&&s.notifyMessages.length||(s.notifyMessages=[]),s.notifyMessages.push(E.proto.WebMessageInfo.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},r.fromObject=function(e){if(e instanceof E.proto.WebNotificationsInfo)return e;var a=new E.proto.WebNotificationsInfo;if(e.timestamp!=null&&(I.Long?(a.timestamp=I.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new I.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.unreadChats!=null&&(a.unreadChats=e.unreadChats>>>0),e.notifyMessageCount!=null&&(a.notifyMessageCount=e.notifyMessageCount>>>0),e.notifyMessages){if(!Array.isArray(e.notifyMessages))throw TypeError(".proto.WebNotificationsInfo.notifyMessages: array expected");a.notifyMessages=[];for(var A=0;ARr.hasSubscribers||PC.hasSubscribers,Vj=new Set,qj=typeof process=="object"&&process?process:{},Ume=(n,r,o,i)=>{typeof qj.emitWarning=="function"?qj.emitWarning(n,r,o,i):console.error(`[${o}] ${r}: ${n}`)},Hme=n=>!Vj.has(n),Ns=n=>!!n&&n===Math.floor(n)&&n>0&&isFinite(n),zj=n=>Ns(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?yf:null:null,yf=class extends Array{constructor(n){super(n),this.fill(0)}},Kme=class GC{heap;length;static#e=!1;static create(r){let o=zj(r);if(!o)return[];GC.#e=!0;let i=new GC(r,o);return GC.#e=!1,i}constructor(r,o){if(!GC.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new o(r),this.length=0}push(r){this.heap[this.length++]=r}pop(){return this.heap[--this.length]}},Mn=class Wj{#e;#A;#t;#r;#g;#n;#E;#s;get perf(){return this.#s}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#I;#a;#i;#o;#c;#l;#p;#h;#C;#d;#Q;#u;#B;#y;#f;#D;#m;#w;#N;static unsafeExposeInternals(r){return{starts:r.#B,ttls:r.#y,autopurgeTimers:r.#f,sizes:r.#u,keyMap:r.#i,keyList:r.#o,valList:r.#c,next:r.#l,prev:r.#p,get head(){return r.#h},get tail(){return r.#C},free:r.#d,isBackgroundFetch:o=>r.#_(o),backgroundFetch:(o,i,e,a)=>r.#J(o,i,e,a),moveToTail:o=>r.#j(o),indexes:o=>r.#P(o),rindexes:o=>r.#R(o),isStale:o=>r.#T(o)}}get max(){return this.#e}get maxSize(){return this.#A}get calculatedSize(){return this.#a}get size(){return this.#I}get fetchMethod(){return this.#n}get memoMethod(){return this.#E}get dispose(){return this.#t}get onInsert(){return this.#r}get disposeAfter(){return this.#g}constructor(r){let{max:o=0,ttl:i,ttlResolution:e=1,ttlAutopurge:a,updateAgeOnGet:A,updateAgeOnHas:t,allowStale:s,dispose:g,onInsert:c,disposeAfter:l,noDisposeOnSet:p,noUpdateTTL:B,maxSize:Q=0,maxEntrySize:f=0,sizeCalculation:y,fetchMethod:m,memoMethod:R,noDeleteOnFetchRejection:k,noDeleteOnStaleGet:G,allowStaleOnFetchRejection:K,allowStaleOnFetchAbort:x,ignoreFetchAbort:H,backgroundFetchSize:q=1,perf:j}=r;if(this.backgroundFetchSize=q,j!==void 0&&typeof j?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#s=j??Lme,o!==0&&!Ns(o))throw new TypeError("max option must be a nonnegative integer");let F=o?zj(o):Array;if(!F)throw new Error("invalid max value: "+o);if(this.#e=o,this.#A=Q,this.maxEntrySize=f||this.#A,this.sizeCalculation=y,this.sizeCalculation){if(!this.#A&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(R!==void 0&&typeof R!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#E=R,m!==void 0&&typeof m!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#n=m,this.#m=!!m,this.#i=new Map,this.#o=Array.from({length:o}).fill(void 0),this.#c=Array.from({length:o}).fill(void 0),this.#l=new F(o),this.#p=new F(o),this.#h=0,this.#C=0,this.#d=Kme.create(o),this.#I=0,this.#a=0,typeof g=="function"&&(this.#t=g),typeof c=="function"&&(this.#r=c),typeof l=="function"?(this.#g=l,this.#Q=[]):(this.#g=void 0,this.#Q=void 0),this.#D=!!this.#t,this.#N=!!this.#r,this.#w=!!this.#g,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!B,this.noDeleteOnFetchRejection=!!k,this.allowStaleOnFetchRejection=!!K,this.allowStaleOnFetchAbort=!!x,this.ignoreFetchAbort=!!H,this.maxEntrySize!==0){if(this.#A!==0&&!Ns(this.#A))throw new TypeError("maxSize must be a positive integer if specified");if(!Ns(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!s,this.noDeleteOnStaleGet=!!G,this.updateAgeOnGet=!!A,this.updateAgeOnHas=!!t,this.ttlResolution=Ns(e)||e===0?e:1,this.ttlAutopurge=!!a,this.ttl=i||0,this.ttl){if(!Ns(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#S()}if(this.#e===0&&this.ttl===0&&this.#A===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#A){let T="LRU_CACHE_UNBOUNDED";Hme(T)&&(Vj.add(T),Ume("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",T,Wj))}}getRemainingTTL(r){return this.#i.has(r)?1/0:0}#S(){let r=new yf(this.#e),o=new yf(this.#e);this.#y=r,this.#B=o;let i=this.ttlAutopurge?Array.from({length:this.#e}):void 0;this.#f=i,this.#F=(s,g,c=this.#s.now())=>{o[s]=g!==0?c:0,r[s]=g,e(s,g)},this.#O=s=>{o[s]=r[s]!==0?this.#s.now():0,e(s,r[s])};let e=this.ttlAutopurge?(s,g)=>{if(i?.[s]&&(clearTimeout(i[s]),i[s]=void 0),g&&g!==0&&i){let c=setTimeout(()=>{this.#T(s)?(this.#U(this.#o[s],"expire"),i[s]=void 0):e(s,t(s))},g+1);c.unref&&c.unref(),i[s]=c}}:()=>{};this.#M=(s,g)=>{if(r[g]){let c=r[g],l=o[g];if(!c||!l)return;s.ttl=c,s.start=l,s.now=a||A();let p=s.now-l;s.remainingTTL=c-p}};let a=0,A=()=>{let s=this.#s.now();if(this.ttlResolution>0){a=s;let g=setTimeout(()=>a=0,this.ttlResolution);g.unref&&g.unref()}return s};this.getRemainingTTL=s=>{let g=this.#i.get(s);return g===void 0?0:t(g)};let t=s=>{let g=r[s],c=o[s];if(!g||!c)return 1/0;let l=(a||A())-c;return g-l};this.#T=s=>{let g=o[s],c=r[s];return!!c&&!!g&&(a||A())-g>c}}#O=()=>{};#M=()=>{};#F=()=>{};#T=()=>!1;#L(){let r=new yf(this.#e);this.#a=0,this.#u=r,this.#k=o=>{this.#a-=r[o],r[o]=0},this.#b=(o,i,e,a)=>{if(!Ns(e)){if(this.#_(i))return this.backgroundFetchSize;if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(e=a(i,o),!Ns(e))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return e},this.#v=(o,i,e)=>{if(r[o]=i,this.#A){let a=this.#A-r[o];for(;this.#a>a;)this.#H(!0)}this.#a+=r[o],e&&(e.entrySize=i,e.totalCalculatedSize=this.#a)}}#k=r=>{};#v=(r,o,i)=>{};#b=(r,o,i,e)=>{if(i||e)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#P({allowStale:r=this.allowStale}={}){if(this.#I)for(let o=this.#C;this.#K(o)&&((r||!this.#T(o))&&(yield o),o!==this.#h);)o=this.#p[o]}*#R({allowStale:r=this.allowStale}={}){if(this.#I)for(let o=this.#h;this.#K(o)&&((r||!this.#T(o))&&(yield o),o!==this.#C);)o=this.#l[o]}#K(r){return r!==void 0&&this.#i.get(this.#o[r])===r}*entries(){for(let r of this.#P())this.#c[r]!==void 0&&this.#o[r]!==void 0&&!this.#_(this.#c[r])&&(yield[this.#o[r],this.#c[r]])}*rentries(){for(let r of this.#R())this.#c[r]!==void 0&&this.#o[r]!==void 0&&!this.#_(this.#c[r])&&(yield[this.#o[r],this.#c[r]])}*keys(){for(let r of this.#P()){let o=this.#o[r];o!==void 0&&!this.#_(this.#c[r])&&(yield o)}}*rkeys(){for(let r of this.#R()){let o=this.#o[r];o!==void 0&&!this.#_(this.#c[r])&&(yield o)}}*values(){for(let r of this.#P())this.#c[r]!==void 0&&!this.#_(this.#c[r])&&(yield this.#c[r])}*rvalues(){for(let r of this.#R())this.#c[r]!==void 0&&!this.#_(this.#c[r])&&(yield this.#c[r])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(r,o={}){for(let i of this.#P()){let e=this.#c[i],a=this.#_(e)?e.__staleWhileFetching:e;if(a!==void 0&&r(a,this.#o[i],this))return this.#x(this.#o[i],o)}}forEach(r,o=this){for(let i of this.#P()){let e=this.#c[i],a=this.#_(e)?e.__staleWhileFetching:e;a!==void 0&&r.call(o,a,this.#o[i],this)}}rforEach(r,o=this){for(let i of this.#R()){let e=this.#c[i],a=this.#_(e)?e.__staleWhileFetching:e;a!==void 0&&r.call(o,a,this.#o[i],this)}}purgeStale(){let r=!1;for(let o of this.#R({allowStale:!0}))this.#T(o)&&(this.#U(this.#o[o],"expire"),r=!0);return r}info(r){let o=this.#i.get(r);if(o===void 0)return;let i=this.#c[o],e=this.#_(i)?i.__staleWhileFetching:i;if(e===void 0)return;let a={value:e};if(this.#y&&this.#B){let A=this.#y[o],t=this.#B[o];if(A&&t){let s=A-(this.#s.now()-t);a.ttl=s,a.start=Date.now()}}return this.#u&&(a.size=this.#u[o]),a}dump(){let r=[];for(let o of this.#P({allowStale:!0})){let i=this.#o[o],e=this.#c[o],a=this.#_(e)?e.__staleWhileFetching:e;if(a===void 0||i===void 0)continue;let A={value:a};if(this.#y&&this.#B){A.ttl=this.#y[o];let t=this.#s.now()-this.#B[o];A.start=Math.floor(Date.now()-t)}this.#u&&(A.size=this.#u[o]),r.unshift([i,A])}return r}load(r){this.clear();for(let[o,i]of r){if(i.start){let e=Date.now()-i.start;i.start=this.#s.now()-e}this.#G(o,i.value,i)}}set(r,o,i={}){let{status:e=Rr.hasSubscribers?{}:void 0}=i;i.status=e,e&&(e.op="set",e.key=r,o!==void 0&&(e.value=o),e.cache=this);let a=this.#G(r,o,i);return e&&Rr.hasSubscribers&&Rr.publish(e),a}#G(r,o,i,e){let{ttl:a=this.ttl,start:A,noDisposeOnSet:t=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:g}=i,c=this.#_(o);if(o===void 0)return g&&(g.set="deleted"),this.delete(r),this;let{noUpdateTTL:l=this.noUpdateTTL}=i;g&&!c&&(g.value=o);let p=this.#b(r,o,i.size||0,s,g);if(this.maxEntrySize&&p>this.maxEntrySize)return this.#U(r,"set"),g&&(g.set="miss",g.maxEntrySizeExceeded=!0),this;let B=this.#I===0?void 0:this.#i.get(r);if(B===void 0)B=this.#I===0?this.#C:this.#d.length!==0?this.#d.pop():this.#I===this.#e?this.#H(!1):this.#I,this.#o[B]=r,this.#c[B]=o,this.#i.set(r,B),this.#l[this.#C]=B,this.#p[B]=this.#C,this.#C=B,this.#I++,this.#v(B,p,g),g&&(g.set="add"),l=!1,this.#N&&!c&&this.#r?.(o,r,"add");else{this.#j(B);let Q=this.#c[B];if(o!==Q){if(!t)if(this.#_(Q)){Q!==e&&Q.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=Q;f!==void 0&&f!==o&&(this.#D&&this.#t?.(f,r,"set"),this.#w&&this.#Q?.push([f,r,"set"]))}else this.#D&&this.#t?.(Q,r,"set"),this.#w&&this.#Q?.push([Q,r,"set"]);if(this.#k(B),this.#v(B,p,g),this.#c[B]=o,!c){let f=Q&&this.#_(Q)?Q.__staleWhileFetching:Q,y=f===void 0?"add":o!==f?"replace":"update";g&&(g.set=y,f!==void 0&&(g.oldValue=f)),this.#N&&this.onInsert?.(o,r,y)}}else c||(g&&(g.set="update"),this.#N&&this.onInsert?.(o,r,"update"))}if(a!==0&&!this.#y&&this.#S(),this.#y&&(l||this.#F(B,a,A),g&&this.#M(g,B)),!t&&this.#w&&this.#Q){let Q=this.#Q,f;for(;f=Q?.shift();)this.#g?.(...f)}return this}pop(){try{for(;this.#I;){let r=this.#c[this.#h];if(this.#H(!0),this.#_(r)){if(r.__staleWhileFetching)return r.__staleWhileFetching}else if(r!==void 0)return r}}finally{if(this.#w&&this.#Q){let r=this.#Q,o;for(;o=r?.shift();)this.#g?.(...o)}}}#H(r){let o=this.#h,i=this.#o[o],e=this.#c[o],a=this.#_(e);a&&e.__abortController.abort(new Error("evicted"));let A=a?e.__staleWhileFetching:e;return(this.#D||this.#w)&&A!==void 0&&(this.#D&&this.#t?.(A,i,"evict"),this.#w&&this.#Q?.push([A,i,"evict"])),this.#k(o),this.#f?.[o]&&(clearTimeout(this.#f[o]),this.#f[o]=void 0),r&&(this.#o[o]=void 0,this.#c[o]=void 0,this.#d.push(o)),this.#I===1?(this.#h=this.#C=0,this.#d.length=0):this.#h=this.#l[o],this.#i.delete(i),this.#I--,o}has(r,o={}){let{status:i=Rr.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="has",i.key=r,i.cache=this);let e=this.#Y(r,o);return Rr.hasSubscribers&&Rr.publish(i),e}#Y(r,o={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:e}=o,a=this.#i.get(r);if(a!==void 0){let A=this.#c[a];if(this.#_(A)&&A.__staleWhileFetching===void 0)return!1;if(this.#T(a))e&&(e.has="stale",this.#M(e,a));else return i&&this.#O(a),e&&(e.has="hit",this.#M(e,a)),!0}else e&&(e.has="miss");return!1}peek(r,o={}){let{status:i=J0()?{}:void 0}=o;i&&(i.op="peek",i.key=r,i.cache=this),o.status=i;let e=this.#W(r,o);return Rr.hasSubscribers&&Rr.publish(i),e}#W(r,o){let{status:i,allowStale:e=this.allowStale}=o,a=this.#i.get(r);if(a===void 0||!e&&this.#T(a)){i&&(i.peek=a===void 0?"miss":"stale");return}let A=this.#c[a],t=this.#_(A)?A.__staleWhileFetching:A;return i&&(t!==void 0?(i.peek="hit",i.value=t):i.peek="miss"),t}#J(r,o,i,e){let a=o===void 0?void 0:this.#c[o];if(this.#_(a))return a;let A=new AbortController,{signal:t}=i;t?.addEventListener("abort",()=>A.abort(t.reason),{signal:A.signal});let s={signal:A.signal,options:i,context:e},g=(f,y=!1)=>{let{aborted:m}=A.signal,R=i.ignoreFetchAbort&&f!==void 0,k=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(m&&!y?(i.status.fetchAborted=!0,i.status.fetchError=A.signal.reason,R&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),m&&!R&&!y)return l(A.signal.reason,k);let G=B,K=this.#c[o];return(K===B||K===void 0&&R&&y)&&(f===void 0?G.__staleWhileFetching!==void 0?this.#c[o]=G.__staleWhileFetching:this.#U(r,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#G(r,f,s.options,G))),f},c=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),l(f,!1)),l=(f,y)=>{let{aborted:m}=A.signal,R=m&&i.allowStaleOnFetchAbort,k=R||i.allowStaleOnFetchRejection,G=k||i.noDeleteOnFetchRejection,K=B;if(this.#c[o]===B&&(!G||!y&&K.__staleWhileFetching===void 0?this.#U(r,"fetch"):R||(this.#c[o]=K.__staleWhileFetching)),k)return i.status&&K.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),K.__staleWhileFetching;if(K.__returned===K)throw f},p=(f,y)=>{let m=this.#n?.(r,a,s);A.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=R=>g(R,!0)))}),m&&m instanceof Promise?m.then(R=>f(R===void 0?void 0:R),y):m!==void 0&&f(m)};i.status&&(i.status.fetchDispatched=!0);let B=new Promise(p).then(g,c),Q=Object.assign(B,{__abortController:A,__staleWhileFetching:a,__returned:void 0});return o===void 0?(this.#G(r,Q,{...s.options,status:void 0}),o=this.#i.get(r)):this.#c[o]=Q,Q}#_(r){if(!this.#m)return!1;let o=r;return!!o&&o instanceof Promise&&o.hasOwnProperty("__staleWhileFetching")&&o.__abortController instanceof AbortController}fetch(r,o={}){let i=PC.hasSubscribers,{status:e=J0()?{}:void 0}=o;o.status=e,e&&o.context&&(e.context=o.context);let a=this.#q(r,o);return e&&i&&(e.trace=!0,PC.tracePromise(()=>a,e).catch(()=>{})),a}async#q(r,o={}){let{allowStale:i=this.allowStale,updateAgeOnGet:e=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:A=this.ttl,noDisposeOnSet:t=this.noDisposeOnSet,size:s=0,sizeCalculation:g=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:B=this.ignoreFetchAbort,allowStaleOnFetchAbort:Q=this.allowStaleOnFetchAbort,context:f,forceRefresh:y=!1,status:m,signal:R}=o;if(m&&(m.op="fetch",m.key=r,y&&(m.forceRefresh=!0),m.cache=this),!this.#m)return m&&(m.fetch="get"),this.#x(r,{allowStale:i,updateAgeOnGet:e,noDeleteOnStaleGet:a,status:m});let k={allowStale:i,updateAgeOnGet:e,noDeleteOnStaleGet:a,ttl:A,noDisposeOnSet:t,size:s,sizeCalculation:g,noUpdateTTL:c,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:Q,ignoreFetchAbort:B,status:m,signal:R},G=this.#i.get(r);if(G===void 0){m&&(m.fetch="miss");let K=this.#J(r,G,k,f);return K.__returned=K}else{let K=this.#c[G];if(this.#_(K)){let j=i&&K.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",j&&(m.returnedStale=!0)),j?K.__staleWhileFetching:K.__returned=K}let x=this.#T(G);if(!y&&!x)return m&&(m.fetch="hit"),this.#j(G),e&&this.#O(G),m&&this.#M(m,G),K;let H=this.#J(r,G,k,f),q=H.__staleWhileFetching!==void 0&&i;return m&&(m.fetch=x?"stale":"refresh",q&&x&&(m.returnedStale=!0)),q?H.__staleWhileFetching:H.__returned=H}}forceFetch(r,o={}){let i=PC.hasSubscribers,{status:e=J0()?{}:void 0}=o;o.status=e,e&&o.context&&(e.context=o.context);let a=this.#Z(r,o);return e&&i&&(e.trace=!0,PC.tracePromise(()=>a,e).catch(()=>{})),a}async#Z(r,o={}){let i=await this.#q(r,o);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(r,o={}){let{status:i=Rr.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="memo",i.key=r,o.context&&(i.context=o.context),i.cache=this);let e=this.#X(r,o);return i&&(i.value=e),Rr.hasSubscribers&&Rr.publish(i),e}#X(r,o={}){let i=this.#E;if(!i)throw new Error("no memoMethod provided to constructor");let{context:e,status:a,forceRefresh:A,...t}=o;a&&A&&(a.forceRefresh=!0);let s=this.#x(r,t),g=A||s===void 0;if(a&&(a.memo=g?"miss":"hit",g||(a.value=s)),!g)return s;let c=i(r,s,{options:t,context:e});return a&&(a.value=c),this.#G(r,c,t),c}get(r,o={}){let{status:i=Rr.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="get",i.key=r,i.cache=this);let e=this.#x(r,o);return i&&(e!==void 0&&(i.value=e),Rr.hasSubscribers&&Rr.publish(i)),e}#x(r,o={}){let{allowStale:i=this.allowStale,updateAgeOnGet:e=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:A}=o,t=this.#i.get(r);if(t===void 0){A&&(A.get="miss");return}let s=this.#c[t],g=this.#_(s);return A&&this.#M(A,t),this.#T(t)?g?(A&&(A.get="stale-fetching"),i&&s.__staleWhileFetching!==void 0?(A&&(A.returnedStale=!0),s.__staleWhileFetching):void 0):(a||this.#U(r,"expire"),A&&(A.get="stale"),i?(A&&(A.returnedStale=!0),s):void 0):(A&&(A.get=g?"fetching":"hit"),this.#j(t),e&&this.#O(t),g?s.__staleWhileFetching:s)}#V(r,o){this.#p[o]=r,this.#l[r]=o}#j(r){r!==this.#C&&(r===this.#h?this.#h=this.#l[r]:this.#V(this.#p[r],this.#l[r]),this.#V(this.#C,r),this.#C=r)}delete(r){return this.#U(r,"delete")}#U(r,o){Rr.hasSubscribers&&Rr.publish({op:"delete",delete:o,key:r,cache:this});let i=!1;if(this.#I!==0){let e=this.#i.get(r);if(e!==void 0)if(this.#f?.[e]&&(clearTimeout(this.#f[e]),this.#f[e]=void 0),i=!0,this.#I===1)this.#z(o);else{this.#k(e);let a=this.#c[e];if(this.#_(a)?a.__abortController.abort(new Error("deleted")):(this.#D||this.#w)&&(this.#D&&this.#t?.(a,r,o),this.#w&&this.#Q?.push([a,r,o])),this.#i.delete(r),this.#o[e]=void 0,this.#c[e]=void 0,e===this.#C)this.#C=this.#p[e];else if(e===this.#h)this.#h=this.#l[e];else{let A=this.#p[e];this.#l[A]=this.#l[e];let t=this.#l[e];this.#p[t]=this.#p[e]}this.#I--,this.#d.push(e)}}if(this.#w&&this.#Q?.length){let e=this.#Q,a;for(;a=e?.shift();)this.#g?.(...a)}return i}clear(){return this.#z("delete")}#z(r){for(let o of this.#R({allowStale:!0})){let i=this.#c[o];if(this.#_(i))i.__abortController.abort(new Error("deleted"));else{let e=this.#o[o];this.#D&&this.#t?.(i,e,r),this.#w&&this.#Q?.push([i,e,r])}}if(this.#i.clear(),this.#c.fill(void 0),this.#o.fill(void 0),this.#y&&this.#B){this.#y.fill(0),this.#B.fill(0);for(let o of this.#f??[])o!==void 0&&clearTimeout(o);this.#f?.fill(void 0)}if(this.#u&&this.#u.fill(0),this.#h=0,this.#C=0,this.#d.length=0,this.#a=0,this.#I=0,this.#w&&this.#Q){let o=this.#Q,i;for(;i=o?.shift();)this.#g?.(...i)}}};var Uf=Le(ar(),1);import{createHash as wSe,randomBytes as zC}from"crypto";var JJ=["critical_block","critical_unblock_low","regular_high","regular_low","regular"];var Y6e=Le(ar(),1),Qr;(function(n){n[n.Connecting=0]="Connecting",n[n.AwaitingInitialSync=1]="AwaitingInitialSync",n[n.Syncing=2]="Syncing",n[n.Online=3]="Online"})(Qr||(Qr={}));var Rs;(function(n){n.BIZ_COMMERCE_VIOLATION_ALCOHOL="BIZ_COMMERCE_VIOLATION_ALCOHOL",n.BIZ_COMMERCE_VIOLATION_ADULT="BIZ_COMMERCE_VIOLATION_ADULT",n.BIZ_COMMERCE_VIOLATION_ANIMALS="BIZ_COMMERCE_VIOLATION_ANIMALS",n.BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS="BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS",n.BIZ_COMMERCE_VIOLATION_DATING="BIZ_COMMERCE_VIOLATION_DATING",n.BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS="BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS",n.BIZ_COMMERCE_VIOLATION_DRUGS="BIZ_COMMERCE_VIOLATION_DRUGS",n.BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC="BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC",n.BIZ_COMMERCE_VIOLATION_GAMBLING="BIZ_COMMERCE_VIOLATION_GAMBLING",n.BIZ_COMMERCE_VIOLATION_HEALTHCARE="BIZ_COMMERCE_VIOLATION_HEALTHCARE",n.BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY="BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY",n.BIZ_COMMERCE_VIOLATION_SUPPLEMENTS="BIZ_COMMERCE_VIOLATION_SUPPLEMENTS",n.BIZ_COMMERCE_VIOLATION_TOBACCO="BIZ_COMMERCE_VIOLATION_TOBACCO",n.BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT="BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT",n.BIZ_COMMERCE_VIOLATION_WEAPONS="BIZ_COMMERCE_VIOLATION_WEAPONS",n.BIZ_QUALITY="BIZ_QUALITY",n.DEFAULT="DEFAULT",n.WEB_COMPANION_ONLY="WEB_COMPANION_ONLY"})(Rs||(Rs={}));var qJ;(function(n){n.NONE="NONE",n.FIRST_WARNING="FIRST_WARNING",n.SECOND_WARNING="SECOND_WARNING",n.CAPPED="CAPPED"})(qJ||(qJ={}));var VJ;(function(n){n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.NOT_ACTIVE="NOT_ACTIVE",n.ACTIVE="ACTIVE",n.ACTIVE_UPGRADE_AVAILABLE="ACTIVE_UPGRADE_AVAILABLE"})(VJ||(VJ={}));var zJ;(function(n){n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.ELIGIBLE="ELIGIBLE",n.ACTIVE_IN_CURRENT_CYCLE="ACTIVE_IN_CURRENT_CYCLE",n.EXHAUSTED="EXHAUSTED"})(zJ||(zJ={}));var QA=Ae.WebMessageInfo.StubType,sl=Ae.WebMessageInfo.Status,LC;(function(n){n.PN="pn",n.LID="lid"})(LC||(LC={}));var kr;(function(n){n.xwa2_newsletter_create="xwa2_newsletter_create",n.xwa2_newsletter_subscribers="xwa2_newsletter_subscribers",n.xwa2_newsletter_view="xwa2_newsletter_view",n.xwa2_newsletter_metadata="xwa2_newsletter",n.xwa2_newsletter_admin_count="xwa2_newsletter_admin",n.xwa2_newsletter_mute_v2="xwa2_newsletter_mute_v2",n.xwa2_newsletter_unmute_v2="xwa2_newsletter_unmute_v2",n.xwa2_newsletter_follow="xwa2_newsletter_follow",n.xwa2_newsletter_unfollow="xwa2_newsletter_unfollow",n.xwa2_newsletter_join_v2="xwa2_newsletter_join_v2",n.xwa2_newsletter_leave_v2="xwa2_newsletter_leave_v2",n.xwa2_newsletter_change_owner="xwa2_newsletter_change_owner",n.xwa2_newsletter_demote="xwa2_newsletter_demote",n.xwa2_newsletter_delete_v2="xwa2_newsletter_delete_v2",n.xwa2_fetch_account_reachout_timelock="xwa2_fetch_account_reachout_timelock",n.xwa2_message_capping_info="xwa2_message_capping_info"})(kr||(kr={}));var fr;(function(n){n.CREATE="8823471724422422",n.UPDATE_METADATA="24250201037901610",n.METADATA="6563316087068696",n.SUBSCRIBERS="9783111038412085",n.FOLLOW="24404358912487870",n.UNFOLLOW="9767147403369991",n.MUTE="29766401636284406",n.UNMUTE="9864994326891137",n.ADMIN_COUNT="7130823597031706",n.CHANGE_OWNER="7341777602580933",n.DEMOTE="6551828931592903",n.DELETE="30062808666639665",n.REACHOUT_TIMELOCK="23983697327930364",n.MESSAGE_CAPPING_INFO="24503548349331633"})(fr||(fr={}));var yt;(function(n){n[n.connectionClosed=428]="connectionClosed",n[n.connectionLost=408]="connectionLost",n[n.connectionReplaced=440]="connectionReplaced",n[n.timedOut=408]="timedOut",n[n.loggedOut=401]="loggedOut",n[n.badSession=500]="badSession",n[n.restartRequired=515]="restartRequired",n[n.multideviceMismatch=411]="multideviceMismatch",n[n.forbidden=403]="forbidden",n[n.unavailableService=503]="unavailableService"})(yt||(yt={}));var UC={};er(UC,{DOUBLE_BYTE_TOKENS:()=>WJ,SINGLE_BYTE_TOKENS:()=>ZJ,TAGS:()=>ASe,TOKEN_MAP:()=>rT});var ASe={LIST_EMPTY:0,DICTIONARY_0:236,DICTIONARY_1:237,DICTIONARY_2:238,DICTIONARY_3:239,INTEROP_JID:245,FB_JID:246,AD_JID:247,LIST_8:248,LIST_16:249,JID_PAIR:250,HEX_8:251,BINARY_8:252,BINARY_20:253,BINARY_32:254,NIBBLE_8:255,PACKED_MAX:127},WJ=[["read-self","active","fbns","protocol","reaction","screen_width","heartbeat","deviceid","2:47DEQpj8","uploadfieldstat","voip_settings","retry","priority","longitude","conflict","false","ig_professional","replaced","preaccept","cover_photo","uncompressed","encopt","ppic","04","passive","status-revoke-drop","keygen","540","offer","rate","opus","latitude","w:gp2","ver","4","business_profile","medium","sender","prev_v_id","email","website","invited","sign_credential","05","transport","skey","reason","peer_abtest_bucket","America/Sao_Paulo","appid","refresh","100","06","404","101","104","107","102","109","103","member_add_mode","105","transaction-id","110","106","outgoing","108","111","tokens","followers","ig_handle","self_pid","tue","dec","thu","joinable","peer_pid","mon","features","wed","peer_device_presence","pn","delete","07","fri","audio_duration","admin","connected","delta","rcat","disable","collection","08","480","sat","phash","all","invite","accept","critical_unblock_low","group_update","signed_credential","blinded_credential","eph_setting","net","09","background_location","refresh_id","Asia/Kolkata","privacy_mode_ts","account_sync","voip_payload_type","service_areas","acs_public_key","v_id","0a","fallback_class","relay","actual_actors","metadata","w:biz","5","connected-limit","notice","0b","host_storage","fb_page","subject","privatestats","invis","groupadd","010","note.m4r","uuid","0c","8000","sun","372","1020","stage","1200","720","canonical","fb","011","video_duration","0d","1140","superadmin","012","Opening.m4r","keystore_attestation","dleq_proof","013","timestamp","ab_key","w:sync:app:state","0e","vertical","600","p_v_id","6","likes","014","500","1260","creator","0f","rte","destination","group","group_info","syncd_anti_tampering_fatal_exception_enabled","015","dl_bw","Asia/Jakarta","vp8/h.264","online","1320","fb:multiway","10","timeout","016","nse_retry","urn:xmpp:whatsapp:dirty","017","a_v_id","web_shops_chat_header_button_enabled","nse_call","inactive-upgrade","none","web","groups","2250","mms_hot_content_timespan_in_seconds","contact_blacklist","nse_read","suspended_group_deletion_notification","binary_version","018","https://www.whatsapp.com/otp/copy/","reg_push","shops_hide_catalog_attachment_entrypoint","server_sync",".","ephemeral_messages_allowed_values","019","mms_vcache_aggregation_enabled","iphone","America/Argentina/Buenos_Aires","01a","mms_vcard_autodownload_size_kb","nse_ver","shops_header_dropdown_menu_item","dhash","catalog_status","communities_mvp_new_iqs_serverprop","blocklist","default","11","ephemeral_messages_enabled","01b","original_dimensions","8","mms4_media_retry_notification_encryption_enabled","mms4_server_error_receipt_encryption_enabled","original_image_url","sync","multiway","420","companion_enc_static","shops_profile_drawer_entrypoint","01c","vcard_as_document_size_kb","status_video_max_duration","request_image_url","01d","regular_high","s_t","abt","share_ext_min_preliminary_image_quality","01e","32","syncd_key_rotation_enabled","data_namespace","md_downgrade_read_receipts2","patch","polltype","ephemeral_messages_setting","userrate","15","partial_pjpeg_bw_threshold","played-self","catalog_exists","01f","mute_v2"],["reject","dirty","announcement","020","13","9","status_video_max_bitrate","fb:thrift_iq","offline_batch","022","full","ctwa_first_business_reply_logging","h.264","smax_id","group_description_length","https://www.whatsapp.com/otp/code","status_image_max_edge","smb_upsell_business_profile_enabled","021","web_upgrade_to_md_modal","14","023","s_o","smaller_video_thumbs_status_enabled","media_max_autodownload","960","blocking_status","peer_msg","joinable_group_call_client_version","group_call_video_maximization_enabled","return_snapshot","high","America/Mexico_City","entry_point_block_logging_enabled","pop","024","1050","16","1380","one_tap_calling_in_group_chat_size","regular_low","inline_joinable_education_enabled","hq_image_max_edge","locked","America/Bogota","smb_biztools_deeplink_enabled","status_image_quality","1088","025","payments_upi_intent_transaction_limit","voip","w:g2","027","md_pin_chat_enabled","026","multi_scan_pjpeg_download_enabled","shops_product_grid","transaction_id","ctwa_context_enabled","20","fna","hq_image_quality","alt_jpeg_doc_detection_quality","group_call_max_participants","pkey","America/Belem","image_max_kbytes","web_cart_v1_1_order_message_changes_enabled","ctwa_context_enterprise_enabled","urn:xmpp:whatsapp:account","840","Asia/Kuala_Lumpur","max_participants","video_remux_after_repair_enabled","stella_addressbook_restriction_type","660","900","780","context_menu_ios13_enabled","mute-state","ref","payments_request_messages","029","frskmsg","vcard_max_size_kb","sample_buffer_gif_player_enabled","match_last_seen","510","4983","video_max_bitrate","028","w:comms:chat","17","frequently_forwarded_max","groups_privacy_blacklist","Asia/Karachi","02a","web_download_document_thumb_mms_enabled","02b","hist_sync","biz_block_reasons_version","1024","18","web_is_direct_connection_for_plm_transparent","view_once_write","file_max_size","paid_convo_id","online_privacy_setting","video_max_edge","view_once_read","enhanced_storage_management","multi_scan_pjpeg_encoding_enabled","ctwa_context_forward_enabled","video_transcode_downgrade_enable","template_doc_mime_types","hq_image_bw_threshold","30","body","u_aud_limit_sil_restarts_ctrl","other","participating","w:biz:directory","1110","vp8","4018","meta","doc_detection_image_max_edge","image_quality","1170","02c","smb_upsell_chat_banner_enabled","key_expiry_time_second","pid","stella_interop_enabled","19","linked_device_max_count","md_device_sync_enabled","02d","02e","360","enhanced_block_enabled","ephemeral_icon_in_forwarding","paid_convo_status","gif_provider","project_name","server-error","canonical_url_validation_enabled","wallpapers_v2","syncd_clear_chat_delete_chat_enabled","medianotify","02f","shops_required_tos_version","vote","reset_skey_on_id_change","030","image_max_edge","multicast_limit_global","ul_bw","21","25","5000","poll","570","22","031","1280","WhatsApp","032","bloks_shops_enabled","50","upload_host_switching_enabled","web_ctwa_context_compose_enabled","ptt_forwarded_features_enabled","unblocked","partial_pjpeg_enabled","fbid:devices","height","ephemeral_group_query_ts","group_join_permissions","order","033","alt_jpeg_status_quality","migrate","popular-bank","win_uwp_deprecation_killswitch_enabled","web_download_status_thumb_mms_enabled","blocking","url_text","035","web_forwarding_limit_to_groups","1600","val","1000","syncd_msg_date_enabled","bank-ref-id","max_subject","payments_web_enabled","web_upload_document_thumb_mms_enabled","size","request","ephemeral","24","receipt_agg","ptt_remember_play_position","sampling_weight","enc_rekey","mute_always","037","034","23","036","action","click_to_chat_qr_enabled","width","disabled","038","md_blocklist_v2","played_self_enabled","web_buttons_message_enabled","flow_id","clear","450","fbid:thread","bloks_session_state","America/Lima","attachment_picker_refresh","download_host_switching_enabled","1792","u_aud_limit_sil_restarts_test2","custom_urls","device_fanout","optimistic_upload","2000","key_cipher_suite","web_smb_upsell_in_biz_profile_enabled","e","039","siri_post_status_shortcut","pair-device","lg","lc","stream_attribution_url","model","mspjpeg_phash_gen","catalog_send_all","new_multi_vcards_ui","share_biz_vcard_enabled","-","clean","200","md_blocklist_v2_server","03b","03a","web_md_migration_experience","ptt_conversation_waveform","u_aud_limit_sil_restarts_test1"],["64","ptt_playback_speed_enabled","web_product_list_message_enabled","paid_convo_ts","27","manufacturer","psp-routing","grp_uii_cleanup","ptt_draft_enabled","03c","business_initiated","web_catalog_products_onoff","web_upload_link_thumb_mms_enabled","03e","mediaretry","35","hfm_string_changes","28","America/Fortaleza","max_keys","md_mhfs_days","streaming_upload_chunk_size","5541","040","03d","2675","03f","...","512","mute","48","041","alt_jpeg_quality","60","042","md_smb_quick_reply","5183","c","1343","40","1230","043","044","mms_cat_v1_forward_hot_override_enabled","user_notice","ptt_waveform_send","047","Asia/Calcutta","250","md_privacy_v2","31","29","128","md_messaging_enabled","046","crypto","690","045","enc_iv","75","failure","ptt_oot_playback","AIzaSyDR5yfaG7OG8sMTUj8kfQEb8T9pN8BM6Lk","w","048","2201","web_large_files_ui","Asia/Makassar","812","status_collapse_muted","1334","257","2HP4dm","049","patches","1290","43cY6T","America/Caracas","web_sticker_maker","campaign","ptt_pausable_enabled","33","42","attestation","biz","04b","query_linked","s","125","04a","810","availability","1411","responsiveness_v2_m1","catalog_not_created","34","America/Santiago","1465","enc_p","04d","status_info","04f","key_version","..","04c","04e","md_group_notification","1598","1215","web_cart_enabled","37","630","1920","2394","-1","vcard","38","elapsed","36","828","peer","pricing_category","1245","invalid","stella_ios_enabled","2687","45","1528","39","u_is_redial_audio_1104_ctrl","1025","1455","58","2524","2603","054","bsp_system_message_enabled","web_pip_redesign","051","verify_apps","1974","1272","1322","1755","052","70","050","1063","1135","1361","80","1096","1828","1851","1251","1921","key_config_id","1254","1566","1252","2525","critical_block","1669","max_available","w:auth:backup:token","product","2530","870","1022","participant_uuid","web_cart_on_off","1255","1432","1867","41","1415","1440","240","1204","1608","1690","1846","1483","1687","1749","69","url_number","053","1325","1040","365","59","Asia/Riyadh","1177","test_recommended","057","1612","43","1061","1518","1635","055","1034","1375","750","1430","event_code","1682","503","55","865","78","1309","1365","44","America/Guayaquil","535","LIMITED","1377","1613","1420","1599","1822","05a","1681","password","1111","1214","1376","1478","47","1082","4282","Europe/Istanbul","1307","46","058","1124","256","rate-overlimit","retail","u_a_socket_err_fix_succ_test","1292","1370","1388","520","861","psa","regular","1181","1766","05b","1183","1213","1304","1537"],["1724","profile_picture","1071","1314","1605","407","990","1710","746","pricing_model","056","059","061","1119","6027","65","877","1607","05d","917","seen","1516","49","470","973","1037","1350","1394","1480","1796","keys","794","1536","1594","2378","1333","1524","1825","116","309","52","808","827","909","495","1660","361","957","google","1357","1565","1967","996","1775","586","736","1052","1670","bank","177","1416","2194","2222","1454","1839","1275","53","997","1629","6028","smba","1378","1410","05c","1849","727","create","1559","536","1106","1310","1944","670","1297","1316","1762","en","1148","1295","1551","1853","1890","1208","1784","7200","05f","178","1283","1332","381","643","1056","1238","2024","2387","179","981","1547","1705","05e","290","903","1069","1285","2436","062","251","560","582","719","56","1700","2321","325","448","613","777","791","51","488","902","Asia/Almaty","is_hidden","1398","1527","1893","1999","2367","2642","237","busy","065","067","233","590","993","1511","54","723","860","363","487","522","605","995","1321","1691","1865","2447","2462","NON_TRANSACTIONAL","433","871","432","1004","1207","2032","2050","2379","2446","279","636","703","904","248","370","691","700","1068","1655","2334","060","063","364","533","534","567","1191","1210","1473","1827","069","701","2531","514","prev_dhash","064","496","790","1046","1139","1505","1521","1108","207","544","637","final","1173","1293","1694","1939","1951","1993","2353","2515","504","601","857","modify","spam_request","p_121_aa_1101_test4","866","1427","1502","1638","1744","2153","068","382","725","1704","1864","1990","2003","Asia/Dubai","508","531","1387","1474","1632","2307","2386","819","2014","066","387","1468","1706","2186","2261","471","728","1147","1372","1961"]],ZJ=["","xmlstreamstart","xmlstreamend","s.whatsapp.net","type","participant","from","receipt","id","notification","disappearing_mode","status","jid","broadcast","user","devices","device_hash","to","offline","message","result","class","xmlns","duration","notify","iq","t","ack","g.us","enc","urn:xmpp:whatsapp:push","presence","config_value","picture","verified_name","config_code","key-index-list","contact","mediatype","routing_info","edge_routing","get","read","urn:xmpp:ping","fallback_hostname","0","chatstate","business_hours_config","unavailable","download_buckets","skmsg","verified_level","composing","handshake","device-list","media","text","fallback_ip4","media_conn","device","creation","location","config","item","fallback_ip6","count","w:profile:picture","image","business","2","hostname","call-creator","display_name","relaylatency","platform","abprops","success","msg","offline_preview","prop","key-index","v","day_of_week","pkmsg","version","1","ping","w:p","download","video","set","specific_hours","props","primary","unknown","hash","commerce_experience","last","subscribe","max_buckets","call","profile","member_since_text","close_time","call-id","sticker","mode","participants","value","query","profile_options","open_time","code","list","host","ts","contacts","upload","lid","preview","update","usync","w:stats","delivery","auth_ttl","context","fail","cart_enabled","appdata","category","atn","direct_connection","decrypt-fail","relay_id","mmg-fallback.whatsapp.net","target","available","name","last_id","mmg.whatsapp.net","categories","401","is_new","index","tctoken","ip4","token_id","latency","recipient","edit","ip6","add","thumbnail-document","26","paused","true","identity","stream:error","key","sidelist","background","audio","3","thumbnail-image","biz-cover-photo","cat","gcm","thumbnail-video","error","auth","deny","serial","in","registration","thumbnail-link","remove","00","gif","thumbnail-gif","tag","capability","multicast","item-not-found","description","business_hours","config_expo_key","md-app-state","expiration","fallback","ttl","300","md-msg-hist","device_orientation","out","w:m","open_24h","side_list","token","inactive","01","document","te2","played","encrypt","msgr","hide","direct_path","12","state","not-authorized","url","terminate","signature","status-revoke-delay","02","te","linked_accounts","trusted_contact","timezone","ptt","kyc-id","privacy_token","readreceipts","appointment_only","address","expected_ts","privacy","7","android","interactive","device-identity","enabled","attribute_padding","1080","03","screen_height"],rT={};for(let[n,r]of ZJ.entries())rT[r]={index:n};for(let[n,r]of WJ.entries())for(let[o,i]of r.entries())rT[i]={dict:n,index:o};var uA="@s.whatsapp.net";var XJ="0@c.us";var ut;(function(n){n[n.WHATSAPP=0]="WHATSAPP",n[n.LID=1]="LID",n[n.HOSTED=128]="HOSTED",n[n.HOSTED_LID=129]="HOSTED_LID"})(ut||(ut={}));var $J=(n,r)=>{switch(r){case ut.LID:return"lid";case ut.HOSTED:return"hosted";case ut.HOSTED_LID:return"hosted.lid";case ut.WHATSAPP:default:return n}},Ft=(n,r,o,i)=>`${n||""}${i?`_${i}`:""}${o?`:${o}`:""}@${r}`,lA=n=>{let r=typeof n=="string"?n.indexOf("@"):-1;if(r<0)return;let o=n.slice(r+1),i=n.slice(0,r),[e,a]=i.split(":"),[A,t]=e.split("_"),s=ut.WHATSAPP;return o==="lid"?s=ut.LID:o==="hosted"?s=ut.HOSTED:o==="hosted.lid"?s=ut.HOSTED_LID:t&&(s=parseInt(t)),{server:o,user:A,domainType:s,device:a?+a:void 0}},lt=(n,r)=>lA(n)?.user===lA(r)?.user,gl=n=>n?.endsWith("@bot"),nt=n=>n?.endsWith("@s.whatsapp.net"),vA=n=>n?.endsWith("@lid"),HC=n=>n?.endsWith("@broadcast"),ir=n=>n?.endsWith("@g.us"),_n=n=>n==="status@broadcast",ks=n=>n?.endsWith("@newsletter"),Lt=n=>n?.endsWith("@hosted"),yr=n=>n?.endsWith("@hosted.lid"),tSe=/^1313555\d{4}$|^131655500\d{2}$/,eq=n=>n&&tSe.test(n.split("@")[0])&&n.endsWith("@c.us"),oA=n=>{let r=lA(n);if(!r)return"";let{user:o,server:i}=r;return Ft(o,i==="c.us"?"s.whatsapp.net":i)},Aq=(n,r)=>{let i=lA(n)?.device||0,{server:e,user:a}=lA(r);return Ft(a,e,i)};var tq=(n,r=UC,o=[0])=>{let i=rq(n,r,o);return Buffer.from(i)},rq=({tag:n,attrs:r,content:o},i,e)=>{let{TAGS:a,TOKEN_MAP:A}=i,t=H=>e.push(H&255),s=(H,q,j=!1)=>{for(let F=0;F>T*8&255)}},g=H=>{for(let q of H)e.push(q)},c=H=>{g([H>>8&255,H&255])},l=H=>g([H>>16&15,H>>8&255,H&255]),p=H=>{if(H>=4294967296)throw new Error("string too large to encode: "+H);H>=1<<20?(t(a.BINARY_32),s(H,4)):H>=256?(t(a.BINARY_20),l(H)):(t(a.BINARY_8),t(H))},B=H=>{let q=Buffer.from(H,"utf-8");p(q.length),g(q)},Q=({domainType:H,device:q,user:j,server:F})=>{typeof q<"u"?(t(a.AD_JID),t(H||0),t(q||0),G(j)):(t(a.JID_PAIR),j.length?G(j):t(a.LIST_EMPTY),G(F))},f=H=>{switch(H){case"-":return 10;case".":return 11;case"\0":return 15;default:if(H>="0"&&H<="9")return H.charCodeAt(0)-48;throw new Error(`invalid byte for nibble "${H}"`)}},y=H=>{if(H>="0"&&H<="9")return H.charCodeAt(0)-48;if(H>="A"&&H<="F")return 10+H.charCodeAt(0)-65;if(H>="a"&&H<="f")return 10+H.charCodeAt(0)-97;if(H==="\0")return 15;throw new Error(`Invalid hex char "${H}"`)},m=(H,q)=>{if(H.length>a.PACKED_MAX)throw new Error("Too many bytes to pack");t(q==="nibble"?a.NIBBLE_8:a.HEX_8);let j=Math.ceil(H.length/2);H.length%2!==0&&(j|=128),t(j);let F=q==="nibble"?f:y,T=(U,b)=>F(U)<<4|F(b),V=Math.floor(H.length/2);for(let U=0;U{if(!H||H.length>a.PACKED_MAX)return!1;for(let q of H)if(!(q>="0"&&q<="9")&&q!=="-"&&q!==".")return!1;return!0},k=H=>{if(!H||H.length>a.PACKED_MAX)return!1;for(let q of H)if(!(q>="0"&&q<="9")&&!(q>="A"&&q<="F"))return!1;return!0},G=H=>{if(H==null){t(a.LIST_EMPTY);return}if(H===""){B(H);return}let q=A[H];if(q)typeof q.dict=="number"&&t(a.DICTIONARY_0+q.dict),t(q.index);else if(R(H))m(H,"nibble");else if(k(H))m(H,"hex");else{let j=lA(H);j?Q(j):B(H)}},K=H=>{H===0?t(a.LIST_EMPTY):H<256?g([a.LIST_8,H]):(t(a.LIST_16),c(H))};if(!n)throw new Error("Invalid node: tag cannot be undefined");let x=Object.keys(r||{}).filter(H=>typeof r[H]<"u"&&r[H]!==null);K(2*x.length+1+(typeof o<"u"?1:0)),G(n);for(let H of x)typeof r[H]=="string"&&(G(H),G(r[H]));if(typeof o=="string")G(o);else if(Buffer.isBuffer(o)||o instanceof Uint8Array)p(o.length),g(o);else if(Array.isArray(o)){let H=o.filter(q=>q&&(q.tag||Buffer.isBuffer(q)||q instanceof Uint8Array||typeof q=="string"));K(H.length);for(let q of H)rq(q,i,e)}else if(!(typeof o>"u"))throw new Error(`invalid children for header "${n}": ${o} (${typeof o})`);return e};import{promisify as rSe}from"util";import{inflate as aSe}from"zlib";var iSe=rSe(aSe),oSe=async n=>(2&n.readUInt8()?n=await iSe(n.slice(1)):n=n.slice(1),n),aq=(n,r,o={index:0})=>{let{DOUBLE_BYTE_TOKENS:i,SINGLE_BYTE_TOKENS:e,TAGS:a}=r,A=L=>{if(o.index+L>n.length)throw new Error("end of stream")},t=()=>{let L=n[o.index];return o.index+=1,L},s=()=>(A(1),t()),g=L=>{A(L);let X=n.slice(o.index,o.index+L);return o.index+=L,X},c=L=>g(L).toString("utf-8"),l=(L,X=!1)=>{A(L);let pe=0;for(let me=0;me(A(3),((t()&15)<<16)+(t()<<8)+t()),B=L=>{if(L>=0&&L<16)return L<10?48+L:65+L-10;throw new Error("invalid hex: "+L)},Q=L=>{if(L>=0&&L<=9)return 48+L;switch(L){case 10:return 45;case 11:return 46;case 15:return 0;default:throw new Error("invalid nibble: "+L)}},f=(L,X)=>{if(L===a.NIBBLE_8)return Q(X);if(L===a.HEX_8)return B(X);throw new Error("unknown tag: "+L)},y=L=>{let X=s(),pe="";for(let me=0;me<(X&127);me++){let qe=s();pe+=String.fromCharCode(f(L,(qe&240)>>4)),pe+=String.fromCharCode(f(L,qe&15))}return X>>7!==0&&(pe=pe.slice(0,-1)),pe},m=L=>L===a.LIST_EMPTY||L===a.LIST_8||L===a.LIST_16,R=L=>{switch(L){case a.LIST_EMPTY:return 0;case a.LIST_8:return s();case a.LIST_16:return l(2);default:throw new Error("invalid tag for list size: "+L)}},k=()=>{let L=H(s()),X=H(s());if(X)return(L||"")+"@"+X;throw new Error("invalid jid pair: "+L+", "+X)},G=()=>{let L=s(),X=Number(L),pe=s(),me=H(s()),qe="s.whatsapp.net";return X===ut.LID?qe="lid":X===ut.HOSTED?qe="hosted":X===ut.HOSTED_LID&&(qe="hosted.lid"),Ft(me,qe,pe)},K=()=>{let L=H(s()),X=l(2),pe=H(s());return`${L}:${X}@${pe}`},x=()=>{let L=H(s()),X=l(2),pe=l(2),me="interop",qe=o.index;try{me=H(s())}catch{o.index=qe}return`${pe}-${L}:${X}@${me}`},H=L=>{if(L>=1&&L{let X=[],pe=R(L);for(let me=0;me{let pe=i[L];if(!pe)throw new Error(`Invalid double token dict (${L})`);let me=pe[X];if(typeof me>"u")throw new Error(`Invalid double token (${X})`);return me},F=R(s()),T=H(s());if(!F||!T.length)throw new Error("invalid node");let V={},U;if(F===0||!T)throw new Error("invalid node");let b=F-1>>1;for(let L=0;L{let r=await oSe(n);return aq(r,UC)};var nq=Le(ar(),1);var oq=new WeakMap,mA=(n,r)=>{if(!n||!Array.isArray(n.content))return[];let o=oq.get(n);if(!o){o=new Map;for(let i of n.content){let e=o.get(i.tag);e||o.set(i.tag,e=[]),e.push(i)}oq.set(n,o)}return o.get(r)||[]},ie=(n,r)=>mA(n,r)[0],bo=({content:n})=>Array.isArray(n)?n:[],vr=(n,r)=>{let o=ie(n,r)?.content;if(Buffer.isBuffer(o)||o instanceof Uint8Array)return o},RA=(n,r)=>{let o=ie(n,r)?.content;if(Buffer.isBuffer(o)||o instanceof Uint8Array)return Buffer.from(o).toString("utf-8");if(typeof o=="string")return o},vs=(n,r,o)=>{let i=vr(n,r);if(i)return nSe(i,o)},Oa=n=>{let r=ie(n,"error");if(r)throw new nq.Boom(r.attrs.text||"Unknown error",{data:+r.attrs.code})},aT=(n,r)=>mA(n,r).reduce((e,{attrs:a})=>(typeof a.name=="string"?e[a.name]=a.value||a.config_value:e[a.config_code]=a.value||a.config_value,e),{});function nSe(n,r){let o=0;for(let i=0;i" ".repeat(n);function Zi(n,r=0){if(!n)return n;if(typeof n=="string")return bf(r)+n;if(n instanceof Uint8Array)return bf(r)+Buffer.from(n).toString("hex");if(Array.isArray(n))return n.map(a=>bf(r+1)+Zi(a,r+1)).join(` `);let o=Zi(n.content,r+1),i=`<${n.tag} ${Object.entries(n.attrs||{}).filter(([,a])=>a!==void 0).map(([a,A])=>`${a}='${A}'`).join(" ")}`,e=o?`> ${o} ${bf(r)}`:"/>";return i+e}var Fs=Le(Os(),1);import{createCipheriv as cT,createDecipheriv as IT,createHash as ySe,createHmac as mSe,randomBytes as SSe}from"crypto";var JC=class n{static __wrap(r){r=r>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=r,sq.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,sq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_expandedappstatekeys_free(r,0)}get indexKey(){let r=$.expandedappstatekeys_indexKey(this.__wbg_ptr);return EA(r)}get patchMacKey(){let r=$.expandedappstatekeys_patchMacKey(this.__wbg_ptr);return EA(r)}get snapshotMacKey(){let r=$.expandedappstatekeys_snapshotMacKey(this.__wbg_ptr);return EA(r)}get valueEncryptionKey(){let r=$.expandedappstatekeys_valueEncryptionKey(this.__wbg_ptr);return EA(r)}get valueMacKey(){let r=$.expandedappstatekeys_valueMacKey(this.__wbg_ptr);return EA(r)}};Symbol.dispose&&(JC.prototype[Symbol.dispose]=JC.prototype.free);var Nf=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,gq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_groupcipher_free(r,0)}decrypt(r){let o=st(r,$.__wbindgen_export),i=_A,e=$.groupcipher_decrypt(this.__wbg_ptr,o,i);return EA(e)}encrypt(r){let o=st(r,$.__wbindgen_export),i=_A,e=$.groupcipher_encrypt(this.__wbg_ptr,o,i);return EA(e)}constructor(r,o,i){let e=$i(o,$.__wbindgen_export,$.__wbindgen_export2),a=_A;Ps(i,Gs);let A=$.groupcipher_new(Je(r),e,a,i.__wbg_ptr);return this.__wbg_ptr=A>>>0,gq.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(Nf.prototype[Symbol.dispose]=Nf.prototype.free);var Tf=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,cq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_groupsessionbuilder_free(r,0)}create(r){Ps(r,El);let o=$.groupsessionbuilder_create(this.__wbg_ptr,r.__wbg_ptr);return EA(o)}constructor(r){let o=$.groupsessionbuilder_new(Je(r));return this.__wbg_ptr=o>>>0,cq.register(this,this.__wbg_ptr,this),this}process(r,o){Ps(r,El),Ps(o,ll);let i=$.groupsessionbuilder_process(this.__wbg_ptr,r.__wbg_ptr,o.__wbg_ptr);return EA(i)}};Symbol.dispose&&(Tf.prototype[Symbol.dispose]=Tf.prototype.free);var qC=class n{static __wrap(r){r=r>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=r,Iq.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,Iq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_internalbinarynode_free(r,0)}get attrs(){let r=$.internalbinarynode_attrs(this.__wbg_ptr);return EA(r)}get content(){let r=$.internalbinarynode_content(this.__wbg_ptr);return EA(r)}set attrs(r){$.internalbinarynode_set_attrs(this.__wbg_ptr,Je(r))}set content(r){$.internalbinarynode_set_content(this.__wbg_ptr,Je(r))}get tag(){let r,o;try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.internalbinarynode_tag(a,this.__wbg_ptr);var i=Ke().getInt32(a+0,!0),e=Ke().getInt32(a+4,!0);return r=i,o=e,Wt(i,e)}finally{$.__wbindgen_add_to_stack_pointer(16),$.__wbindgen_export4(r,o,1)}}toJSON(){let r=$.internalbinarynode_toJSON(this.__wbg_ptr);return EA(r)}};Symbol.dispose&&(qC.prototype[Symbol.dispose]=qC.prototype.free);var Il=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,lq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_lthashantitampering_free(r,0)}constructor(){let r=$.lthashantitampering_new();return this.__wbg_ptr=r>>>0,lq.register(this,this.__wbg_ptr,this),this}subtractThenAdd(r,o,i){try{let t=$.__wbindgen_add_to_stack_pointer(-16),s=st(r,$.__wbindgen_export),g=_A,c=Qq(o,$.__wbindgen_export),l=_A,p=Qq(i,$.__wbindgen_export),B=_A;$.lthashantitampering_subtractThenAdd(t,this.__wbg_ptr,s,g,c,l,p,B);var e=Ke().getInt32(t+0,!0),a=Ke().getInt32(t+4,!0),A=Ke().getInt32(t+8,!0);if(A)throw EA(a);return EA(e)}finally{$.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(Il.prototype[Symbol.dispose]=Il.prototype.free);var Rf=class n{static __wrap(r){r=r>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=r,iT.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,iT.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_lthashstate_free(r,0)}clone(){let r=$.lthashstate_clone(this.__wbg_ptr);return n.__wrap(r)}deleteValueMac(r){let o=$i(r,$.__wbindgen_export,$.__wbindgen_export2),i=_A;return $.lthashstate_deleteValueMac(this.__wbg_ptr,o,i)!==0}getValueMac(r){let o=$i(r,$.__wbindgen_export,$.__wbindgen_export2),i=_A,e=$.lthashstate_getValueMac(this.__wbg_ptr,o,i);return EA(e)}hasValueMac(r){let o=$i(r,$.__wbindgen_export,$.__wbindgen_export2),i=_A;return $.lthashstate_hasValueMac(this.__wbg_ptr,o,i)!==0}get hash(){let r=$.lthashstate_hash(this.__wbg_ptr);return EA(r)}constructor(){let r=$.lthashstate_new();return this.__wbg_ptr=r>>>0,iT.register(this,this.__wbg_ptr,this),this}setValueMac(r,o){let i=$i(r,$.__wbindgen_export,$.__wbindgen_export2),e=_A,a=st(o,$.__wbindgen_export),A=_A;$.lthashstate_setValueMac(this.__wbg_ptr,i,e,a,A)}set hash(r){let o=st(r,$.__wbindgen_export),i=_A;$.lthashstate_set_hash(this.__wbg_ptr,o,i)}set version(r){$.lthashstate_set_version(this.__wbg_ptr,r)}get version(){let r=$.lthashstate_version(this.__wbg_ptr);return BigInt.asUintN(64,r)}};Symbol.dispose&&(Rf.prototype[Symbol.dispose]=Rf.prototype.free);var kf=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,Eq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_noisesession_free(r,0)}authenticate(r){let o=st(r,$.__wbindgen_export),i=_A;$.noisesession_authenticate(this.__wbg_ptr,o,i)}get bufferedBytes(){return $.noisesession_bufferedBytes(this.__wbg_ptr)>>>0}clearBuffer(){$.noisesession_clearBuffer(this.__wbg_ptr)}decodeFrame(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16),A=st(r,$.__wbindgen_export),t=_A;$.noisesession_decodeFrame(a,this.__wbg_ptr,A,t);var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return EA(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}decrypt(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16),A=st(r,$.__wbindgen_export),t=_A;$.noisesession_decrypt(a,this.__wbg_ptr,A,t);var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return EA(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}encodeFrame(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.noisesession_encodeFrame(a,this.__wbg_ptr,Je(r));var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return EA(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}encodeFrameRaw(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16),A=st(r,$.__wbindgen_export),t=_A;$.noisesession_encodeFrameRaw(a,this.__wbg_ptr,A,t);var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return EA(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}encrypt(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16),A=st(r,$.__wbindgen_export),t=_A;$.noisesession_encrypt(a,this.__wbg_ptr,A,t);var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return EA(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}finishInit(){try{let i=$.__wbindgen_add_to_stack_pointer(-16);$.noisesession_finishInit(i,this.__wbg_ptr);var r=Ke().getInt32(i+0,!0),o=Ke().getInt32(i+4,!0);if(o)throw EA(r)}finally{$.__wbindgen_add_to_stack_pointer(16)}}getHash(){let r=$.noisesession_getHash(this.__wbg_ptr);return EA(r)}get isFinished(){return $.noisesession_isFinished(this.__wbg_ptr)!==0}mixIntoKey(r){try{let e=$.__wbindgen_add_to_stack_pointer(-16),a=st(r,$.__wbindgen_export),A=_A;$.noisesession_mixIntoKey(e,this.__wbg_ptr,a,A);var o=Ke().getInt32(e+0,!0),i=Ke().getInt32(e+4,!0);if(i)throw EA(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}constructor(r,o,i){try{let g=$.__wbindgen_add_to_stack_pointer(-16),c=st(r,$.__wbindgen_export),l=_A,p=st(o,$.__wbindgen_export),B=_A;var e=Xi(i)?0:st(i,$.__wbindgen_export),a=_A;$.noisesession_new(g,c,l,p,B,e,a);var A=Ke().getInt32(g+0,!0),t=Ke().getInt32(g+4,!0),s=Ke().getInt32(g+8,!0);if(s)throw EA(t);return this.__wbg_ptr=A>>>0,Eq.register(this,this.__wbg_ptr,this),this}finally{$.__wbindgen_add_to_stack_pointer(16)}}processHandshakeFinish(r,o,i){try{let t=$.__wbindgen_add_to_stack_pointer(-16),s=st(r,$.__wbindgen_export),g=_A,c=st(o,$.__wbindgen_export),l=_A,p=st(i,$.__wbindgen_export),B=_A;$.noisesession_processHandshakeFinish(t,this.__wbg_ptr,s,g,c,l,p,B);var e=Ke().getInt32(t+0,!0),a=Ke().getInt32(t+4,!0),A=Ke().getInt32(t+8,!0);if(A)throw EA(a);return EA(e)}finally{$.__wbindgen_add_to_stack_pointer(16)}}processHandshakeInit(r,o,i,e){try{let s=$.__wbindgen_add_to_stack_pointer(-16),g=st(r,$.__wbindgen_export),c=_A,l=st(o,$.__wbindgen_export),p=_A,B=st(i,$.__wbindgen_export),Q=_A,f=st(e,$.__wbindgen_export),y=_A;$.noisesession_processHandshakeInit(s,this.__wbg_ptr,g,c,l,p,B,Q,f,y);var a=Ke().getInt32(s+0,!0),A=Ke().getInt32(s+4,!0),t=Ke().getInt32(s+8,!0);if(t)throw EA(A);return EA(a)}finally{$.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(kf.prototype[Symbol.dispose]=kf.prototype.free);var Gs=class n{static __wrap(r){r=r>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=r,oT.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,oT.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_protocoladdress_free(r,0)}get deviceId(){return $.protocoladdress_deviceId(this.__wbg_ptr)>>>0}static from(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.protocoladdress_from(a,Je(r));var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return n.__wrap(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}get id(){let r,o;try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.protocoladdress_id(a,this.__wbg_ptr);var i=Ke().getInt32(a+0,!0),e=Ke().getInt32(a+4,!0);return r=i,o=e,Wt(i,e)}finally{$.__wbindgen_add_to_stack_pointer(16),$.__wbindgen_export4(r,o,1)}}is(r){return Ps(r,n),$.protocoladdress_is(this.__wbg_ptr,r.__wbg_ptr)!==0}constructor(r,o){try{let A=$.__wbindgen_add_to_stack_pointer(-16);$.protocoladdress_new(A,Je(r),Je(o));var i=Ke().getInt32(A+0,!0),e=Ke().getInt32(A+4,!0),a=Ke().getInt32(A+8,!0);if(a)throw EA(e);return this.__wbg_ptr=i>>>0,oT.register(this,this.__wbg_ptr,this),this}finally{$.__wbindgen_add_to_stack_pointer(16)}}toString(){let r,o;try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.protocoladdress_toString(a,this.__wbg_ptr);var i=Ke().getInt32(a+0,!0),e=Ke().getInt32(a+4,!0);return r=i,o=e,Wt(i,e)}finally{$.__wbindgen_add_to_stack_pointer(16),$.__wbindgen_export4(r,o,1)}}};Symbol.dispose&&(Gs.prototype[Symbol.dispose]=Gs.prototype.free);var ll=class n{static __wrap(r){r=r>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=r,pq.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,pq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_senderkeydistributionmessage_free(r,0)}static deserialize(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16),A=st(r,$.__wbindgen_export),t=_A;$.senderkeydistributionmessage_deserialize(a,A,t);var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return n.__wrap(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}serialize(){let r=$.senderkeydistributionmessage_serialize(this.__wbg_ptr);return EA(r)}};Symbol.dispose&&(ll.prototype[Symbol.dispose]=ll.prototype.free);var El=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,Cq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_senderkeyname_free(r,0)}constructor(r,o){let i=$i(r,$.__wbindgen_export,$.__wbindgen_export2),e=_A;Ps(o,Gs);let a=$.senderkeyname_new(i,e,o.__wbg_ptr);return this.__wbg_ptr=a>>>0,Cq.register(this,this.__wbg_ptr,this),this}toString(){let r,o;try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.senderkeyname_toString(a,this.__wbg_ptr);var i=Ke().getInt32(a+0,!0),e=Ke().getInt32(a+4,!0);return r=i,o=e,Wt(i,e)}finally{$.__wbindgen_add_to_stack_pointer(16),$.__wbindgen_export4(r,o,1)}}};Symbol.dispose&&(El.prototype[Symbol.dispose]=El.prototype.free);var vf=class n{static __wrap(r){r=r>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=r,nT.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,nT.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_senderkeyrecord_free(r,0)}static deserialize(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16),A=st(r,$.__wbindgen_export),t=_A;$.senderkeyrecord_deserialize(a,A,t);var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return n.__wrap(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}isEmpty(){return $.senderkeyrecord_isEmpty(this.__wbg_ptr)!==0}constructor(){let r=$.senderkeyrecord_new();return this.__wbg_ptr=r>>>0,nT.register(this,this.__wbg_ptr,this),this}serialize(){try{let e=$.__wbindgen_add_to_stack_pointer(-16);$.senderkeyrecord_serialize(e,this.__wbg_ptr);var r=Ke().getInt32(e+0,!0),o=Ke().getInt32(e+4,!0),i=Ke().getInt32(e+8,!0);if(i)throw EA(o);return EA(r)}finally{$.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(vf.prototype[Symbol.dispose]=vf.prototype.free);var Pf=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,hq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_sessionbuilder_free(r,0)}initOutgoing(r){let o=$.sessionbuilder_initOutgoing(this.__wbg_ptr,Je(r));return EA(o)}constructor(r,o){Ps(o,Gs);let i=$.sessionbuilder_new(Je(r),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,hq.register(this,this.__wbg_ptr,this),this}processPreKeyBundle(r){let o=$.sessionbuilder_processPreKeyBundle(this.__wbg_ptr,Je(r));return EA(o)}};Symbol.dispose&&(Pf.prototype[Symbol.dispose]=Pf.prototype.free);var Gf=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,dq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_sessioncipher_free(r,0)}decryptPreKeyWhisperMessage(r){let o=st(r,$.__wbindgen_export),i=_A,e=$.sessioncipher_decryptPreKeyWhisperMessage(this.__wbg_ptr,o,i);return EA(e)}decryptWhisperMessage(r){let o=st(r,$.__wbindgen_export),i=_A,e=$.sessioncipher_decryptWhisperMessage(this.__wbg_ptr,o,i);return EA(e)}encrypt(r){let o=st(r,$.__wbindgen_export),i=_A,e=$.sessioncipher_encrypt(this.__wbg_ptr,o,i);return EA(e)}hasOpenSession(){let r=$.sessioncipher_hasOpenSession(this.__wbg_ptr);return EA(r)}constructor(r,o){Ps(o,Gs);let i=$.sessioncipher_new(Je(r),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,dq.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(Gf.prototype[Symbol.dispose]=Gf.prototype.free);var VC=class n{static __wrap(r){r=r>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=r,uq.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,uq.unregister(this),r}free(){let r=this.__destroy_into_raw();$.__wbg_sessionrecord_free(r,0)}static deserialize(r){try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.sessionrecord_deserialize(a,Je(r));var o=Ke().getInt32(a+0,!0),i=Ke().getInt32(a+4,!0),e=Ke().getInt32(a+8,!0);if(e)throw EA(i);return n.__wrap(o)}finally{$.__wbindgen_add_to_stack_pointer(16)}}haveOpenSession(){return $.sessionrecord_haveOpenSession(this.__wbg_ptr)!==0}serialize(){let r=$.sessionrecord_serialize(this.__wbg_ptr);return EA(r)}};Symbol.dispose&&(VC.prototype[Symbol.dispose]=VC.prototype.free);function fq(n){let r=st(n,$.__wbindgen_export),o=_A,i=$.expandAppStateKeys(r,o);return JC.__wrap(i)}function eo(n,r,o){try{let A=$.__wbindgen_add_to_stack_pointer(-16),t=st(n,$.__wbindgen_export),s=_A;$.hkdf(A,t,s,r,Je(o));var i=Ke().getInt32(A+0,!0),e=Ke().getInt32(A+4,!0),a=Ke().getInt32(A+8,!0);if(a)throw EA(e);return EA(i)}finally{$.__wbindgen_add_to_stack_pointer(16)}}function sSe(){return{__proto__:null,"./whatsapp_rust_bridge_bg.js":{__proto__:null,__wbg_Error_83742b46f01ce22d:function(r,o){let i=Error(Wt(r,o));return Je(i)},__wbg_Number_a5a435bd7bbec835:function(r){return Number(we(r))},__wbg_String_8564e559799eccda:function(r,o){let i=String(we(o)),e=$i(i,$.__wbindgen_export,$.__wbindgen_export2),a=_A;Ke().setInt32(r+4,a,!0),Ke().setInt32(r+0,e,!0)},__wbg___wbindgen_bigint_get_as_i64_447a76b5c6ef7bda:function(r,o){let i=we(o),e=typeof i=="bigint"?i:void 0;Ke().setBigInt64(r+8,Xi(e)?BigInt(0):e,!0),Ke().setInt32(r+0,!Xi(e),!0)},__wbg___wbindgen_boolean_get_c0f3f60bac5a78d1:function(r){let o=we(r),i=typeof o=="boolean"?o:void 0;return Xi(i)?16777215:i?1:0},__wbg___wbindgen_debug_string_5398f5bb970e0daa:function(r,o){let i=gT(we(o)),e=$i(i,$.__wbindgen_export,$.__wbindgen_export2),a=_A;Ke().setInt32(r+4,a,!0),Ke().setInt32(r+0,e,!0)},__wbg___wbindgen_in_41dbb8413020e076:function(r,o){return we(r)in we(o)},__wbg___wbindgen_is_bigint_e2141d4f045b7eda:function(r){return typeof we(r)=="bigint"},__wbg___wbindgen_is_function_3c846841762788c1:function(r){return typeof we(r)=="function"},__wbg___wbindgen_is_null_0b605fc6b167c56f:function(r){return we(r)===null},__wbg___wbindgen_is_object_781bc9f159099513:function(r){let o=we(r);return typeof o=="object"&&o!==null},__wbg___wbindgen_is_undefined_52709e72fb9f179c:function(r){return we(r)===void 0},__wbg___wbindgen_jsval_eq_ee31bfad3e536463:function(r,o){return we(r)===we(o)},__wbg___wbindgen_jsval_loose_eq_5bcc3bed3c69e72b:function(r,o){return we(r)==we(o)},__wbg___wbindgen_number_get_34bb9d9dcfa21373:function(r,o){let i=we(o),e=typeof i=="number"?i:void 0;Ke().setFloat64(r+8,Xi(e)?0:e,!0),Ke().setInt32(r+0,!Xi(e),!0)},__wbg___wbindgen_string_get_395e606bd0ee4427:function(r,o){let i=we(o),e=typeof i=="string"?i:void 0;var a=Xi(e)?0:$i(e,$.__wbindgen_export,$.__wbindgen_export2),A=_A;Ke().setInt32(r+4,A,!0),Ke().setInt32(r+0,a,!0)},__wbg___wbindgen_throw_6ddd609b62940d55:function(r,o){throw new Error(Wt(r,o))},__wbg__wbg_cb_unref_6b5b6b8576d35cb1:function(r){we(r)._wbg_cb_unref()},__wbg_attrs_eb268b5ce109b817:function(r){let o=we(r).attrs;return Je(o)},__wbg_call_2d781c1f4d5c0ef8:function(){return zt(function(r,o,i){let e=we(r).call(we(o),we(i));return Je(e)},arguments)},__wbg_call_e133b57c9155d22c:function(){return zt(function(r,o){let i=we(r).call(we(o));return Je(i)},arguments)},__wbg_content_54fb4ecf37d1b68a:function(r){let o=we(r).content;return Je(o)},__wbg_debug_10ca7029b12f8d85:function(r,o,i,e){we(r).debug(we(o),i===0?void 0:Wt(i,e))},__wbg_done_08ce71ee07e3bd17:function(r){return we(r).done},__wbg_entries_e8a20ff8c9757101:function(r){let o=Object.entries(we(r));return Je(o)},__wbg_error_9cce413345f88385:function(r,o,i,e){we(r).error(we(o),i===0?void 0:Wt(i,e))},__wbg_from_4bdf88943703fd48:function(r){let o=Array.from(we(r));return Je(o)},__wbg_getOurIdentity_85a51d9b5b46c006:function(){return zt(function(r){let o=we(r).getOurIdentity();return Je(o)},arguments)},__wbg_getOurRegistrationId_6d41d022f3c2af8a:function(){return zt(function(r){let o=we(r).getOurRegistrationId();return Je(o)},arguments)},__wbg_getRandomValues_3f44b700395062e5:function(){return zt(function(r,o){globalThis.crypto.getRandomValues(KC(r,o))},arguments)},__wbg_get_326e41e095fb2575:function(){return zt(function(r,o){let i=Reflect.get(we(r),we(o));return Je(i)},arguments)},__wbg_get_3ef1eba1850ade27:function(){return zt(function(r,o){let i=Reflect.get(we(r),we(o));return Je(i)},arguments)},__wbg_get_a8ee5c45dabc1b3b:function(r,o){let i=we(r)[o>>>0];return Je(i)},__wbg_get_unchecked_329cfe50afab7352:function(r,o){let i=we(r)[o>>>0];return Je(i)},__wbg_get_with_ref_key_6412cf3094599694:function(r,o){let i=we(r)[we(o)];return Je(i)},__wbg_has_926ef2ff40b308cf:function(){return zt(function(r,o){return Reflect.has(we(r),we(o))},arguments)},__wbg_info_b728e87a346ff6a2:function(r,o,i,e){we(r).info(we(o),i===0?void 0:Wt(i,e))},__wbg_instanceof_ArrayBuffer_101e2bf31071a9f6:function(r){let o;try{o=we(r)instanceof ArrayBuffer}catch{o=!1}return o},__wbg_instanceof_Map_f194b366846aca0c:function(r){let o;try{o=we(r)instanceof Map}catch{o=!1}return o},__wbg_instanceof_Object_be1962063fcc0c9f:function(r){let o;try{o=we(r)instanceof Object}catch{o=!1}return o},__wbg_instanceof_Promise_7c3bdd7805c2c6e6:function(r){let o;try{o=we(r)instanceof Promise}catch{o=!1}return o},__wbg_instanceof_Uint8Array_740438561a5b956d:function(r){let o;try{o=we(r)instanceof Uint8Array}catch{o=!1}return o},__wbg_internalbinarynode_new:function(r){let o=qC.__wrap(r);return Je(o)},__wbg_isArray_33b91feb269ff46e:function(r){return Array.isArray(we(r))},__wbg_isSafeInteger_ecd6a7f9c3e053cd:function(r){return Number.isSafeInteger(we(r))},__wbg_isTrustedIdentity_8beedd37958ed6af:function(){return zt(function(r,o,i,e,a){let A=we(r).isTrustedIdentity(Wt(o,i),we(e),a>>>0);return Je(A)},arguments)},__wbg_iterator_d8f549ec8fb061b1:function(){return Je(Symbol.iterator)},__wbg_keys_ab0d051a1c55236d:function(r){let o=Object.keys(we(r));return Je(o)},__wbg_length_b3416cf66a5452c8:function(r){return we(r).length},__wbg_length_ea16607d7b61445b:function(r){return we(r).length},__wbg_level_4b50b181832c5acf:function(r,o){let i=we(o).level,e=$i(i,$.__wbindgen_export,$.__wbindgen_export2),a=_A;Ke().setInt32(r+4,a,!0),Ke().setInt32(r+0,e,!0)},__wbg_loadPreKey_db3458e3339f7328:function(){return zt(function(r,o){let i=we(r).loadPreKey(o>>>0);return Je(i)},arguments)},__wbg_loadSenderKey_fd075b57283fd71b:function(){return zt(function(r,o,i){let e=we(r).loadSenderKey(Wt(o,i));return Je(e)},arguments)},__wbg_loadSession_8564b20b09724f27:function(){return zt(function(r,o,i){let e=we(r).loadSession(Wt(o,i));return Je(e)},arguments)},__wbg_loadSignedPreKey_3d5c6c6819f3adf3:function(){return zt(function(r,o){let i=we(r).loadSignedPreKey(o>>>0);return Je(i)},arguments)},__wbg_new_5f486cdf45a04d78:function(r){let o=new Uint8Array(we(r));return Je(o)},__wbg_new_7dce085c132c6f91:function(r,o){let i=new TypeError(Wt(r,o));return Je(i)},__wbg_new_a70fbab9066b301f:function(){let r=new Array;return Je(r)},__wbg_new_ab79df5bd7c26067:function(){let r=new Object;return Je(r)},__wbg_new_from_slice_22da9388ac046e50:function(r,o){let i=new Uint8Array(KC(r,o));return Je(i)},__wbg_new_typed_aaaeaf29cf802876:function(r,o){try{var i={a:r,b:o},e=(A,t)=>{let s=i.a;i.a=0;try{return cSe(s,i.b,A,t)}finally{i.a=s}};let a=new Promise(e);return Je(a)}finally{i.a=i.b=0}},__wbg_new_with_length_3259a525196bd8cc:function(r){let o=new Array(r>>>0);return Je(o)},__wbg_new_with_length_825018a1616e9e55:function(r){let o=new Uint8Array(r>>>0);return Je(o)},__wbg_next_11b99ee6237339e3:function(){return zt(function(r){let o=we(r).next();return Je(o)},arguments)},__wbg_next_e01a967809d1aa68:function(r){let o=we(r).next;return Je(o)},__wbg_parse_e9eddd2a82c706eb:function(){return zt(function(r,o){let i=JSON.parse(Wt(r,o));return Je(i)},arguments)},__wbg_prototypesetcall_d62e5099504357e6:function(r,o,i){Uint8Array.prototype.set.call(KC(r,o),we(i))},__wbg_push_e87b0e732085a946:function(r,o){return we(r).push(we(o))},__wbg_queueMicrotask_0c399741342fb10f:function(r){let o=we(r).queueMicrotask;return Je(o)},__wbg_queueMicrotask_a082d78ce798393e:function(r){queueMicrotask(we(r))},__wbg_removePreKey_c0b0a066eb6f2e1e:function(){return zt(function(r,o){let i=we(r).removePreKey(o>>>0);return Je(i)},arguments)},__wbg_resolve_ae8d83246e5bcc12:function(r){let o=Promise.resolve(we(r));return Je(o)},__wbg_senderkeydistributionmessage_new:function(r){let o=ll.__wrap(r);return Je(o)},__wbg_sessionrecord_new:function(r){let o=VC.__wrap(r);return Je(o)},__wbg_set_282384002438957f:function(r,o,i){we(r)[o>>>0]=EA(i)},__wbg_set_6be42768c690e380:function(r,o,i){we(r)[EA(o)]=EA(i)},__wbg_set_7eaa4f96924fd6b3:function(){return zt(function(r,o,i){return Reflect.set(we(r),we(o),we(i))},arguments)},__wbg_set_8c0b3ffcf05d61c2:function(r,o,i){we(r).set(KC(o,i))},__wbg_static_accessor_GLOBAL_8adb955bd33fac2f:function(){let r=typeof global>"u"?null:global;return Xi(r)?0:Je(r)},__wbg_static_accessor_GLOBAL_THIS_ad356e0db91c7913:function(){let r=typeof globalThis>"u"?null:globalThis;return Xi(r)?0:Je(r)},__wbg_static_accessor_SELF_f207c857566db248:function(){let r=typeof self>"u"?null:self;return Xi(r)?0:Je(r)},__wbg_static_accessor_WINDOW_bb9f1ba69d61b386:function(){let r=typeof window>"u"?null:window;return Xi(r)?0:Je(r)},__wbg_storeSenderKey_8a6c9ec5f7e1cd2e:function(){return zt(function(r,o,i,e){let a=we(r).storeSenderKey(Wt(o,i),we(e));return Je(a)},arguments)},__wbg_storeSessionRaw_09b5cc73064d12d8:function(){return zt(function(r,o,i,e){let a=we(r).storeSessionRaw(Wt(o,i),we(e));return Je(a)},arguments)},__wbg_storeSession_4d419555ce654965:function(){return zt(function(r,o,i,e){let a=we(r).storeSession(Wt(o,i),EA(e));return Je(a)},arguments)},__wbg_tag_33cfe8e9ee66b4db:function(r,o){let i=we(o).tag,e=$i(i,$.__wbindgen_export,$.__wbindgen_export2),a=_A;Ke().setInt32(r+4,a,!0),Ke().setInt32(r+0,e,!0)},__wbg_then_098abe61755d12f6:function(r,o){let i=we(r).then(we(o));return Je(i)},__wbg_then_9e335f6dd892bc11:function(r,o,i){let e=we(r).then(we(o),we(i));return Je(e)},__wbg_trace_58264fbce2ceb5e6:function(r,o,i,e){we(r).trace(we(o),i===0?void 0:Wt(i,e))},__wbg_value_21fc78aab0322612:function(r){let o=we(r).value;return Je(o)},__wbg_warn_db531770752932a9:function(r,o,i,e){we(r).warn(we(o),i===0?void 0:Wt(i,e))},__wbindgen_cast_0000000000000001:function(r,o){let i=lSe(r,o,$.__wasm_bindgen_func_elem_694,gSe);return Je(i)},__wbindgen_cast_0000000000000002:function(r){return Je(r)},__wbindgen_cast_0000000000000003:function(r){return Je(r)},__wbindgen_cast_0000000000000004:function(r,o){let i=KC(r,o);return Je(i)},__wbindgen_cast_0000000000000005:function(r,o){let i=Wt(r,o);return Je(i)},__wbindgen_cast_0000000000000006:function(r){let o=BigInt.asUintN(64,r);return Je(o)},__wbindgen_object_clone_ref:function(r){let o=we(r);return Je(o)},__wbindgen_object_drop_ref:function(r){EA(r)}}}}function gSe(n,r,o){try{let a=$.__wbindgen_add_to_stack_pointer(-16);$.__wasm_bindgen_func_elem_699(a,n,r,Je(o));var i=Ke().getInt32(a+0,!0),e=Ke().getInt32(a+4,!0);if(e)throw EA(i)}finally{$.__wbindgen_add_to_stack_pointer(16)}}function cSe(n,r,o,i){$.__wasm_bindgen_func_elem_1248(n,r,Je(o),Je(i))}var sq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_expandedappstatekeys_free(n>>>0,1)),gq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_groupcipher_free(n>>>0,1)),cq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_groupsessionbuilder_free(n>>>0,1)),Iq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_internalbinarynode_free(n>>>0,1)),lq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_lthashantitampering_free(n>>>0,1)),iT=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_lthashstate_free(n>>>0,1)),Eq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_noisesession_free(n>>>0,1)),oT=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_protocoladdress_free(n>>>0,1)),pq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_senderkeydistributionmessage_free(n>>>0,1)),Cq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_senderkeyname_free(n>>>0,1)),nT=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_senderkeyrecord_free(n>>>0,1)),hq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_sessionbuilder_free(n>>>0,1)),dq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_sessioncipher_free(n>>>0,1)),uq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>$.__wbg_sessionrecord_free(n>>>0,1));function Je(n){xC===Nn.length&&Nn.push(Nn.length+1);let r=xC;return xC=Nn[r],Nn[r]=n,r}function Ps(n,r){if(!(n instanceof r))throw new Error(`expected instance of ${r.name}`)}var Bq=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>n.dtor(n.a,n.b));function gT(n){let r=typeof n;if(r=="number"||r=="boolean"||n==null)return`${n}`;if(r=="string")return`"${n}"`;if(r=="symbol"){let e=n.description;return e==null?"Symbol":`Symbol(${e})`}if(r=="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+=gT(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 ISe(n){n<1028||(Nn[n]=xC,xC=n)}function KC(n,r){return n=n>>>0,cl().subarray(n/1,n/1+r)}var nc=null;function Ke(){return(nc===null||nc.buffer.detached===!0||nc.buffer.detached===void 0&&nc.buffer!==$.memory.buffer)&&(nc=new DataView($.memory.buffer)),nc}function Wt(n,r){return n=n>>>0,pSe(n,r)}var YC=null;function cl(){return(YC===null||YC.byteLength===0)&&(YC=new Uint8Array($.memory.buffer)),YC}function we(n){return Nn[n]}function zt(n,r){try{return n.apply(this,r)}catch(o){$.__wbindgen_export3(Je(o))}}var Nn=new Array(1024).fill(void 0);Nn.push(void 0,null,!0,!1);var xC=Nn.length;function Xi(n){return n==null}function lSe(n,r,o,i){let e={a:n,b:r,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let t=e.a;e.a=0;try{return i(t,e.b,...A)}finally{e.a=t,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,Bq.unregister(e))},Bq.register(a,e,e),a}function st(n,r){let o=r(n.length*1,1)>>>0;return cl().set(n,o/1),_A=n.length,o}function Qq(n,r){let o=r(n.length*4,4)>>>0,i=Ke();for(let e=0;e>>0;return cl().subarray(s,s+t.length).set(t),_A=t.length,s}let i=n.length,e=r(i,1)>>>0,a=cl(),A=0;for(;A127)break;a[e+A]=t}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let t=cl().subarray(e+A,e+i),s=jC.encodeInto(n,t);A+=s.written,e=o(e,i,A,1)>>>0}return _A=A,e}function EA(n){let r=we(n);return ISe(n),r}var _f=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});_f.decode();var ESe=2146435072,sT=0;function pSe(n,r){return sT+=r,sT>=ESe&&(_f=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),_f.decode(),sT=r),_f.decode(cl().subarray(n,n+r))}var jC=new TextEncoder;"encodeInto"in jC||(jC.encodeInto=function(n,r){let o=jC.encode(n);return r.set(o),{read:n.length,written:o.length}});var _A=0,CSe,$;function hSe(n,r){return $=n.exports,CSe=r,nc=null,YC=null,$}function yq(n){if($!==void 0)return $;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let r=sSe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,r);return hSe(o,n)}var dSe=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 mq(n){let r=atob(n),o=new Uint8Array(r.length);for(let i=0;in.length===33?n:Buffer.concat([Tn,n]),Ut={generateKeyPair:()=>{let{pubKey:n,privKey:r}=Fs.generateKeyPair();return{private:Buffer.from(r),public:Buffer.from(n.slice(1))}},sharedKey:(n,r)=>{let o=Fs.calculateAgreement(di(r),n);return Buffer.from(o)},sign:(n,r)=>Fs.calculateSignature(n,r),verify:(n,r,o)=>{try{return Fs.verifySignature(di(n),r,o),!0}catch{return!1}}},Ff=(n,r)=>{let o=Ut.generateKeyPair(),i=di(o.public),e=Ut.sign(n.private,i);return{keyPair:o,signature:e,keyId:r}},Dq=16;function sc(n,r,o,i){let e=cT("aes-256-gcm",r,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function gc(n,r,o,i){let e=IT("aes-256-gcm",r,o),a=n.slice(0,n.length-Dq),A=n.slice(n.length-Dq);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function wq(n,r,o){let i=cT("aes-256-ctr",r,o);return Buffer.concat([i.update(n),i.final()])}function Oq(n,r,o){let i=IT("aes-256-ctr",r,o);return Buffer.concat([i.update(n),i.final()])}function Mq(n,r){return DSe(n.subarray(16),r,n.subarray(0,16))}function DSe(n,r,o){let i=IT("aes-256-cbc",r,o);return Buffer.concat([i.update(n),i.final()])}function bq(n,r){let o=SSe(16),i=cT("aes-256-cbc",r,o);return Buffer.concat([o,i.update(n),i.final()])}function Ao(n,r,o="sha256"){return mSe(o,r).update(n).digest()}function pl(n){return ySe("sha256").update(n).digest()}async function Lf(n,r){let i=new TextEncoder().encode(n),e=new Uint8Array(r instanceof Uint8Array?r:new Uint8Array(r)),a=await Sq.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await Sq.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var WC={replacer:(n,r)=>Buffer.isBuffer(r)||r instanceof Uint8Array||r?.type==="Buffer"?{type:"Buffer",data:Buffer.from(r?.data||r).toString("base64")}:r,reviver:(n,r)=>{if(typeof r=="object"&&r!==null&&r.type==="Buffer"&&typeof r.data=="string")return Buffer.from(r.data,"base64");if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=Object.keys(r);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(r);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return r}},Cl=(n,r="me")=>(n?.fromMe?r:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",Tq=n=>n==null||n==="",OSe=n=>{let o=(zC(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},Rq=n=>{let r=new Uint8Array(n);if(r.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=r[r.length-1];if(o>r.length)throw new Error(`unpad given ${r.length} bytes, but pad is ${o}`);return new Uint8Array(r.buffer,r.byteOffset,r.length-o)},kq=n=>(n.sort(),"2:"+pl(Buffer.from(n.join(""))).toString("base64").slice(0,6)),hl=n=>OSe(Ae.Message.encode(n).finish()),vq=()=>Uint16Array.from(zC(2))[0]&16383,Rn=(n,r=4)=>{let o=n,i=new Uint8Array(r);for(let e=r-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},or=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,Pr=(n=new Date)=>Math.floor(n.getTime()/1e3);var ZC=n=>Pq(n).delay,Pq=n=>{let r=new Error().stack,o,i;return{delay:new Promise((A,t)=>{o=setTimeout(A,n),i=t}),cancel:()=>{clearTimeout(o),i(new Uf.Boom("Cancelled",{statusCode:500,data:{stack:r}}))}}};async function dl(n,r){if(!n)return new Promise(r);let o=new Error().stack,{delay:i,cancel:e}=Pq(n);return new Promise((A,t)=>{i.then(()=>t(new Uf.Boom("Timed Out",{statusCode:yt.timedOut,data:{stack:o}}))).catch(s=>t(s)),r(A,t)}).finally(e)}var nr=n=>{let r=Buffer.alloc(44);if(r.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=lA(n);e?.user&&(r.write(e.user,8),r.write("@c.us",8+e.user.length))}return zC(16).copy(r,28),"3EB0"+wSe("sha256").update(r).digest().toString("hex").toUpperCase().substring(0,18)},lT=()=>"3EB0"+zC(18).toString("hex").toUpperCase();function ET(n,r){return async(o,i)=>{let e,a;await dl(i,(A,t)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&t(g?.error||new Uf.Boom("Connection Closed",{statusCode:yt.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(r,e)}).finally(()=>{n.off(r,e),n.off("connection.update",a)})}}var Gq=n=>ET(n,"connection.update");var Fq=()=>{let n=zC(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},MSe={sender:Ae.WebMessageInfo.Status.SERVER_ACK,played:Ae.WebMessageInfo.Status.PLAYED,read:Ae.WebMessageInfo.Status.READ,"read-self":Ae.WebMessageInfo.Status.READ},Lq=n=>{let r=MSe[n];return typeof n>"u"?Ae.WebMessageInfo.Status.DELIVERY_ACK:r},bSe={conflict:yt.connectionReplaced},Uq=n=>{let[r]=bo(n),o=r?.tag||"unknown",i=+(n.attrs.code||bSe[o]||yt.badSession);return i===yt.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},Hq=({tag:n,attrs:r})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":r.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},_q="Unexpected server response: ",Kq=n=>{let r=500;if(n?.message?.includes(_q)){let o=+n?.message.slice(_q.length);!Number.isNaN(o)&&o>=400&&(r=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(r=408);return r};function Hf(n){for(let r in n)typeof n[r]>"u"&&delete n[r];return n}var Nq="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function Yq(n){let r=0,o=0,i=[];for(let e of n)for(r=r<<8|e&255,o+=8;o>=5;)i.push(Nq.charAt(r>>>o-5&31)),o-=5;return o>0&&i.push(Nq.charAt(r<<5-o&31)),i.join("")}function xq(n){return Ae.Message.encode(n).finish()}var cc=Le(ar(),1);var _Se=async(n,r)=>vA(n)||yr(n)?n:await r.lidMapping.getLIDForPN(n)||n,NSe=async(n,r,o,i,e)=>{let{senderAlt:a}=Yf(n);if(a&&vA(a)&&nt(r)&&i===r)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:r}]),await o.migrateSession(r,a),e.debug({sender:r,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:r,senderAlt:a,error:A},"Failed to store LID mapping")}},Kf="Message absent from node",jq="Key used already or never filled",Jq="Your account has been restricted",TSe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},Ic={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},pT={MessageAccountRestriction:"463",SmaxInvalid:"479"},Yf=n=>{let r,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(r=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(r=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:r,recipientAlt:o}};function CT(n,r,o){let i,e,a,A=!1,t=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!t)throw new cc.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new cc.Boom("Invalid message stanza: missing from attribute",{data:n});let l=Yf(n),p=m=>lt(m,r),B=m=>lt(m,o);if(nt(s)||vA(s)||yr(s)||Lt(s)){if(c&&!gl(c)){if(!p(s)&&!B(s))throw new cc.Boom("receipient present, but msg not from me",{data:n});(p(s)||B(s))&&(A=!0),e=c}else(p(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(ir(s)){if(!g)throw new cc.Boom("No participant in group message");(p(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(HC(s)){if(!g)throw new cc.Boom("No participant in group message");let m=p(g);_n(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(ks(s))i="newsletter",e=s,a=s,(p(s)||B(s))&&(A=!0);else throw new cc.Boom("Unknown message type",{data:n});let Q=n?.attrs?.notify,f={remoteJid:e,remoteJidAlt:ir(e)?void 0:l.senderAlt,remoteJidUsername:ir(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:t,participant:g,participantAlt:ir(e)?l.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:l.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:f,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:Q,broadcast:HC(s)};return f.fromMe&&(y.status=Ae.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var qq=(n,r,o,i,e)=>{let{fullMessage:a,author:A,sender:t}=CT(n,r,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:l}of n.content){if(g==="verified_name"&&l instanceof Uint8Array){let Q=Ae.VerifiedNameCertificate.decode(l),f=Ae.VerifiedNameCertificate.Details.decode(Q.details);a.verifiedBizName=f.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"||!(l instanceof Uint8Array))continue;s+=1;let p,B=await _Se(A,i);g!=="plaintext"&&await NSe(n,A,i,B,e);try{let Q=g==="plaintext"?"plaintext":c.type;switch(Q){case"skmsg":p=await i.decryptGroupMessage({group:t,authorJid:A,msg:l});break;case"pkmsg":case"msg":p=await i.decryptMessage({jid:B,type:Q,ciphertext:l});break;case"plaintext":p=l;break;default:throw new Error(`Unknown e2e type: ${Q}`)}let f=Ae.Message.decode(Q!=="plaintext"?Rq(p):p);if(f=f.deviceSentMessage?.message||f,f.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:f.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,f):a.message=f}catch(Q){let f={key:a.key,err:Q,messageType:g==="plaintext"?"plaintext":c.type,sender:t,author:A,isSessionRecordError:RSe(Q)};e.error(f,"failed to decrypt message"),a.messageStubType=Ae.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[Q.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=Ae.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[Kf])}}};function RSe(n){let r=n?.message||n?.toString()||"";return TSe.sessionRecordErrors.some(o=>r.includes(o))}var Yn=Le(ar(),1);import{randomBytes as bk}from"crypto";import{promises as _k}from"fs";var ro=Le(ar(),1);import{exec as RTe}from"child_process";import*as qa from"crypto";import{once as aE}from"events";import{createReadStream as Lm,createWriteStream as fk,promises as oE}from"fs";import{tmpdir as QZ}from"os";import{join as Gm}from"path";import{Readable as Kh,Transform as kTe}from"stream";import{URL as yk}from"url";var mk=()=>QZ(),fZ=async()=>{let[n,r]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(iz(),az)).catch(()=>{})]);if(r)return{sharp:r};if(n)return{jimp:n};throw new ro.Boom("No image processing library available")},vTe=n=>`WhatsApp ${RZ[n]} Keys`,Um=async(n,r,o)=>{let{stream:i}=await Yh(n);o?.debug("got stream for raw upload");let e=qa.createHash("sha256"),a=Gm(QZ(),r+nr()),A=fk(a),t=0;try{for await(let g of i)t+=g.length,e.update(g),A.write(g)||await aE(A,"drain");A.end(),await aE(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:t}}catch(s){A.destroy(),i.destroy();try{await oE.unlink(a)}catch{}throw s}};async function yZ(n,r){if(!n)throw new ro.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=eo(n,112,{info:vTe(r)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var PTe=async(n,r,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${r}`;RTe(A,t=>{t?a(t):e()})}),Sk=async(n,r=32)=>{n instanceof Kh&&(n=await Fm(n));let o=await fZ();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(r).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:r,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new ro.Boom("No image processing library available")},GTe=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),Hm=async(n,r)=>{let o,{width:i=640,height:e=640}=r||{};if(Buffer.isBuffer(n))o=n;else{let{stream:t}=await Yh(n);o=await Fm(t)}let a=await fZ(),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 t=await a.jimp.Jimp.read(o),s=Math.min(t.width,t.height);A=t.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 ro.Boom("No image processing library available");return{img:await A}};async function mZ(n){let r=await Promise.resolve().then(()=>(uZ(),dZ)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await r.parseBuffer(n,void 0,i):typeof n=="string"?o=await r.parseFile(n,i):o=await r.parseStream(n,void 0,i),o.format.duration}async function SZ(n,r){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let p=Lm(n);i=await Fm(p)}else i=await Fm(n);let a=(await o(i)).getChannelData(0),A=64,t=Math.floor(a.length/A),s=[];for(let p=0;pp*g);return new Uint8Array(c.map(p=>Math.floor(100*p)))}catch(o){r?.debug("Failed to generate waveform: "+o)}}var BZ=n=>{let r=new Kh({read:()=>{}});return r.push(n),r.push(null),r},Fm=async n=>{let r=[];for await(let o of n)r.push(o);return n.destroy(),Buffer.concat(r)},Yh=async(n,r)=>{if(Buffer.isBuffer(n))return{stream:BZ(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:BZ(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await Km(n.url,r),type:"remote"}:{stream:Lm(n.url),type:"file"}};async function DZ(n,r,o){let i,e;if(r==="image"){let{buffer:a,original:A}=await Sk(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(r==="video"){let a=Gm(mk(),nr()+".jpg");try{await PTe(n,a,"00:00:00",{width:32,height:32}),i=(await oE.readFile(a)).toString("base64"),await oE.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var Km=async(n,r={})=>{let o=await fetch(n.toString(),{dispatcher:r.dispatcher,method:"GET",headers:r.headers});if(!o.ok)throw new ro.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof Kh?o.body:Kh.fromWeb(o.body)},wZ=async(n,r,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await Yh(n,e);o?.debug("fetched media stream");let t=qa.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await yZ(t,r),l=Gm(mk(),r+nr()+"-enc"),p=fk(l),B,Q;i&&(Q=Gm(mk(),r+nr()+"-original"),B=fk(Q));let f=0,y=qa.createCipheriv("aes-256-cbc",s,g),m=qa.createHmac("sha256",c).update(g),R=qa.createHash("sha256"),k=qa.createHash("sha256"),G=async K=>{k.update(K),m.update(K),p.write(K)||await aE(p,"drain")};try{for await(let F of a){if(f+=F.length,A==="remote"&&e?.maxContentLength&&f+F.length>e.maxContentLength)throw new ro.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(F)||await aE(B,"drain")),R.update(F),await G(y.update(F))}await G(y.final());let K=m.digest().slice(0,10);k.update(K);let x=R.digest(),H=k.digest();p.write(K);let q=aE(p,"finish"),j=B?aE(B,"finish"):Promise.resolve();return p.end(),B?.end?.(),a.destroy(),await q,await j,o?.debug("encrypted data successfully"),{mediaKey:t,originalFilePath:Q,encFilePath:l,mac:K,fileEncSha256:H,fileSha256:x,fileLength:f}}catch(K){p.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),R.destroy(),k.destroy(),a.destroy();try{await oE.unlink(l),Q&&await oE.unlink(Q)}catch(x){o?.error({err:x},"failed deleting tmp files")}throw K}},Dk="mmg.whatsapp.net",iE=16,Qk=n=>Math.floor(n/iE)*iE,xh=(n,r=Dk)=>`https://${r}${n}`,FTe=n=>{if(n)try{return new yk(n).host}catch{return}},nE=async({mediaKey:n,directPath:r,url:o},i,e={})=>{let a=e.host??FTe(o),A=r?xh(r,a):o;if(!A)throw new ro.Boom("No valid media URL or directPath present in message",{statusCode:400});let t=await yZ(n,i);return LTe(A,t,e)},LTe=async(n,{cipherKey:r,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,t=0,s=!1;if(i){let m=Qk(i||0);m&&(t=m-iE,A=m,s=!0)}let g=e?Qk(e||0)+iE:void 0,c=a?.headers?a.headers:void 0,l={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:jh};(t||g)&&(l.Range=`bytes=${t}-`,g&&(l.Range+=g));let p=await Km(n,{...a||{},headers:l}),B=Buffer.from([]),Q,f=(m,R)=>{if(i||e){let k=A>=i?void 0:Math.max(i-A,0),G=A+m.lengththis.push(x)),k()}catch(x){k(x)}},final(m){try{f(Q.final(),R=>this.push(R)),m()}catch(R){m(R)}}});return p.pipe(y,{end:!0})};var UTe=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",OZ=async({url:n,filePath:r,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new yk(n),t=A.protocol==="https:"?await import("https"):await import("http"),g=(await oE.stat(r)).size;return new Promise((c,l)=>{let p=t.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},Q=>{if(Q.statusCode&&Q.statusCode>=300&&Q.statusCode<400&&Q.headers.location){Q.resume();let y=new yk(Q.headers.location,n).toString();c(OZ({url:y,filePath:r,headers:o,timeoutMs:i,agent:e},a+1));return}let f="";Q.on("data",y=>f+=y),Q.on("end",()=>{try{c(JSON.parse(f))}catch{c(void 0)}})});p.on("error",l),p.on("timeout",()=>{p.destroy(),l(new Error("Upload timeout"))});let B=Lm(r);B.pipe(p),B.on("error",Q=>{p.destroy(),l(Q)})})},HTe=async({url:n,filePath:r,headers:o,timeoutMs:i,agent:e})=>{let a=Lm(r),A=Kh.toWeb(a),t=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...t?{dispatcher:t}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},KTe=async(n,r)=>UTe()?(r?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),OZ(n)):(r?.debug("Using web-standard Fetch API for upload"),HTe(n)),MZ=({customUploadHosts:n,fetchAgent:r,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:t,timeoutMs:s})=>{let g=await e(!1),c,l=[...n,...g.hosts];t=GTe(t);let B={...(()=>{let Q=i?.headers;return Q?Array.isArray(Q)?Object.fromEntries(Q):Q:{}})(),"Content-Type":"application/octet-stream",Origin:jh};for(let{hostname:Q}of l){o.debug(`uploading to "${Q}"`);let f=encodeURIComponent(g.auth),y=`https://${Q}${Ok[A]}/${t}?auth=${f}&token=${t}`,m;try{if(m=await KTe({url:y,filePath:a,headers:B,timeoutMs:s,agent:r},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(R){let k=Q===l[g.hosts.length-1]?.hostname;o.warn({trace:R?.stack,uploadResult:m},`Error in uploading to ${Q} ${k?"":", retrying..."}`)}}if(!c)throw new ro.Boom("Media upload failed on all hosts",{statusCode:500});return c},bZ=n=>eo(n,32,{info:"WhatsApp Media Retry Notification"}),_Z=(n,r,o)=>{let i={stanzaId:n.id},e=Ae.ServerErrorReceipt.encode(i).finish(),a=qa.randomBytes(12),A=bZ(r),t=sc(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:oA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:t},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},NZ=n=>{let r=ie(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:r.attrs.jid,fromMe:r.attrs.from_me==="true",participant:r.attrs.participant}},i=ie(n,"error");if(i){let e=+i.attrs.code;o.error=new ro.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:wk(e)})}else{let e=ie(n,"encrypt"),a=vr(e,"enc_p"),A=vr(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new ro.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},TZ=({ciphertext:n,iv:r},o,i)=>{let e=bZ(o),a=gc(n,e,r,Buffer.from(i));return Ae.MediaRetryNotification.decode(a)},wk=n=>YTe[n],YTe={[Ae.MediaRetryNotification.ResultType.SUCCESS]:200,[Ae.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[Ae.MediaRetryNotification.ResultType.NOT_FOUND]:404,[Ae.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as xTe}from"crypto";var jTe=[{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}]}],vZ=n=>{let r=new Map;for(let o of n)r.set(o.f,{m:o.m,children:o.s?vZ(o.s):void 0});return r},JTe=vZ(jTe),qTe=new Map,VTe="Report Token",Ym={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},xm=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,zTe=(n,r,o,i,e)=>{let a=Buffer.concat([Buffer.from(r,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return eo(e,32,{info:a.toString("latin1")})},PZ=(n,r)=>{let o=[],i=0;for(;i>3,A=e.value&7,t=i;i+=e.bytes;let s=r.get(a),g=l=>l>n.length?!1:(o.push({num:a,bytes:n.subarray(t,l)}),i=l,!0),c=l=>l>n.length?!1:(i=l,!0);if(A===Ym.VARINT){let l=Mk(n,i);if(!l.ok)return null;let p=i+l.bytes;if(!s){if(!c(p))return null;continue}if(!g(p))return null;continue}if(A===Ym.FIXED64){let l=i+8;if(!s){if(!c(l))return null;continue}if(!g(l))return null;continue}if(A===Ym.FIXED32){let l=i+4;if(!s){if(!c(l))return null;continue}if(!g(l))return null;continue}if(A===Ym.BYTES){let l=Mk(n,i);if(!l.ok)return null;let p=i+l.bytes,B=p+l.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let Q=PZ(n.subarray(p,B),s.children??qTe);if(Q===null)return null;if(Q.length>0){let f=kZ(e.value),y=kZ(Q.length);o.push({num:a,bytes:Buffer.concat([f,y,Q])})}i=B;continue}o.push({num:a,bytes:n.subarray(t,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)))},Mk=(n,r)=>{let o=0,i=0,e=0;for(;r+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},kZ=n=>{let r=[],o=n>>>0;for(;o>127;)r.push(o&127|128),o>>>=7;return r.push(o),Buffer.from(r)},GZ=async(n,r,o)=>{let i=r.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=zTe(VTe,o.id,e,a,i),t=PZ(n,JTe);if(!t||t.length===0)return null;let s=xTe("sha256",A).update(t).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var WTe={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},FZ={image:Ae.Message.ImageMessage,video:Ae.Message.VideoMessage,audio:Ae.Message.AudioMessage,sticker:Ae.Message.StickerMessage,document:Ae.Message.DocumentMessage},ZTe=n=>n.match(qZ)?.[0],XTe=async(n,r,o)=>{let i=ZTe(n);if(r&&i)try{return await r(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},LZ=async n=>{let r;if(typeof n=="number")r=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),r=parseInt(o,16),r}},Jh=async(n,r)=>{let o=r.logger,i;for(let x of VZ)x in n&&(i=x);if(!i)throw new Yn.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&&!!r.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=WTe[i]),a){let x=await r.mediaCache.get(a);if(x){o?.debug({cacheableKey:a},"got media cache hit");let H=Ae.Message.decode(x),q=`${i}Message`;return Object.assign(H[q],{...e,media:void 0}),H}}if(!!r.jid&&ks(r.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:x,fileSha256:H,fileLength:q}=await Um(e.media,r.mediaTypeOverride||i,o),j=H.toString("base64"),{mediaUrl:F,directPath:T}=await r.upload(x,{fileEncSha256B64:j,mediaType:i,timeoutMs:r.mediaUploadTimeoutMs});await _k.unlink(x);let V=Ae.Message.fromObject({[`${i}Message`]:FZ[i].fromObject({url:F,directPath:T,fileSha256:H,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 r.mediaCache.set(a,Ae.Message.encode(V).finish())),V}let t=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=r.backgroundColor&&i==="audio"&&e.ptt===!0,l=t||s,{mediaKey:p,encFilePath:B,originalFilePath:Q,fileEncSha256:f,fileSha256:y,fileLength:m}=await wZ(e.media,r.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:l,opts:r.options}),R=f.toString("base64"),[{mediaUrl:k,directPath:G}]=await Promise.all([(async()=>{let x=await r.upload(B,{fileEncSha256B64:R,mediaType:i,timeoutMs:r.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),x})(),(async()=>{try{if(s){let{thumbnail:x,originalImageDimensions:H}=await DZ(Q,i,r);e.jpegThumbnail=x,!e.width&&H&&(e.width=H.width,e.height=H.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}t&&(e.seconds=await mZ(Q),o?.debug("computed audio duration")),g&&(e.waveform=await SZ(Q,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await LZ(r.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(x){o?.warn({trace:x.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await _k.unlink(B),Q&&await _k.unlink(Q),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),K=Ae.Message.fromObject({[`${i}Message`]:FZ[i].fromObject({url:k,directPath:G,mediaKey:p,fileEncSha256:f,fileSha256:y,fileLength:m,mediaKeyTimestamp:Pr(),...e,media:void 0})});return e.ptv&&(K.ptvMessage=K.videoMessage,delete K.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await r.mediaCache.set(a,Ae.Message.encode(K).finish())),K},$Te=n=>{n=n||0;let r={ephemeralMessage:{message:{protocolMessage:{type:Ae.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return Ae.Message.fromObject(r)},eRe=(n,r)=>{let o=n.message;if(!o)throw new Yn.Boom("no content in message",{statusCode:400});o=Hr(o),o=Ae.Message.decode(Ae.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!r?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},Or=(n,r)=>typeof n=="object"&&n!==null&&r in n&&n[r]!==null&&n[r]!==void 0;function Tc(n,r){return typeof n=="object"&&n!==null&&r in n&&n[r]!==null}var ARe=async(n,r)=>{var o,i;let e={};if(Or(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await XTe(n.text,r.getUrlInfo,r.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let t=A.highQualityThumbnail;t&&(a.thumbnailDirectPath=t.directPath,a.mediaKey=t.mediaKey,a.mediaKeyTimestamp=t.mediaKeyTimestamp,a.thumbnailWidth=t.width,a.thumbnailHeight=t.height,a.thumbnailSha256=t.fileSha256,a.thumbnailEncSha256=t.fileEncSha256)}r.backgroundColor&&(a.backgroundArgb=await LZ(r.backgroundColor)),r.font&&(a.font=r.font),e.extendedTextMessage=a}else if(Or(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new Yn.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=Ae.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=Ae.Message.ContactsArrayMessage.create(n.contacts)}else if(Or(n,"location"))e.locationMessage=Ae.Message.LocationMessage.create(n.location);else if(Or(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=Ae.Message.ReactionMessage.create(n.react);else if(Or(n,"delete"))e.protocolMessage={key:n.delete,type:Ae.Message.ProtocolMessage.Type.REVOKE};else if(Or(n,"forward"))e=eRe(n.forward,n.force);else if(Or(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?Vh:0:n.disappearingMessagesInChat;e=$Te(a)}else if(Or(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,r.getProfilePicUrl){let a=await r.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:r?.options?.dispatcher});if(A.ok){let t=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=t}}}}else if(Or(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(Or(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:Ae.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(Tc(n,"ptv")&&n.ptv){let{videoMessage:a}=await Jh({video:n.video},r);e.ptvMessage=a}else if(Or(n,"product")){let{imageMessage:a}=await Jh({image:n.product.productImage},r);e.productMessage=Ae.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(Or(n,"listReply"))e.listResponseMessage={...n.listReply};else if(Or(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&r.getCallLink){let A=await r.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?JZ:jZ)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||bk(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(Or(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new Yn.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new Yn.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||bk(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 Or(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:Or(n,"sharePhoneNumber")?e.protocolMessage={type:Ae.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:Or(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:Or(n,"limitSharing")?e.protocolMessage={type:Ae.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await Jh(n,r);if(Tc(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),Tc(n,"mentions")&&n.mentions?.length||Tc(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(Tc(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:Ae.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),Tc(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 Tc(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:Ae.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),xm(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=bk(32))),Ae.Message.create(e)},tRe=(n,r,o)=>{o.timestamp||(o.timestamp=new Date);let i=Hr(r),e=qh(i),a=Pr(o.timestamp),{quoted:A,userJid:t}=o;if(A&&!ks(n)){let g=A.key.fromMe?t:A.participant||A.key.participant||A.key.remoteJid,c=Hr(A.message),l=qh(c);c=Ae.Message.create({[l]:c[l]});let p=c[l];typeof p=="object"&&p&&"contextInfo"in p&&delete p.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=oA(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"&&!ks(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||Vh}),r=Ae.Message.create(r);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||nr()},message:r,messageTimestamp:a,messageStubParameters:[],participant:ir(n)||_n(n)?t:void 0,status:sl.PENDING};return Ae.WebMessageInfo.fromObject(s)},UZ=async(n,r,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),tRe(n,await ARe(r,{...o,jid:n}),o)),qh=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},Hr=n=>{if(!n)return;for(let o=0;o<5;o++){let i=r(n);if(!i)break;n=i.message}return n;function r(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},HZ=n=>{let r=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=Hr(n),n?.buttonsMessage?r(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?r(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?r(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?r(n?.templateMessage?.fourRowTemplate):n};var Nk=(n,r)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===r.userJid);o?Object.assign(o,r):n.userReceipt.push(r)},Tk=(n,r)=>{let o=Cl(r.key),i=(n.reactions||[]).filter(e=>Cl(e.key)!==o);r.text=r.text||"",i.push(r),n.reactions=i};var KZ=n=>{let r={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;r[A]||(r[A]={jid:o,participant:e,messageIds:[]}),r[A].messageIds.push(i)}return Object.values(r)},rRe=[410,404],YZ=async(n,r,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&rRe.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=HZ(n.message);if(!A)throw new Yn.Boom("No message present",{statusCode:400,data:n});let t=qh(A),s=t?.replace("Message",""),g=A[t];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new Yn.Boom(`"${t}" 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 l=await nE(c,s,o);if(r==="buffer"){let p=[];for await(let B of l)p.push(B);return Buffer.concat(p)}return l}},xZ=n=>{n=HZ(n);let r=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!r)throw new Yn.Boom("given message is not a media message",{statusCode:400,data:n});return r};var jm=Le(ar(),1);import{createHash as nRe}from"crypto";function aRe(n,r){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:di(r)}),iRe=async({get:n},r,o)=>{let i=[];for(let e=r;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=r-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=Ut.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,r]}},zh=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:Rn(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),kk=(n,r)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:Rn(r,3)},{tag:"value",attrs:{},content:n.public}]}),Rk=n=>typeof n=="number"&&Number.isInteger(n),WZ=n=>{let r=ie(n,"keys");if(!r)return null;let o=vr(r,"type");if(!o||o.length!==1||o[0]!==Tn[0])return null;let i=vr(r,"identity"),e=ie(r,"skey");if(!i||i.length!==32||!e)return null;let a=vs(n,"registration",4);if(!Rk(a))return null;let A=vr(e,"value"),t=vr(e,"signature"),s=vs(e,"id",3);if(!A||A.length!==32||!t||!Rk(s))return null;let g=ie(r,"key"),c;if(g){let l=vr(g,"value"),p=vs(g,"id",3);if(!l||l.length!==32||!Rk(p))return null;c={keyId:p,publicKey:di(l)}}return{registrationId:a,identityKey:di(i),signedPreKey:{keyId:s,publicKey:di(A),signature:t},preKey:c}},ZZ=async(n,r)=>{let o=A=>A?{keyId:vs(A,"id",3),publicKey:di(vr(A,"value")),signature:vr(A,"signature")}:void 0,i=mA(ie(n,"list"),"user");for(let A of i)Oa(A);let a=aRe(i,100);for(let A of a)for(let t of A){let s=ie(t,"skey"),g=ie(t,"key"),c=vr(t,"identity"),l=t.attrs.jid,p=vs(t,"registration",4);await r.injectE2ESession({jid:l,session:{registrationId:p,identityKey:di(c),signedPreKey:o(s),preKey:o(g)}})}},XZ=(n,r,o,i)=>{let{user:e,device:a}=lA(r),A=[];for(let t of n){let{devices:s,id:g}=t,c=lA(g),{user:l,server:p}=c,{domainType:B}=c,Q=s?.deviceList;if(Array.isArray(Q))for(let{id:f,keyIndex:y,isHosted:m}of Q)(!i||f!==0)&&(e!==l&&o!==l||a!==f)&&(f===0||y)&&(m&&(B=B===ut.LID?ut.HOSTED_LID:ut.HOSTED),A.push({user:l,device:f,domainType:B,server:$J(p,B)}))}return A},vk=async({creds:n,keys:r},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=oRe(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await r.set({"pre-key":i});let t=await iRe(r,a[0],a[0]+a[1]);return{update:A,preKeys:t}},$Z=async(n,r)=>{let{creds:o}=n,{update:i,preKeys:e}=await vk(n,r),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:uA},content:[{tag:"registration",attrs:{},content:Rn(o.registrationId)},{tag:"type",attrs:{},content:Tn},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>kk(e[+A],+A))},zh(o.signedPreKey)]};return{update:i,node:a}};var sRe=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?Ae.ClientPayload.UserAgent.Platform.ANDROID:Ae.ClientPayload.UserAgent.Platform.WEB,releaseChannel:Ae.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),e9={"Mac OS":Ae.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:Ae.ClientPayload.WebInfo.WebSubPlatform.WIN32},gRe=n=>{let r=Ae.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&e9[n.browser[0]]&&n.browser[1]==="Desktop"&&(r=e9[n.browser[0]]),{webSubPlatform:r}},A9=n=>{let r={connectType:Ae.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:Ae.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:sRe(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(r.webInfo=gRe(n)),n.pushName&&(r.pushName=n.pushName),r},t9=(n,r)=>{let{user:o,device:i}=lA(n),e={...A9(r),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return Ae.ClientPayload.fromObject(e)},cRe=n=>{let r=n.toUpperCase();return r==="ANDROID"?Ae.DeviceProps.PlatformType.ANDROID_PHONE:Ae.DeviceProps.PlatformType[r]||Ae.DeviceProps.PlatformType.CHROME},r9=({registrationId:n,signedPreKey:r,signedIdentityKey:o},i)=>{let e=nRe("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:cRe(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=Ae.DeviceProps.encode(a).finish(),t={...A9(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:Rn(n),eKeytype:Tn,eIdent:o.public,eSkeyId:Rn(r.keyId,3),eSkeyVal:r.keyPair.public,eSkeySig:r.signature}};return Ae.ClientPayload.fromObject(t)},a9=(n,{advSecretKey:r,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=ie(n,"pair-success"),A=ie(a,"device-identity"),t=ie(a,"platform"),s=ie(a,"device"),g=ie(a,"biz");if(!A||!s)throw new jm.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,l=s.attrs.jid,p=s.attrs.lid,{details:B,hmac:Q,accountType:f}=Ae.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);f!==void 0&&f===Ae.ADVEncryptionType.HOSTED&&(y=Pk);let m=Ao(Buffer.concat([y,B]),Buffer.from(r,"base64"));if(Buffer.compare(Q,m)!==0)throw new jm.Boom("Invalid account signature");let R=Ae.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:k,accountSignature:G,details:K}=R,x=Ae.ADVDeviceIdentity.decode(K),H=x.deviceType===Ae.ADVEncryptionType.HOSTED?Pk:i9,q=Buffer.concat([H,K,o.public]);if(!Ut.verify(k,q,G))throw new jm.Boom("Failed to verify account signature");let j=Buffer.concat([o9,K,o.public,k]);R.deviceSignature=Ut.sign(o.private,j);let F=zZ(p,k),T=Wh(R,!1),V={tag:"iq",attrs:{to:uA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":x.keyIndex.toString()},content:T}]}]};return{creds:{account:R,me:{id:l,name:c,lid:p},signalIdentities:[...i||[],F],platform:t?.attrs.name},reply:V}},Wh=(n,r)=>(n={...n},(!r||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),Ae.ADVSignedDeviceIdentity.encode(n).finish());var sE=Le(ar(),1);var g9=12,n9=Buffer.alloc(0),s9=n=>{let r=new ArrayBuffer(g9);return new DataView(r).setUint32(8,n),new Uint8Array(r)},Gk=class{constructor(r,o){this.encKey=r,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(g9)}encrypt(r){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,sc(r,this.encKey,this.iv,n9)}decrypt(r){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,gc(r,this.decKey,this.iv,n9)}},c9=({keyPair:{private:n,public:r},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(I9),A=a.byteLength===32?a:pl(a),t=A,s=A,g=A,c=0,l=!1,p=Buffer.alloc(0),B=null,Q=!1,f=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=pl(Buffer.concat([A,q])))},R=q=>{if(B)return B.encrypt(q);let j=sc(q,s,s9(c++),A);return m(j),j},k=q=>{if(B)return B.decrypt(q);let j=gc(q,g,s9(c++),A);return m(q),j},G=q=>{let j=eo(Buffer.from(q),64,{salt:t,info:""});return[j.subarray(0,32),j.subarray(32)]},K=q=>{let[j,F]=G(q);t=j,s=F,g=F,c=0},x=async()=>{Q=!0;let[q,j]=G(new Uint8Array(0));B=new Gk(q,j),Q=!1,i.trace("Noise handler transitioned to Transport state"),f&&(i.trace({length:p.length},"Flushing buffered frames after transport ready"),await H(f),f=null)},H=async q=>{let j;for(;;){if(p.length<3||(j=p[0]<<16|p[1]<<8|p[2],p.length{m(q.ephemeral),K(Ut.sharedKey(n,q.ephemeral));let F=k(q.static);K(Ut.sharedKey(n,F));let T=k(q.payload),{intermediate:V,leaf:U}=Ae.CertChain.decode(T);if(!U?.details||!U?.signature)throw new sE.Boom("invalid noise leaf certificate",{statusCode:400});if(!V?.details||!V?.signature)throw new sE.Boom("invalid noise intermediate certificate",{statusCode:400});let b=Ae.CertChain.NoiseCertificate.Details.decode(V.details),{issuerSerial:L}=b,X=Ut.verify(b.key,U.details,U.signature),pe=Ut.verify(Fk.PUBLIC_KEY,V.details,V.signature);if(!X)throw new sE.Boom("noise certificate signature invalid",{statusCode:400});if(!pe)throw new sE.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(L!==Fk.SERIAL)throw new sE.Boom("certification match failed",{statusCode:400});let me=R(j.public);return K(Ut.sharedKey(j.private,q.ephemeral)),me},encodeFrame:q=>{B&&(q=B.encrypt(q));let j=q.byteLength,F=l?0:y.length,T=Buffer.allocUnsafe(F+3+j);return l||(T.set(y),l=!0),T[F]=j>>>16&255,T[F+1]=j>>>8&255,T[F+2]=j&255,T.set(q,F+3),T},decodeFrame:async(q,j)=>{if(Q){p=Buffer.concat([p,q]),f=j;return}p.length===0?p=Buffer.from(q):p=Buffer.concat([p,q]),await H(j)}}};import{pipeline as IRe}from"stream/promises";import{promisify as lRe}from"util";import{createInflate as ERe,inflate as pRe}from"zlib";var CRe=lRe(pRe),hRe=n=>{for(let r of n){let o=r.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(nt(i)||Lt(i)))return i}},dRe=async(n,r)=>{let o=await nE(n,"md-msg-hist",{options:r}),i=ERe(),e=[];i.on("data",t=>e.push(t)),await IRe(o,i);let a=Buffer.concat(e);return Ae.HistorySync.decode(a)},uRe=(n,r)=>{let o=[],i=[],e=[],a=[];r?.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 Ae.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case Ae.HistorySync.HistorySyncType.RECENT:case Ae.HistorySync.HistorySyncType.FULL:case Ae.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 t=A.id,s=vA(t)||yr(t),g=nt(t)||Lt(t);if(s&&A.pnJid)a.push({lid:t,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:t});else if(s&&!A.pnJid){let l=hRe(A.messages||[]);l&&a.push({lid:t,pn:l})}let c=A.messages||[];delete A.messages;for(let l of c){let p=l.message;o.push(p),A.messages?.length||(A.messages=[{message:p}]),!p.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=or(p.messageTimestamp)),(p.messageStubType===QA.BIZ_PRIVACY_MODE_TO_BSP||p.messageStubType===QA.BIZ_PRIVACY_MODE_TO_FB)&&p.messageStubParameters?.[0]&&i.push({id:p.key.participant||p.key.remoteJid,verifiedName:p.messageStubParameters?.[0]})}e.push(A)}break;case Ae.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}},l9=async(n,r,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=Ae.HistorySync.decode(await CRe(n.initialHistBootstrapInlinePayload)):i=await dRe(n,r),uRe(i,o)},Jm=n=>(n?Hr(n):void 0)?.protocolMessage?.historySyncNotification;var Mi=Le(ar(),1);var Wo;(function(n){n.Chat="label_jid",n.Message="label_message"})(Wo||(Wo={}));var E9=new Il;var p9=(n,r,o)=>{let i=[];if(!r)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=nt(r),A=a?r:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:r,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&vA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:r}}),i},C9=(n,r)=>{for(let o of r)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var Zh=n=>{let r=fq(n);return{indexKey:r.indexKey,valueEncryptionKey:r.valueEncryptionKey,valueMacKey:r.valueMacKey,snapshotMacKey:r.snapshotMacKey,patchMacKey:r.patchMacKey}},h9=(n,r,o,i)=>{let e=n===Ae.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 t=new Uint8Array(8);t[7]=A.length;let s=new Uint8Array(A.length+r.length+t.length);return s.set(A,0),s.set(r,A.length),s.set(t,A.length+r.length),Ao(s,i,"sha512").subarray(0,32)},d9=n=>{let r=Buffer.alloc(8);return r.writeUint32BE(n,4),r},u9=({indexValueMap:n,hash:r})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let t=Buffer.from(e).toString("base64"),s=n[t];if(A===Ae.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[t]}else o.push(a),n[t]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=E9.subtractThenAdd(r,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},Lk=(n,r,o,i)=>{let e=Buffer.concat([n,d9(r),Buffer.from(o,"utf-8")]);return Ao(e,i,"sha256")},B9=(n,r,o,i,e)=>{let a=Buffer.concat([n,...r,d9(o),Buffer.from(i,"utf-8")]);return Ao(a,e)},qm=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),Uk=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),Hk=2,Xh=n=>n?.data?.isMissingKey===!0,Q9=(n,r)=>r>=Hk||n?.name==="TypeError",f9=async({type:n,index:r,syncAction:o,apiVersion:i,operation:e},a,A,t)=>{let s=a?await t(a):void 0;if(!s)throw new Mi.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(r)),l=Ae.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),p=Ae.SyncActionData.encode(l).finish(),B=Zh(s.keyData),Q=bq(p,B.valueEncryptionKey),f=h9(e,Q,g,B.valueMacKey),y=Ao(c,B.indexKey),m=u9(A);m.mix({indexMac:y,valueMac:f,operation:e}),Object.assign(A,m.finish()),A.version+=1;let R=Lk(A.hash,A.version,n,B.snapshotMacKey),k={patchMac:B9(R,[f],A.version,n,B.patchMacKey),snapshotMac:R,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([Q,f])},keyId:{id:g}}}]},G=y.toString("base64");return A.indexValueMap[G]={valueMac:f},{patch:k,state:A}},y9=async(n,r,o,i,e)=>{let a=u9(r),A=new Map;for(let s of n){let g="operation"in s?s.operation:Ae.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,l;try{l=await t(c.keyId.id)}catch(R){if(Xh(R))throw R;continue}let p=c.value.blob,B=p.subarray(0,-32),Q=p.subarray(-32);if(e){let R=h9(g,B,c.keyId.id,l.valueMacKey);if(Buffer.compare(R,Q)!==0)continue}let f;try{f=Mq(B,l.valueEncryptionKey)}catch{continue}let y=Ae.SyncActionData.decode(f);if(e){let R=Ao(y.index,l.indexKey);if(Buffer.compare(R,c.index.blob)!==0)throw new Mi.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:Q,operation:g})}return a.finish();async function t(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let l=await o(g);if(!l)throw new Mi.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let p=Zh(l.keyData);return A.set(g,p),p}},BRe=async(n,r,o,i,e,a)=>{if(a){let t=Buffer.from(n.keyId.id).toString("base64"),s=await i(t);if(!s)throw new Mi.Boom(`failed to find key "${t}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=Zh(s.keyData),c=n.mutations.map(p=>p.record.value.blob.slice(-32)),l=B9(n.snapshotMac,c,or(n.version.version),r,g.patchMacKey);if(Buffer.compare(l,n.patchMac)!==0)throw new Mi.Boom("Invalid patch mac")}return await y9(n.mutations,o,i,e,a)},m9=async(n,r)=>{let o=ie(n,"sync"),i=mA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=ie(a,"patches"),t=mA(A||a,"patch"),s=ie(a,"snapshot"),g=[],c=a.attrs.name,l=a.attrs.has_more_patches==="true",p;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=Ae.ExternalBlobReference.decode(s.content),Q=await S9(B,r);p=Ae.SyncdSnapshot.decode(Q)}for(let{content:B}of t)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let Q=Ae.SyncdPatch.decode(B);Q.version||(Q.version={version:+a.attrs.version+1}),g.push(Q)}e[c]={patches:g,hasMorePatches:l,snapshot:p}})),e},S9=async(n,r)=>{let o=await nE(n,"md-app-state",{options:r}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},QRe=async(n,r)=>{let o=await S9(n,r);return Ae.SyncdMutations.decode(o)},D9=async(n,r,o,i,e=!0,a)=>{let A=qm();A.version=or(r.version.version);let t={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await y9(r.records,A,o,s?l=>{let p=l.syncAction.index?.toString();t[p]=l}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let l=Buffer.from(r.keyId.id).toString("base64"),p=await o(l);if(!p)throw new Mi.Boom(`failed to find key "${l}" to decode mutation`,{data:{isMissingKey:!0}});let B=Zh(p.keyData),Q=Lk(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(r.mac,Q)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:t}},Kk=async(n,r,o,i,e,a,A,t=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of r){let{version:l,keyId:p,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:l},"downloading external patch");let m=await QRe(c.externalMutations,e);A?.debug({name:n,version:l,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let Q=or(l.version);s.version=Q;let f=typeof a>"u"||Q>a,y;try{y=await BRe(c,n,s,i,f?m=>{let R=m.syncAction.index?.toString();g[R]=m}:()=>{},t)}catch(m){if(Xh(m))throw m;A?.warn({name:n,version:Q,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,t){let m=Buffer.from(p.id).toString("base64"),R=await i(m);if(!R)throw new Mi.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let k=Zh(R.keyData),G=Lk(s.hash,s.version,n,k.snapshotMacKey);if(Buffer.compare(B,G)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},w9=(n,r)=>{let o=Ae.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 Mi.Boom("Incomplete key",{statusCode:400,data:s});if(ir(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new Mi.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!or(s.messageTimestamp))throw new Mi.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=oA(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",r],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",r],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",r],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:t}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:t,messageTimestamp:a}},index:["deleteMessageForMe",r,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",r,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",r],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",r],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",r,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",r,"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:[Wo.Chat,n.addChatLabel.labelId,r],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Wo.Chat,n.removeChatLabel.labelId,r],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Wo.Message,n.addMessageLabel.labelId,r,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Wo.Message,n.removeMessageLabel.labelId,r,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new Mi.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},O9=(n,r,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:t},index:[s,g,c,l]}=n;if(t?.muteAction)r.emit("chats.update",[{id:g,muteEndTime:t.muteAction?.muted?or(t.muteAction.muteEndTimestamp):null,conditional:p(g,void 0)}]);else if(t?.archiveChatAction||s==="archive"||s==="unarchive"){let Q=t?.archiveChatAction,f=Q?Q.archived:s==="archive",y=A?.unarchiveChats?Q?.messageRange:void 0;r.emit("chats.update",[{id:g,archived:f,conditional:p(g,y)}])}else if(t?.markChatAsReadAction){let Q=t.markChatAsReadAction,f=a&&Q.read;r.emit("chats.update",[{id:g,unreadCount:f?null:Q?.read?0:-1,conditional:p(g,Q?.messageRange)}])}else if(t?.deleteMessageForMeAction||s==="deleteMessageForMe")r.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:l==="1"}]});else if(t?.contactAction){let Q=p9(t.contactAction,g,e);C9(r,Q)}else if(t?.pushNameSetting){let Q=t?.pushNameSetting?.name;Q&&o?.name!==Q&&r.emit("creds.update",{me:{...o,name:Q}})}else if(t?.pinAction)r.emit("chats.update",[{id:g,pinned:t.pinAction?.pinned?or(t.timestamp):null,conditional:p(g,void 0)}]);else if(t?.unarchiveChatsSetting){let Q=!!t.unarchiveChatsSetting.unarchiveChats;r.emit("creds.update",{accountSettings:{unarchiveChats:Q}}),e?.info(`archive setting updated => '${t.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=Q)}else if(t?.starAction||s==="star"){let Q=t?.starAction?.starred;typeof Q!="boolean"&&(Q=n.index[n.index.length-1]==="1"),r.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:l==="1"},update:{starred:Q}}])}else if(t?.deleteChatAction||s==="deleteChat")a||r.emit("chats.delete",[g]);else if(t?.labelEditAction){let{name:Q,color:f,deleted:y,predefinedId:m}=t.labelEditAction;r.emit("labels.edit",{id:g,name:Q,color:f,deleted:y,predefinedId:m?String(m):void 0})}else t?.labelAssociationAction?r.emit("labels.association",{type:t.labelAssociationAction.labeled?"add":"remove",association:s===Wo.Chat?{type:Wo.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:Wo.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):t?.localeSetting?.locale?r.emit("settings.update",{setting:"locale",value:t.localeSetting.locale}):t?.timeFormatAction?r.emit("settings.update",{setting:"timeFormat",value:t.timeFormatAction}):t?.pnForLidChatAction?t.pnForLidChatAction.pnJid&&r.emit("lid-mapping.update",{lid:g,pn:t.pnForLidChatAction.pnJid}):t?.privacySettingRelayAllCalls?r.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:t.privacySettingRelayAllCalls}):t?.statusPrivacy?r.emit("settings.update",{setting:"statusPrivacy",value:t.statusPrivacy}):t?.lockChatAction?r.emit("chats.lock",{id:g,locked:!!t.lockChatAction.locked}):t?.privacySettingDisableLinkPreviewsAction?r.emit("settings.update",{setting:"disableLinkPreviews",value:t.privacySettingDisableLinkPreviewsAction}):t?.notificationActivitySettingAction?.notificationActivitySetting?r.emit("settings.update",{setting:"notificationActivitySetting",value:t.notificationActivitySettingAction.notificationActivitySetting}):t?.lidContactAction?r.emit("contacts.upsert",[{id:g,name:t.lidContactAction.fullName||t.lidContactAction.firstName||t.lidContactAction.username||void 0,username:t.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):t?.privacySettingChannelsPersonalisedRecommendationAction?r.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:t.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function p(Q,f){return a?y=>{let m=y.historySets.chats[Q]||y.chatUpserts[Q];if(m)return f?B(m,f):!0}:void 0}function B(Q,f){let y=Number(f?.lastMessageTimestamp||f?.lastSystemMessageTimestamp||0),m=Number(Q?.lastMessageRecvTimestamp||0);return y>=m}};var fRe=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,r){let o=(...i)=>{this.off(n,o),r(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let r=this._eventListeners.get(n);return r?r.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,r){let o=this._eventListeners.get(n)??[];return o.unshift(r),this._eventListeners.set(n,o),this}prependOnceListener(n,r){let o=(...i)=>{this.off(n,o),r(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,r){return this.on(n,r),this}on(n,r){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(r)),this}removeListener(n,r){return this.off(n,r),this}off(n,r){let o=this._eventListeners.get(n)??[],i=o.indexOf(r);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...r){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...r),o=!0;if(n===this._errorEvent){let e=r[0]instanceof Error?r[0]:new Error(`${r[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,r),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 r of this._eventListeners.values())r.length>n&&r.splice(n)}getAllListeners(){let n=[];for(let r of this._eventListeners.values())n=[...n,...r];return n}sendLog(n,r){if(!this._logger)return;let o;switch(typeof r=="string"?o=r:Array.isArray(r)&&r.length>0&&r[0]instanceof Error?o=r[0].message:r instanceof Error?o=r.message:Array.isArray(r)&&r.length>0&&typeof r[0]?.message=="string"?o=r[0].message:o=JSON.stringify(r),n){case"error":{this._logger.error?.(o,{event:n,data:r});break}case"warn":{this._logger.warn?.(o,{event:n,data:r});break}case"trace":{this._logger.trace?.(o,{event:n,data:r});break}case"debug":{this._logger.debug?.(o,{event:n,data:r});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:r});break}default:{this._logger.info?.(o,{event:n,data:r});break}}}},ig=class extends fRe{_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 r=n.trim().toLocaleLowerCase();if(!r.startsWith("before")&&!r.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 r=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${r?`: ${r}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,r){this.onHookEntry({event:n,handler:r})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let r=this._hooks.get(n.event);r?r.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,r){this.onHookEntry({event:n,handler:r})}onHooks(n){for(let r of n)this.onHook(r.event,r.handler)}prependHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(r):this._hooks.set(n,[r])}prependOnceHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),r(...i));this.prependHook(n,o)}onceHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),r(...i));this.onHook(n,o)}removeHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(r);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let r of n)this.removeHook(r.event,r.handler)}async hook(n,...r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...r)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...r){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(...r)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...r){await this.hook(`before:${n}`,...r)}async afterHook(n,...r){await this.hook(`after:${n}`,...r)}async callHook(n,...r){await this.hook(n,...r)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var yRe=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,r){if(this._enabled){if(this._store.has(n)){this._store.set(n,r);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,r)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},mRe=class{get name(){return"crc32"}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;r=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)}},Vm=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let r=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}},SRe=class{get name(){return"djb2"}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;r=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)}},DRe=class{get name(){return"fnv1"}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;r=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)}},wRe=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;r=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=r.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,r){if(Math.imul)return Math.imul(n,r);let o=n>>>16&65535,i=n&65535,e=r>>>16&65535,a=r&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,r){return n<>>32-r}},ORe=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 r of n)this._providers.set(r.name,r)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,r){let o=r?.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)}},Yk=class extends ig{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new ORe;_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 yRe(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,r){let o={data:n,algorithm:r?.algorithm??this._defaultAlgorithm,maxLength:r?.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 l=c;r?.maxLength&&l.length>r.maxLength&&(l=l.substring(0,r.maxLength));let p={hash:l,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",p),p.hash}}let A=new TextEncoder().encode(i),t=this._providers.get(o.algorithm);t||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),t=new Vm({algorithm:this._defaultAlgorithm}));let s=await t.toHash(A);this._cache.enabled&&this._cache.set(e,s),r?.maxLength&&s.length>r?.maxLength&&(s=s.substring(0,r.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,r={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=r;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),t=Number.parseInt(A,16),s=i-o+1;return o+t%s}toHashSync(n,r){let o={data:n,algorithm:r?.algorithm??this._defaultAlgorithmSync,maxLength:r?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let l=this._cache.get(a);if(l!==void 0){let p=l;r?.maxLength&&p.length>r.maxLength&&(p=p.substring(0,r.maxLength));let B={hash:p,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let t=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(t);this._cache.enabled&&this._cache.set(a,g),r?.maxLength&&g.length>r?.maxLength&&(g=g.substring(0,r.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,r={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=r;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),t=Number.parseInt(A,16),s=i-o+1;return o+t%s}loadProviders(n,r={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);r.includeBase&&(this.providers.add(new Vm({algorithm:"SHA-256"})),this.providers.add(new Vm({algorithm:"SHA-384"})),this.providers.add(new Vm({algorithm:"SHA-512"})),this.providers.add(new mRe),this.providers.add(new SRe),this.providers.add(new DRe),this.providers.add(new wRe))}};var Jk=n=>{let r;if(n!==void 0){if(typeof n=="number")r=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":r=a;break;case"s":r=a*1e3;break;case"m":r=a*1e3*60;break;case"h":r=a*1e3*60*60;break;case"hr":r=a*1e3*60*60;break;case"d":r=a*1e3*60*60*24;break;default:r=Number(n)}}else r=Number(n)}return r}},Rc=(n,r)=>{r??=new Date;let o=Jk(n);return o===void 0?r.getTime():r.getTime()+o};var $h=(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 xk(n,r={algorithm:"djb2",serialize:JSON.stringify}){let o=r?.algorithm??"djb2",i=(r?.serialize??JSON.stringify)(n);return new Yk().toHashSync(i,{algorithm:o})}function M9(n,r={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=r?.min??0,i=r?.max??10,e=r?.algorithm??"djb2",a=r?.serialize??JSON.stringify,A=r?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let t=a(n);return new Yk().toNumberSync(t,{algorithm:e,min:o,max:i,hashLength:A})}function qk(n,r){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=r;return(...A)=>{let t=MRe(n,A,{keyPrefix:i,serialize:a});r.createKey&&(t=r.createKey(n,A,r));let s=e.get(t);if(s===void 0)try{s=n(...A),e.set(t,s,o)}catch(g){e.emit("error",g),r.cacheErrors&&e.set(t,g,o)}return s}}function Vk(n,r,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=r()}catch(a){throw new zm(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new zm(a,"store")}}catch(a){let A=a instanceof zm?a.context:void 0,t=a instanceof zm?a.error:a;if(o.cache.emit("error",t),o.cacheErrors&&A==="function")try{o.cache.set(i,t,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw t}return e}function MRe(n,r,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${xk(r,{serialize:e})}`:`${n.name}::${xk(r,{serialize:e})}`}var zm=class{error;context;constructor(n,r){this.error=n,this.context=r}};var og=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,r=1){this._enabled&&(this._counters[n]+=r,this.touch())}decrement(n,r=1){this._enabled&&(this._counters[n]-=r,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 r=[],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(r.includes(e))continue;r.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,r,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[r]+=o,this.touch()}mostUsedKeys(n=100,r){return this.sortedKeyEntries(r,"desc").slice(0,n)}leastUsedKeys(n=100,r){return this.sortedKeyEntries(r,"asc").slice(0,n)}keyStats(n){let r=this._trackedKeys.get(n);return r?this.toKeyEntry(n,r):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,r){let o=r.hits+r.misses;return{key:n,count:this.totalOf(r),hits:r.hits,misses:r.misses,gets:r.gets,sets:r.sets,deletes:r.deletes,hitRate:o===0?0:r.hits/o}}sortedKeyEntries(n,r){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=r==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,t=n?a[n]:a.count;return A!==t?(A-t)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=r)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,r){for(let[o,i]of Object.entries(r)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let r=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){r.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=r}applyEvent(n,r){if(this._enabled){if(typeof n=="function"){n(this,...r);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var bRe=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},zk=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let r=new bRe(n);this.head?(r.next=this.head,this.head.prev=r,this.head=r):this.head=this.tail=r,this.nodesMap.set(n,r)}moveToFront(n){let r=this.nodesMap.get(n);if(!r||this.head===r)return;r.prev&&(r.prev.next=r.next);r.next&&(r.next.prev=r.prev);r===this.tail&&(this.tail=r.prev),r.prev=void 0,r.next=this.head;this.head&&(this.head.prev=r),this.head=r,this.tail??=r}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 r=this.nodesMap.get(n);return r?(r.prev?r.prev.next=r.next:(this.head=r.next,this.head&&(this.head.prev=void 0)),r.next?r.next.prev=r.prev:(this.tail=r.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var b9=16777216,Wk=class extends ig{_lru=new zk;_storeHashSize=16;_storeHashAlgorithm=$h.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new og({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 ${b9} 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 ${b9} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new zk;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let r of this._store)n+=r.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 r of this._store)for(let o of r.keys()){let i=r.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),r.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let r of this._store)for(let o of r.values()){if(this.hasExpired(o)){this.recordExpiration(o),r.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 r=this.getStore(n),o=r.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),r.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 r=[];for(let o of n)r.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:r}),r}getRaw(n){let r=this.getStore(n),o=r.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),r.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let r=[];for(let o of n)r.push(this.getRaw(o));return r}set(n,r,o){let i={key:n,value:r,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=Rc(A.ttl);s!==void 0&&(a=s)}}else{let s=Rc(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=Rc(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 t={key:i.key,value:i.value,expires:a};e.set(i.key,t),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let r of n)this.set(r.key,r.value,r.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let r=[];for(let o of n){let i=this.get(o);r.push(!!i)}return r}take(n){let r=this.get(n);if(r)return this.delete(n),r}takeMany(n){let r=[];for(let o of n)r.push(this.take(o));return r}delete(n){this.hookSync("BEFORE_DELETE",n);let r=this.getStore(n);if(this._stats.enabled){let o=r.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}r.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let r of n)this.delete(r);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new zk,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let r=this.getKeyStoreHash(n);return this._store[r]||=new Map,this._store[r]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):M9(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 r of n.values())r.expires&&Date.now()>r.expires&&(this.recordExpiration(r),n.delete(r.key),this.lruRemove(r.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,r){return qk(n,{ttl:r?.ttl??this._ttl,keyPrefix:r?.keyPrefix,createKey:r?.createKey,cache:this})}getOrSet(n,r,o){return Vk(n,r,{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 PRe=class extends ig{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new og({enabled:!0});_cacheable=new Wk;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,r,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:r,ttl:a}),this.emit("set",i,r,e),this._stats.incrementKSize(i),this._stats.incrementVSize(r),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 r of n)this.set(r.key,r.value,r.ttl);return!0}get(n){let r=this.store.get(this.formatKey(n));if(r){if(r.ttl>0){if(r.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 Rc(n);let r=Date.now(),o=n*1e3;return r+o}checkData(){for(let[n,r]of this.store.entries())r.ttl>0&&r.ttl{let a={resolve:i,reject:e,weight:r,priority:o},A=N9(this._queue,t=>o<=t.priority);A===-1&&r<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(r){return FRe(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(r=1,o=0){if(r<=0)throw new Error(`invalid weight ${r}: must be positive`);return this._couldLockImmediately(r,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[r-1]||(this._weightedWaiters[r-1]=[]),LRe(this._weightedWaiters[r-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(r){this._value=r,this._dispatchQueue()}release(r=1){if(r<=0)throw new Error(`invalid weight ${r}: must be positive`);this._value+=r,this._dispatchQueue()}cancel(){this._queue.forEach(r=>r.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(r){let o=this._value;this._value-=r.weight,r.resolve([o,this._newReleaser(r.weight)])}_newReleaser(r){let o=!1;return()=>{o||(o=!0,this.release(r))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let r=this._value;r>0;r--){let o=this._weightedWaiters[r-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[r-1]=[])}else{let r=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<=r);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(r,o){return(this._queue.length===0||this._queue[0].priorityr.priority<=i.priority);n.splice(o+1,0,r)}function N9(n,r){for(let o=n.length-1;o>=0;o--)if(r(n[o]))return o;return-1}var URe=function(n,r,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 t(c){try{g(i.next(c))}catch(l){A(l)}}function s(c){try{g(i.throw(c))}catch(l){A(l)}}function g(c){c.done?a(c.value):e(c.value).then(t,s)}g((i=i.apply(n,r||[])).next())})},jn=class{constructor(r){this._semaphore=new Zk(1,r)}acquire(){return URe(this,arguments,void 0,function*(r=0){let[,o]=yield this._semaphore.acquire(1,r);return o})}runExclusive(r,o=0){return this._semaphore.runExclusive(()=>r(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(r=0){return this._semaphore.waitForUnlock(1,r)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as jRe}from"crypto";var $k=Le(R9(),1);var ev=class n extends Error{name="TimeoutError";constructor(r,o){super(r,o),Error.captureStackTrace?.(this,n)}},k9=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function Av(n,r){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=r,t,s,c=new Promise((l,p)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){p(k9(A));return}if(A&&(s=()=>{p(k9(A))},A.addEventListener("abort",s,{once:!0})),n.then(l,p),o===Number.POSITIVE_INFINITY)return;let B=new ev;t=a.setTimeout.call(void 0,()=>{if(i){try{l(i())}catch(Q){p(Q)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?l():e instanceof Error?p(e):(B.message=e??`Promise timed out after ${o} milliseconds`,p(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,t),t=void 0},c}function tv(n,r,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],r)<=0?(i=++A,e-=a+1):e=a}return i}var YRe=100,gE=class{#e=[];#A=0;enqueue(r,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:r};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 t=tv(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(t,0,A)}setPriority(r,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===r);if(i===-1)throw new ReferenceError(`No promise function with the id "${r}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:r})}remove(r){let o=this.#e.findIndex((i,e)=>eYRe&&this.#A>this.#e.length/2&&this.#t(),r?.run}filter(r){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${r.intervalCap?.toString()??""}\` (${typeof r.intervalCap})`);if(r.interval===void 0||!(Number.isFinite(r.interval)&&r.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${r.interval?.toString()??""}\` (${typeof r.interval})`);if(r.strict&&r.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(r.strict&&r.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=r.carryoverIntervalCount??r.carryoverConcurrencyCount??!1,this.#A=r.intervalCap===Number.POSITIVE_INFINITY||r.interval===0,this.#r=r.intervalCap,this.#E=r.interval,this.#i=r.strict,this.#l=new r.queueClass,this.#p=r.queueClass,this.concurrency=r.concurrency,r.timeout!==void 0&&!(Number.isFinite(r.timeout)&&r.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${r.timeout}\` (${typeof r.timeout})`);this.timeout=r.timeout,this.#d=r.autoStart===!1,this.#K()}#y(r){for(;this.#c=this.#E)this.#c++;else break}(this.#c>100&&this.#c>this.#o.length/2||this.#c===this.#o.length)&&(this.#o=this.#o.slice(this.#c),this.#c=0)}#f(r){this.#i?this.#o.push(r):this.#t++}#D(){this.#i?this.#o.length>this.#c&&this.#o.pop():this.#t>0&&this.#t--}#m(){return this.#o.length-this.#c}get#w(){return this.#A?!0:this.#i?this.#m()=this.#r){let i=this.#o[this.#c],e=this.#E-(r-i);return this.#F(e),!0}return!1}if(this.#I===void 0){let o=this.#s-r;if(o<0)this.#t=this.#e?this.#h:0;else return this.#F(o),!0}return!1}#F(r){this.#a===void 0&&(this.#a=setTimeout(()=>{this.#O()},r))}#T(){this.#I&&(clearInterval(this.#I),this.#I=void 0)}#L(){this.#a&&(clearTimeout(this.#a),this.#a=void 0)}#k(){if(this.#l.size===0){if(this.#T(),this.emit("empty"),this.#h===0){if(this.#L(),this.#i&&this.#c>0){let o=Date.now();this.#y(o)}this.emit("idle")}return!1}let r=!1;if(!this.#d){let o=Date.now(),i=!this.#M(o);if(this.#w&&this.#N){let e=this.#l.dequeue();this.#A||(this.#f(o),this.#G()),i&&this.#v(),this.emit("active"),e(),r=!0}}return r}#v(){this.#A||this.#I!==void 0||this.#i||(this.#I=setInterval(()=>{this.#b()},this.#E),this.#s=Date.now()+this.#E)}#b(){this.#i||(this.#I!==void 0&&(this.#t===0&&this.#h===0?this.#T():this.#s=Date.now()+this.#E),this.#t=this.#e?this.#h:0),this.#P(),this.#G()}#P(){for(;this.#k(););}get concurrency(){return this.#C}set concurrency(r){if(!(typeof r=="number"&&r>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${r}\` (${typeof r})`);this.#C=r,this.#P()}setPriority(r,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#l.setPriority(r,o)}async add(r,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#Q++).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=()=>{},t=async()=>{A(),this.#h++,this.#u.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(p){throw this.#H(),this.#u.delete(a),p}let c=r({signal:o.signal});if(o.timeout!==void 0&&(c=Av(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#h} running, ${this.#l.size} waiting)`})),o.signal){let{signal:p}=o;c=Promise.race([c,new Promise((B,Q)=>{g=()=>{Q(p.reason)},p.addEventListener("abort",g,{once:!0})})])}let l=await c;i(l),this.emit("completed",l)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#u.delete(a),queueMicrotask(()=>{this.#S()})}};this.#l.enqueue(t,o);let s=()=>{if(this.#l instanceof gE){this.#l.remove(t);return}this.#l.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#k(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#B.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#B.add(A)}this.emit("add"),this.#k()})}async addAll(r,o){return Promise.all(r.map(async i=>this.add(i,o)))}start(){return this.#d?(this.#d=!1,this.#P(),this):this}pause(){this.#d=!0}clear(){for(let r of this.#B)r();this.#l=new this.#p,this.#T(),this.#Y(),this.emit("empty"),this.#h===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#l.size!==0&&await this.#R("empty")}async onSizeLessThan(r){this.#l.sizethis.#l.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#R(r,o){let i=Array.isArray(r)?r:[r];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.#l.size}sizeBy(r){return this.#l.filter(r).length}get pending(){return this.#h}get isPaused(){return this.#d}#K(){this.#A||(this.on("add",()=>{this.#l.size>0&&this.#G()}),this.on("next",()=>{this.#G()}))}#G(){this.#A||this.#n||(this.#n=!0,queueMicrotask(()=>{this.#n=!1,this.#Y()}))}#H(){this.#A||(this.#D(),this.#G())}#Y(){let r=this.#g;if(this.#A||this.#l.size===0){r&&(this.#g=!1,this.emit("rateLimitCleared"));return}let o;if(this.#i){let e=Date.now();this.#y(e),o=this.#m()}else o=this.#t;let i=o>=this.#r;i!==r&&(this.#g=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#g}get isSaturated(){return this.#h===this.#C&&this.#l.size>0||this.isRateLimited&&this.#l.size>0}get runningTasks(){return[...this.#u.values()].map(r=>({...r,timeoutRemaining:r.timeout?Math.max(0,r.startTime+r.timeout-Date.now()):void 0}))}};var Zm=class{constructor(r,o){this.store=r,this.logger=o,this.queues=new Map}getQueue(r){return this.queues.has(r)||this.queues.set(r,new kc({concurrency:1})),this.queues.get(r)}async processOperations(r,o,i,e,a){let A=r[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let t=[],s={};for(let g in A)A[g]===null?t.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),t.length>0&&await this.processDeletions(o,t,i,e,a)})}async processDeletions(r,o,i,e,a){if(a)for(let A of o)i[r]?.[A]?(i[r][A]=null,e[r][A]=null):this.logger.warn(`Skipping deletion of non-existent ${r} in transaction: ${A}`);else{let A=await this.store.get(r,o);for(let t of o)A[t]?(i[r][t]=null,e[r][t]=null):this.logger.warn(`Skipping deletion of non-existent ${r}: ${t}`)}}async validateDeletions(r,o){let i=r[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 r[o][A])})}};var P9=(n,r,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new xRe,a=new Map,A=new Map,t=new Map,s=new Zm(n,r);function g(f){return a.has(f)||a.set(f,new kc({concurrency:1})),a.get(f)}function c(f){return A.has(f)||(A.set(f,new jn),t.set(f,0)),A.get(f)}function l(f){let y=t.get(f)??0;t.set(f,y+1)}function p(f){let y=(t.get(f)??1)-1;if(t.set(f,y),y<=0){let m=A.get(f);m&&!m.isLocked()&&(A.delete(f),t.delete(f))}}function B(){return!!e.getStore()}async function Q(f){if(Object.keys(f).length===0){r.trace("no mutations in transaction");return}r.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(f,y);let R=m.cache[f]||{},k=y.filter(K=>!(K in R));if(k.length>0){m.dbQueries++,r.trace({type:f,count:k.length},"fetching missing keys in transaction");let K=await c(f).runExclusive(()=>n.get(f,k));m.cache[f]=m.cache[f]||{},Object.assign(m.cache[f],K)}let G={};for(let K of y){let x=m.cache[f]?.[K];x!=null&&(G[K]=x)}return G},set:async f=>{let y=e.getStore();if(!y){let m=Object.keys(f);for(let R of m){let k=R;k==="pre-key"&&await s.validateDeletions(f,k)}await Promise.all(m.map(R=>g(R).add(async()=>{let k={[R]:f[R]};await n.set(k)})));return}r.trace({types:Object.keys(f)},"caching in transaction");for(let m in f){let R=m;y.cache[R]=y.cache[R]||{},y.mutations[R]=y.mutations[R]||{},R==="pre-key"?await s.processOperations(f,R,y.cache,y.mutations,!0):(Object.assign(y.cache[R],f[R]),Object.assign(y.mutations[R],f[R]))}},isInTransaction:B,transaction:async(f,y)=>{if(e.getStore())return r.trace("reusing existing transaction context"),f();let R=c(y);l(y);try{return await R.runExclusive(async()=>{let k={cache:{},mutations:{},dbQueries:0};r.trace("entering transaction");try{let G=await e.run(k,f);return await Q(k.mutations),r.trace({dbQueries:k.dbQueries},"transaction completed"),G}catch(G){throw r.error({error:G},"transaction failed, rolling back"),G}})}finally{p(y)}}}},G9=n=>{let r=n.me?.id;if(!r)throw new v9.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return r},F9=()=>{let n=Ut.generateKeyPair();return{noiseKey:Ut.generateKeyPair(),pairingEphemeralKeyPair:Ut.generateKeyPair(),signedIdentityKey:n,signedPreKey:Ff(n,1),registrationId:vq(),advSecretKey:jRe(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 JRe,readFile as qRe,stat as VRe,unlink as zRe,writeFile as WRe}from"fs/promises";import{join as rv}from"path";var L9=new Map,av=n=>{let r=L9.get(n);return r||(r=new jn,L9.set(n,r)),r},U9=async n=>{let r=async(t,s)=>{let g=rv(n,a(s));return av(g).acquire().then(async l=>{try{await WRe(g,JSON.stringify(t,WC.replacer))}finally{l()}})},o=async t=>{try{let s=rv(n,a(t));return await av(s).acquire().then(async c=>{try{let l=await qRe(s,{encoding:"utf-8"});return JSON.parse(l,WC.reviver)}finally{c()}})}catch{return null}},i=async t=>{try{let s=rv(n,a(t));return av(s).acquire().then(async c=>{try{await zRe(s)}catch{}finally{c()}})}catch{}},e=await VRe(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 JRe(n,{recursive:!0});let a=t=>t?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||F9();return{state:{creds:A,keys:{get:async(t,s)=>{let g={};return await Promise.all(s.map(async c=>{let l=await o(`${t}-${c}.json`);t==="app-state-sync-key"&&l&&(l=Ae.Message.AppStateSyncKeyData.fromObject(l)),g[c]=l})),g},set:async t=>{let s=[];for(let g in t)for(let c in t[g]){let l=t[g][c],p=`${g}-${c}.json`;s.push(l?r(l,p):i(p))}await Promise.all(s)}}},saveCreds:async()=>r(A,"creds.json")}};var ZRe=192,XRe=async(n,{thumbnailWidth:r,fetchOpts:o})=>{let i=await Km(n,o);return await Sk(i,r)},H9=async(n,r={thumbnailWidth:ZRe,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,{...r.fetchOpts,followRedirects:"follow",handleRedirects:(t,s)=>{let g=new URL(t),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:r.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[t]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:t};if(r.uploadImage){let{imageMessage:g}=await Jh({image:{url:t}},{upload:r.uploadImage,mediaTypeOverride:"thumbnail-link",options:r.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=t?(await XRe(t,r)).buffer:void 0}catch(g){r.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 ske from"events";var ov=Le(ar(),1);var $Re=/^1313555\d{4}$|^131655500\d{2}$/;function eke(n){if(!n)return!1;let r=n.split("@")[0]??"";return r==="0"||$Re.test(r)||gl(n)?!1:!!(nt(n)||vA(n)||Lt(n)||yr(n)||n.endsWith("@c.us"))}var Xm=604800,Ake=4,sg="__index";async function $m(n){let o=(await n.get("tctoken",[sg]))[sg];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!==sg):[]}catch{return[]}}async function cE(n,r){let o=await $m(n),i=new Set(o);for(let e of r)e&&e!==sg&&i.add(e);return{[sg]:{token:Buffer.from(JSON.stringify([...i]))}}}function vc(n){if(n==null)return!0;let r=typeof n=="string"?parseInt(n):n;if(isNaN(r))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/Xm)-(Ake-1))*Xm;return ri}async function Zo(n,r){return vA(n)?n:await r(n)??n}async function Ad(n,r,o,i){return r?vA(n)?n:await o(n)??n:vA(n)&&i?await i(n)??n:n}async function iv({authState:n,jid:r,baseContent:o=[],getLIDForPN:i}){try{let e=await Zo(r,i),A=(await n.keys.get("tctoken",[e]))?.[e],t=A?.token,s=A?.timestamp;if(!t?.length||s===void 0||vc(s)){if(t){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:t}),o}catch{return o.length>0?o:void 0}}async function IE({result:n,fallbackJid:r,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=ie(n,"tokens");if(!a)return;let A=mA(a,"token");for(let t of A){if(t.attrs.type!=="trusted_contact"||!(t.content instanceof Uint8Array))continue;let s=oA(r||t.attrs.jid);if(!eke(s))continue;let g=await Zo(s,i),l=(await o.get("tctoken",[g]))[g],p=l?.timestamp?Number(l.timestamp):0,B=t.attrs.t?Number(t.attrs.t):0;B&&(p>0&&p>B||(await o.set({tctoken:{[g]:{...l,token:Buffer.from(t.content),timestamp:t.attrs.t}}}),e?.(g)))}}var tke=new Set([QA.CALL_MISSED_GROUP_VIDEO,QA.CALL_MISSED_GROUP_VOICE,QA.CALL_MISSED_VIDEO,QA.CALL_MISSED_VOICE]),rke=new Set([QA.GROUP_PARTICIPANT_ADD]);async function ake(n,r,o,i){let e=r.lidMapping.getLIDForPN.bind(r.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?or(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let l=oA(g.id),p=await Zo(l,e);a.push({storageJid:p,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?or(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),t=await o.get("tctoken",A),s={};for(let g of a){let c=t[g.storageJid],l=c?.timestamp?Number(c.timestamp):0;l>0&&l>=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 cE(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Y9=(n,r,o)=>{Lt(n.key.remoteJid)||yr(n.key.remoteJid)?n.key.remoteJid=Ft(lA(n.key?.remoteJid)?.user,Lt(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=oA(n.key.remoteJid),Lt(n.key.participant)||yr(n.key.participant)?n.key.participant=Ft(lA(n.key.participant)?.user,Lt(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=oA(n.key.participant);let i=Hr(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:lt(a.participant||a.remoteJid,r)||lt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},nv=n=>{let r=Hr(n.message),o=!!qh(r);return(!!r||tke.has(n.messageStubType)||rke.has(n.messageStubType))&&o&&!r?.protocolMessage&&!r?.reactionMessage&&!r?.pollUpdateMessage},sv=n=>!n.key.fromMe&&!n.messageStubType,ike=({remoteJid:n,participant:r,fromMe:o})=>{if(!n)throw new ov.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:r,fromMe:o}});if(HC(n)&&!_n(n)&&!o){if(!r)throw new ov.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return r}return n};function oke({encPayload:n,encIv:r},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([l(i),l(o),l(a),l("Event Response"),new Uint8Array([1])]),t=Ao(e,new Uint8Array(32),"sha256"),s=Ao(A,t,"sha256"),g=l(`${i}\0${a}`),c=gc(n,s,r,g);return Ae.Message.EventResponseMessage.decode(c);function l(p){return Buffer.from(p)}}var nke=async(n,{shouldProcessHistoryMsg:r,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:t,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:l}=e,p={id:oA(ike(n.key))},B=nv(n);B&&(p.messages=[{message:n}],p.conversationTimestamp=or(n.messageTimestamp),sv(n)&&(p.unreadCount=(p.unreadCount||0)+1));let Q=Hr(n.message);(B||Q?.reactionMessage?.key?.fromMe)&&l?.unarchiveChats&&(p.archived=!1,p.readOnly=!1);let f=Q?.protocolMessage;if(f){let y=new Set([Ae.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,Ae.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,Ae.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,Ae.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(f.type!==null&&f.type!==void 0&&y.has(f.type)&&!n.key.fromMe){t?.warn({msgId:n.key.id,type:f.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(f.type){case Ae.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=f.historySyncNotification,R=r,k=!e.processedHistoryMessages?.length;if(t?.info({histNotification:m,process:R,id:n.key.id,isLatest:k},"got history notification"),R){m.syncType!==Ae.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let T=await l9(m,s,t);T.lidPnMappings?.length&&(t?.debug({count:T.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(T.lidPnMappings).catch(V=>t?.warn({err:V},"failed to store LID-PN mappings from history sync"))),await ake(T.chats,a,A,t),i.emit("messaging-history.set",{...T,isLatest:m.syncType!==Ae.HistorySync.HistorySyncType.ON_DEMAND?k:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case Ae.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let G=f.appStateSyncKeyShare.keys;if(G?.length){let T="";await A.transaction(async()=>{let V=[];for(let{keyData:U,keyId:b}of G){let L=Buffer.from(b.keyId).toString("base64");V.push(L),await A.set({"app-state-sync-key":{[L]:U}}),T=L}t?.info({newAppStateSyncKeyId:T,newKeys:V},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:T})}else t?.info({protocolMsg:f},"recv app state sync with 0 keys");break;case Ae.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:f.key.id},update:{message:null,messageStubType:QA.REVOKE,key:n.key}}]);break;case Ae.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(p,{ephemeralSettingTimestamp:or(n.messageTimestamp),ephemeralExpiration:f.ephemeralExpiration||null});break;case Ae.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let K=f.peerDataOperationRequestResponseMessage;if(K){let T=K.peerDataOperationResult||[];for(let V of T){let U=V?.placeholderMessageResendResponse;if(U?.webMessageInfoBytes)try{let b=Ae.WebMessageInfo.decode(U.webMessageInfoBytes),L=b.key?.id,X=L?await o?.get(L):void 0;L&&await o?.del(L);let pe;X&&typeof X=="object"?(X.message=b.message,b.messageTimestamp&&(X.messageTimestamp=b.messageTimestamp),pe=X):pe=b,t?.debug({msgId:L,requestId:K.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[pe],type:"notify",requestId:K.stanzaId})}catch(b){t?.warn({err:b,stanzaId:K.stanzaId},"failed to decode placeholder resend response")}}}break;case Ae.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:f.key?.id},update:{message:{editedMessage:{message:f.editedMessage}},messageTimestamp:f.timestampMs?Math.floor(or(f.timestampMs)/1e3):n.messageTimestamp}}]);break;case Ae.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let x=f.memberLabel;x?.label&&i.emit("group.member-tag.update",{groupId:p.id,label:x.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case Ae.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let H=f.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:j}=Ae.LIDMigrationMappingSyncPayload.decode(H);t?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:j},"got lid mappings and chat db migration timestamp");let F=[];for(let{pn:T,latestLid:V,assignedLid:U}of q){let b=V||U;F.push({lid:`${b}@lid`,pn:`${T}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(F),F.length)for(let{pn:T,lid:V}of F)await a.migrateSession(T,V)}}else if(Q?.reactionMessage){let y={...Q.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:Q.reactionMessage?.key}])}else if(Q?.encEventResponseMessage){let y=Q.encEventResponseMessage,m=y.eventCreationMessageKey,R=await g(m);if(R)try{let k=oA(c),G=m.participant||m.remoteJid,K=vA(G)?await a.lidMapping.getPNForLID(G):G,x=Cl({remoteJid:oA(K),fromMe:k===K},k),H=Cl(n.key,k),q=R?.messageContextInfo?.messageSecret;if(!q)t?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let j=oke(y,{eventEncKey:q,eventCreatorJid:x,eventMsgId:m.id,responderJid:H}),F={eventResponseMessageKey:n.key,senderTimestampMs:j.timestampMs,response:j};i.emit("messages.update",[{key:m,update:{eventResponses:[F]}}])}}catch(k){t?.warn({err:k,creationMsgKey:m},"failed to decrypt event response")}else t?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,R=x=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:x}),k=x=>{i.emit("groups.update",[{id:y,...x,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},G=(x,H,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:x.lid,participantPn:x.pn,action:H,method:q})},K=()=>m.find(x=>lt(c,x.phoneNumber));switch(n.messageStubType){case QA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("modify");break;case QA.GROUP_PARTICIPANT_LEAVE:case QA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("remove"),K()&&(p.readOnly=!0);break;case QA.GROUP_PARTICIPANT_ADD:case QA.GROUP_PARTICIPANT_INVITE:case QA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],K()&&(p.readOnly=!1),R("add");break;case QA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("demote");break;case QA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("promote");break;case QA.GROUP_CHANGE_ANNOUNCE:let x=n.messageStubParameters?.[0];k({announce:x==="true"||x==="on"});break;case QA.GROUP_CHANGE_RESTRICT:let H=n.messageStubParameters?.[0];k({restrict:H==="true"||H==="on"});break;case QA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];p.name=q,k({subject:q});break;case QA.GROUP_CHANGE_DESCRIPTION:let j=n.messageStubParameters?.[0];p.description=j,k({desc:j});break;case QA.GROUP_CHANGE_INVITE_LINK:let F=n.messageStubParameters?.[0];k({inviteCode:F});break;case QA.GROUP_MEMBER_ADD_MODE:let T=n.messageStubParameters?.[0];k({memberAddMode:T==="all_member_add"});break;case QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let V=n.messageStubParameters?.[0];k({joinApprovalMode:V==="on"});break;case QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let U=JSON.parse(n.messageStubParameters?.[0]),b=n.messageStubParameters?.[1],L=n.messageStubParameters?.[2];G(U,b,L);break}}Object.keys(p).length>1&&i.emit("chats.update",[p])},x9=nke;var gke=["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"],cke=new Set(gke),j9=n=>{let r=new ske,o=new Set,i=gv(),e=!1,a=null,A=null,t=0,s=1e4,g=3e4;r.on("event",p=>{for(let B in p)r.emit(B,p[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,t=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),l())},g)),t++}function l(){if(!e)return!1;n.debug({bufferCount:t},"Flushing event buffer"),e=!1,t=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 p=gv(),B=Object.values(i.chatUpdates),Q=0;for(let y of B)y.conditional&&(Q+=1,p.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let f=lke(i);return Object.keys(f).length&&r.emit("event",f),i=p,n.trace({conditionalChatUpdatesLeft:Q},"released buffered events"),!0}return{process(p){let B=async Q=>{await p(Q)};return r.on("event",B),()=>{r.off("event",B)}},emit(p,B){if(p==="messages.upsert"){let{type:Q}=B,f=Object.values(i.messageUpserts);if(f.length>0){let y=f[0].type;y!==Q&&(n.debug({bufferedType:y,newType:Q},"messages.upsert type mismatch, emitting buffered messages"),r.emit("event",{"messages.upsert":{messages:f.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&cke.has(p)?(Ike(i,o,p,B,n),!0):r.emit("event",{[p]:B})},isBuffering(){return e},buffer:c,flush:l,createBufferedFunction(p){return async(...B)=>{c();try{let Q=await p(...B);return t===1&&setTimeout(()=>{e&&t===1&&l()},100),Q}catch(Q){throw Q}finally{t=Math.max(0,t-1),t===0&&(A||(A=setTimeout(l,100)))}}},on:(...p)=>r.on(...p),off:(...p)=>r.off(...p),removeAllListeners:(...p)=>r.removeAllListeners(...p),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=gv(),e=!1,t=0,r.removeAllListeners(),n.debug("Event buffer destroyed")}}},gv=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function Ike(n,r,o,i,e){switch(o){case"messaging-history.set":for(let f of i.chats){let y=f.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=f.endOfHistoryTransferType),!m&&!r.has(y)&&(n.historySets.chats[y]=f,r.add(y),a(f))}for(let f of i.contacts){let y=n.historySets.contacts[f.id];if(y)Object.assign(y,Hf(f));else{let m=`c:${f.id}`,R=f.notify||f.name||f.verifiedName;(!r.has(m)||R)&&(n.historySets.contacts[f.id]=f,r.add(m))}}for(let f of i.messages){let y=lE(f.key);!n.historySets.messages[y]&&!r.has(y)&&(n.historySets.messages[y]=f,r.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let f=new Map,y=R=>`${R.userJid||""}:${R.leaveTs||""}:${R.leaveReason||""}`,m=R=>{let k=R.groupJid??JSON.stringify(R),G=f.get(k);if(!G){f.set(k,{...R,pastParticipants:[...R.pastParticipants||[]]});return}let K=new Set((G.pastParticipants||[]).map(y));for(let x of R.pastParticipants||[]){let H=y(x);K.has(H)||(G.pastParticipants.push(x),K.add(H))}};for(let R of n.historySets.pastParticipants||[])m(R);for(let R of i.pastParticipants)m(R);n.historySets.pastParticipants=[...f.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 f of i){let y=f.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=eS(m,f):(m=f,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let f of i){let y=f.id,m=f.conditional?f.conditional(n):!0;if(m){delete f.conditional;let R=n.historySets.chats[y]||n.chatUpserts[y];if(R)eS(R,f);else{let k=n.chatUpdates[y]||{};n.chatUpdates[y]=eS(k,f)}}else m===void 0&&(n.chatUpdates[y]=f);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let f of i)n.chatDeletes.has(f)||n.chatDeletes.add(f),n.chatUpdates[f]&&delete n.chatUpdates[f],n.chatUpserts[f]&&delete n.chatUpserts[f],n.historySets.chats[f]&&delete n.historySets.chats[f];break;case"contacts.upsert":for(let f of i){let y=n.contactUpserts[f.id];y||(y=n.historySets.contacts[f.id],y&&e.debug({contactId:f.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,Hf(f)):(y=f,n.contactUpserts[f.id]=y),n.contactUpdates[f.id]&&(y=Object.assign(n.contactUpdates[f.id],Hf(f)),delete n.contactUpdates[f.id])}break;case"contacts.update":let t=i;for(let f of t){let y=f.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,f);else{let R=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(R,f)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let f of s){let y=lE(f.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(f.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(f,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=f:n.messageUpserts[y]={message:f,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:f,update:y}of c){let m=lE(f),R=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(R)Object.assign(R,y),y.status===sl.READ&&!f.fromMe&&A(R);else{let k=n.messageUpdates[m]||{key:f,update:{}};Object.assign(k.update,y),n.messageUpdates[m]=k}}break;case"messages.delete":let l=i;if("keys"in l){let{keys:f}=l;for(let y of f){let m=lE(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 p=i;for(let{key:f,reaction:y}of p){let m=lE(f),R=n.messageUpserts[m];R?Tk(R.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:f,reactions:[]},Tk(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:f,receipt:y}of B){let m=lE(f),R=n.messageUpserts[m];R?Nk(R.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:f,userReceipt:[]},Nk(n.messageReceipts[m],y))}break;case"groups.update":let Q=i;for(let f of Q){let y=f.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,f))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(t){let s=t.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(t,eS(g,t)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(t){let s=t.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];nv(t)&&sv(t)&&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 lke(n){let r={};n.historySets.empty||(r["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&&(r["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(r["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(r["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;r["messages.upsert"]={messages:a.map(Q=>Q.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(r["messages.update"]=A);let t=Object.values(n.messageDeletes);t.length&&(r["messages.delete"]={keys:t});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:Q})=>Q.flatMap(f=>({key:B,reaction:f})));s.length&&(r["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:Q})=>Q.flatMap(f=>({key:B,receipt:f})));g.length&&(r["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(r["contacts.upsert"]=c);let l=Object.values(n.contactUpdates);l.length&&(r["contacts.update"]=l);let p=Object.values(n.groupUpdates);return p.length&&(r["groups.update"]=p),r}function eS(n,r){return r.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,r.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof r.unreadCount=="number"&&(r={...r},r.unreadCount>=0&&(r.unreadCount=Math.max(r.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,r)}var lE=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var Eke=512,cv="\0",J9=3600*1e3,pke=3e3,Jn;(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"})(Jn||(Jn={}));var q9=new Set([Jn.SignalErrorInvalidMessage,Jn.SignalErrorBadMac]),AS=class{constructor(r,o){this.logger=r,this.recentMessagesMap=new Mn({max:Eke,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(cv);if(a>-1){let A=e.slice(a+cv.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Mn({ttl:J9*2,ttlAutopurge:!0}),this.retryCounters=new Mn({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Mn({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(r,o,i){let e={to:r,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: ${r}/${o}`)}getRecentMessage(r,o){let i={to:r,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(r,o,i){if(!o)return this.sessionRecreateHistory.set(r,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&q9.has(i))return this.sessionRecreateHistory.set(r,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:r,errorCode:Jn[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${Jn[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(r);return!a||e-a>J9?(this.sessionRecreateHistory.set(r,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(r){if(r===void 0||r==="")return;let o=parseInt(r,10);if(!Number.isNaN(o))return o>=Jn.UnknownError&&o<=Jn.StatusRevokeDelay?o:Jn.UnknownError}isMacError(r){return r!==void 0&&q9.has(r)}incrementRetryCount(r){return this.retryCounters.set(r,(this.retryCounters.get(r)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(r)}getRetryCount(r){return this.retryCounters.get(r)||0}hasExceededMaxRetries(r){return this.getRetryCount(r)>=this.maxMsgRetryCount}markRetrySuccess(r){this.statistics.successfulRetries++,this.retryCounters.delete(r),this.cancelPendingPhoneRequest(r),this.removeRecentMessage(r)}markRetryFailed(r){this.statistics.failedRetries++,this.retryCounters.delete(r),this.cancelPendingPhoneRequest(r),this.removeRecentMessage(r)}schedulePhoneRequest(r,o,i=pke){this.cancelPendingPhoneRequest(r),this.pendingPhoneRequests[r]=setTimeout(()=>{delete this.pendingPhoneRequests[r],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${r} with ${i}ms delay`)}cancelPendingPhoneRequest(r){let o=this.pendingPhoneRequests[r];o&&(clearTimeout(o),delete this.pendingPhoneRequests[r],this.logger.debug(`Cancelled pending phone request for message ${r}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let r of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(r);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(r,o,i){this.baseKeys.set(`${r}:${o}`,i)}hasSameBaseKey(r,o,i){let e=this.baseKeys.get(`${r}:${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=>[dke[Cke()]||"Ubuntu",n,hke()]};var ao;(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"})(ao||(ao={}));var uke={Chrome:ao.CHROME,Edge:ao.EDGE,Firefox:ao.FIREFOX,IE:ao.IE,Opera:ao.OPERA,Safari:ao.SAFARI},Bke=([n,r])=>r==="Desktop"?n==="Windows"?ao.UWP:ao.ELECTRON:uke[r]||ao.OTHER_WEB_CLIENT,Iv=n=>Bke(n).toString(),V9=(n,r,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,r,o,i,Iv(e)].join(",");async function z9(n,r){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!ie(n,"identity"))return{action:"no_identity_node"};r.logger.info({jid:o},"identity changed");let e=lA(o);if(e?.device&&e.device!==0)return r.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(r.meId&&(lt(o,r.meId)||r.meLid&<(o,r.meLid)))return r.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(r.debounceCache.get(o))return r.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};r.debounceCache.set(o,!0);let A=!Tq(n.attrs.offline);if(!(await r.validateSession(o)).exists)return r.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(r.logger.debug({jid:o},"old session exists, will refresh session"),A)return r.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};r.onBeforeSessionRefresh?.(o);try{return await r.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return r.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function W9(n,r,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return r&&(a.attrs.error=r.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 Qke(n){return n===null||n===""}function fke(n){return n>2147483647||n<-2147483648?n&4294967295:n}function Z9(n){let r=0;if(!Qke(n))for(let o=0;oo.iteration===r)}addSenderMessageKey(r){this.senderKeyStateStructure.senderMessageKeys.push({iteration:r.getIteration(),seed:r.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(r){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===r);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new Pc(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var qn=class n{constructor(r){if(this.MAX_STATES=5,this.senderKeyStates=[],r)for(let o of r)this.senderKeyStates.push(new Gc(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(r){return r===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===r)}addSenderKeyState(r,o,i,e){this.senderKeyStates.push(new Gc(r,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(r,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new Gc(r,o,i,e))}serialize(){return this.senderKeyStates.map(r=>r.getStructure())}static deserialize(r){let o=Buffer.from(r).toString("utf-8"),i=JSON.parse(o,WC.reviver);return new n(i)}};var eX=Le(Os(),1);import*as rS from"crypto";function AX(){return rS.randomBytes(32)}function tX(){return rS.randomInt(2147483647)}function rX(n){return n||(n=(0,eX.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var Fc=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 Lc=class extends Fc{constructor(r,o,i,e,a){if(super(),a)try{let A=a.slice(1),t=Ae.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=t.id,this.iteration=t.iteration,this.chainKey=typeof t.chainKey=="string"?Buffer.from(t.chainKey,"base64"):t.chainKey,this.signatureKey=typeof t.signingKey=="string"?Buffer.from(t.signingKey,"base64"):t.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=r,this.iteration=o,this.chainKey=i,this.signatureKey=e;let t=Ae.SenderKeyDistributionMessage.encode(Ae.SenderKeyDistributionMessage.create({id:r,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),t])}}intsToByteHighAndLow(r,o){return((r<<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 EE=class{constructor(r){this.senderKeyStore=r}async process(r,o){let i=await this.senderKeyStore.loadSenderKey(r);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(r,i)}async create(r){let o=await this.senderKeyStore.loadSenderKey(r);if(o.isEmpty()){let e=tX(),a=AX(),A=rX();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(r,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new Lc(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var iS=Le(ac(),1);var aS=Le(Os(),1);var pE=class extends Fc{constructor(r,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],t=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=Ae.SenderKeyMessage.decode(t).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,t=Buffer.from(i),s=Ae.SenderKeyMessage.encode(Ae.SenderKeyMessage.create({id:r,iteration:o,ciphertext:t})).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=r,this.iteration=o,this.ciphertext=t,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(r){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,aS.verifySignature)(r,o,i))throw new Error("Invalid signature!")}getSignature(r,o){return Buffer.from((0,aS.calculateSignature)(r,o))}serialize(){return this.serialized}getType(){return 4}};var CE=class{constructor(r,o){this.senderKeyStore=r,this.senderKeyName=o}async encrypt(r){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(),r),t=new pE(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),t.serialize()}async decrypt(r){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new pE(null,null,null,null,r),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(r,o){let i=r.getSenderChainKey();if(i.getIteration()>o){if(r.hasSenderMessageKey(o)){let e=r.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 t=[...i];this.logger.trace(`Batch fetching ${t.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",t);for(let g of t){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:t,lidUser:s}of o){if(e.get(t)===s){this.logger.debug({pnUser:t,lidUser:s},"LID mapping already exists, skipping");continue}a[t]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[t,s]of Object.entries(a))A[t]=s,A[`${s}_reverse`]=t;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[t,s]of Object.entries(a))this.mappingCache.set(`pn:${t}`,s),this.mappingCache.set(`lid:${s}`,t)}async getLIDForPN(r){return(await this.getLIDsForPNs([r]))?.[0]?.lid||null}async getLIDsForPNs(r){if(r.length===0)return null;let o=[...new Set(r)].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(r);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(r){let o={},i={},e=[],a=(A,t,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=t.device!==void 0?t.device:0,l=`${g}${c?`:${c}`:""}@${t.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${l} (user mapping with device ${c})`),i[A]={lid:l,pn:A},!0};for(let A of r){if(!nt(A)&&!Lt(A))continue;let t=lA(A);if(!t)continue;let s=t.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,t,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:t})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],t=await this.keys.get("lid-mapping",A);for(let s of A){let g=t[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 l=this.mappingCache.get(`pn:${g}`);if(l&&typeof l=="string"){if(!a(s,c,l)){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 p=c.device||0,B=oA(s);Lt(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(p):o[B]=[p]}}}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 t of A){let g=lA(t.pn)?.user;if(!g)continue;let c=lA(t.lid)?.user;if(c)for(let l of o[t.pn]){let p=`${c}${l?`:${l}`:""}@${l===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${t.pn} \u2192 ${p} (user mapping with device ${l})`);let B=`${g}${l?`:${l}`:""}@${l===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:p,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(r){return(await this.getPNsForLIDs([r]))?.[0]?.pn||null}async getPNsForLIDs(r){if(r.length===0)return null;let o=[...new Set(r)].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(r);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(r){let o={},i=[],e=(a,A,t)=>{if(!t||typeof t!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${t}:${s}@${A.domainType===ut.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 r){if(!vA(a))continue;let A=lA(a);if(!A)continue;let t=A.user,s=this.mappingCache.get(`lid:${t}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:t,decoded:A})}if(i.length){let a=[...new Set(i.map(t=>`${t.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:t,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(t,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 yke(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=iX.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function oX(n,r,o){let i=new oS(n.keys,r,o),e=mke(n,i),a=n.keys,A=new Mn({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),t=async(g,c)=>{let l=nS(g,c),p=l.toString(),{[p]:B}=await n.keys.get("sender-key",[p]);B||await e.storeSenderKey(l,new qn);let Q=await new EE(e).create(l);return{senderName:l,skdm:Q}};return{decryptGroupMessage({group:g,authorJid:c,msg:l}){let p=nS(g,c),B=new CE(e,p);return a.transaction(async()=>B.decrypt(l),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let l=new EE(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let p=nS(g.groupId,c),B=new Lc(null,null,null,null,g.axolotlSenderKeyDistributionMessage),Q=p.toString(),{[Q]:f}=await n.keys.get("sender-key",[Q]);return f||await e.storeSenderKey(p,new qn),a.transaction(async()=>{let{[Q]:y}=await n.keys.get("sender-key",[Q]);y||await e.storeSenderKey(p,new qn),await l.process(p,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:l}){let p=io(g),B=new Xo.SessionCipher(e,p);if(c==="pkmsg"){let f=yke(l);if(f){let y=p.toString();await e.saveIdentity(y,f)&&r.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function Q(){let f;switch(c){case"pkmsg":f=await B.decryptPreKeyWhisperMessage(l);break;case"msg":f=await B.decryptWhisperMessage(l);break}return f}return a.transaction(async()=>await Q(),g)},async encryptMessage({jid:g,data:c}){let l=io(g),p=new Xo.SessionCipher(e,l);return a.transaction(async()=>{let{type:B,body:Q}=await p.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(Q,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:l}){return a.transaction(async()=>{let{senderName:p,skdm:B}=await t(g,c);return{ciphertext:await new CE(e,p).encrypt(l),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:l}=await t(g,c);return l.serialize()},g)},async hasSenderKey({group:g,meId:c}){let l=nS(g,c).toString(),{[l]:p}=await n.keys.get("sender-key",[l]);return!!p},async getSessionInfo(g){let c=io(g).toString(),l=await e.loadSession(c);if(!l)return null;let p=l.getOpenSession?.(),B=p?.indexInfo?.baseKey,Q=p?.registrationId;return!B||typeof Q!="number"?null:{baseKey:new Uint8Array(B),registrationId:Q}},async injectE2ESession({jid:g,session:c}){r.trace({jid:g},"injecting E2EE session");let l=new Xo.SessionBuilder(e,io(g));return a.transaction(async()=>{await l.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return io(g).toString()},lidMapping:i,async validateSession(g){try{let c=io(g),l=await e.loadSession(c.toString());return l?l.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(l=>{let p=io(l);c[p.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||!vA(c)&&!yr(c))return{migrated:0,skipped:0,total:0};if(!nt(g)&&!Lt(g))return{migrated:0,skipped:0,total:1};let{user:l}=lA(g);r.debug({fromJid:g},"bulk device migration - loading all user devices");let{[l]:p}=await a.get("device-list",[l]);if(!p)return{migrated:0,skipped:0,total:0};let{device:B}=lA(g),Q=B?.toString()||"0";p.includes(Q)||p.push(Q);let y=p.filter(k=>{let G=`${l}.${k}`;return!A.has(G)}).map(k=>`${l}.${k}`),m=await a.get("session",y),R=[];for(let[k,G]of Object.entries(m))if(G){let K=k.split(".")[1];if(!K)continue;let x=parseInt(K),H=x===0?`${l}@s.whatsapp.net`:`${l}:${x}@s.whatsapp.net`;x===99&&(H=`${l}:99@hosted`),R.push(H)}return r.debug({fromJid:g,totalDevices:p.length,devicesWithSessions:R.length,devices:R},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let k=R.map(F=>{let T=Aq(F,c),V=lA(F),U=lA(T);return{fromJid:F,toJid:T,pnUser:V.user,lidUser:U.user,deviceId:V.device||0,fromAddr:io(F),toAddr:io(T)}}),G=k.length,K=0,x=Array.from(new Set(k.map(F=>F.fromAddr.toString()))),H=await a.get("session",x),q={};for(let F of k){let T=F.fromAddr.toString(),V=F.toAddr.toString(),U=H[T];if(U){let b=Xo.SessionRecord.deserialize(U);b.haveOpenSession()&&(q[V]=b.serialize(),q[T]=null,K++)}}if(Object.keys(q).length>0){await a.set({session:q}),r.debug({migratedSessions:K},"bulk session migration complete");for(let F of k)if(q[F.toAddr.toString()]){let T=`${F.pnUser}.${F.deviceId}`;A.set(T,!0)}}let j=G-K;return{migrated:K,skipped:j,total:G}},`migrate-${R.length}-sessions-${lA(c)?.user}`)}}}var io=n=>{let r=lA(n),{user:o,device:i,server:e,domainType:a}=r;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==ut.WHATSAPP?`${o}_${a}`:o,t=i||0;if(i===99&&r.server!=="hosted"&&r.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new Xo.ProtocolAddress(A,t)},nS=(n,r)=>new td(n,io(r));function mke({creds:n,keys:r},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[t,s]=a.split("_"),g=parseInt(s||"0");if(g===ut.LID||g===ut.HOSTED_LID)return e;let c=`${t}${A!=="0"?`:${A}`:""}@${g===ut.HOSTED?"hosted":"s.whatsapp.net"}`,l=await o.getLIDForPN(c);if(l)return io(l).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await r.get("session",[a]);if(A)return Xo.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await r.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await r.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:t}=await r.get("identity-key",[A]),s=t?.length===a.length&&t.every((g,c)=>g===a[c]);return t&&!s?(await r.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):t?!1:(await r.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await r.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>r.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 r.get("sender-key",[a]);return A?qn.deserialize(A):new qn},storeSenderKey:async(e,a)=>{let A=e.toString(),t=JSON.stringify(a.serialize());await r.set({"sender-key":{[A]:Buffer.from(t,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from(di(e.public))}}}}var s$=Le(n$(),1),sd=(0,s$.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var XFe=[2,3e3,1043857760];var jh="https://web.whatsapp.com",jZ="https://call.whatsapp.com/video/",JZ="https://call.whatsapp.com/voice/",QE="CB:",g$="TAG:";var i9=Buffer.from([6,0]),o9=Buffer.from([6,1]),Pk=Buffer.from([6,5]),agA=Buffer.from([6,6]),Vh=10080*60,c$=1440*60,I$=336*60*60,I9="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",$Fe=3,Tn=Buffer.from([5]),l$=Buffer.from([87,65,6,$Fe]),qZ=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,Fk={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},gd=[Ae.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,Ae.HistorySync.HistorySyncType.PUSH_NAME,Ae.HistorySync.HistorySyncType.RECENT,Ae.HistorySync.HistorySyncType.FULL,Ae.HistorySync.HistorySyncType.ON_DEMAND,Ae.HistorySync.HistorySyncType.NON_BLOCKING_DATA,Ae.HistorySync.HistorySyncType.INITIAL_STATUS_V3],ng={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},E$={version:XFe,browser:tS.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:sd.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!==Ae.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:oX},Ok={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"},RZ={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"},VZ=Object.keys(Ok),p$=12e4,cd=5,C$=812,h$=3e4,aP={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var d$=Le(ar(),1);import{createHash as eLe}from"crypto";import{createWriteStream as ALe,promises as tLe}from"fs";import{tmpdir as rLe}from"os";import{join as aLe}from"path";var u$=n=>{let r=ie(n,"product_catalog"),o=mA(r,"product").map(Id),i=ie(r,"paging");return{products:o,nextPageCursor:i?RA(i,"after"):void 0}},B$=n=>{let r=ie(n,"collections");return{collections:mA(r,"collection").map(i=>{let e=RA(i,"id"),a=RA(i,"name"),A=mA(i,"product").map(Id);return{id:e,name:a,products:A,status:nLe(i)}})}},Q$=n=>{let r=ie(n,"order"),o=mA(r,"product").map(a=>{let A=ie(a,"image");return{id:RA(a,"id"),name:RA(a,"name"),imageUrl:RA(A,"url"),price:+RA(a,"price"),currency:RA(a,"currency"),quantity:+RA(a,"quantity")}}),i=ie(r,"price");return{price:{total:+RA(i,"total"),currency:RA(i,"currency")},products:o}},iP=(n,r)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof r.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(r.name)}),typeof r.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(r.description)}),typeof r.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(r.retailerId)}),r.images.length&&i.push({tag:"media",attrs:{},content:r.images.map(a=>{if(!("url"in a))throw new d$.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 r.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(r.price.toString())}),typeof r.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(r.currency)}),"originCountryCode"in r&&(typeof r.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(r.originCountryCode)}]})),typeof r.isHidden<"u"&&(o.is_hidden=r.isHidden.toString()),{tag:"product",attrs:o,content:i}},Id=n=>{let r=n.attrs.is_hidden==="true",o=RA(n,"id"),i=ie(n,"media"),e=ie(n,"status_info");return{id:o,imageUrls:oLe(i),reviewStatus:{whatsapp:RA(e,"status")},availability:"in stock",name:RA(n,"name"),retailerId:RA(n,"retailer_id"),url:RA(n,"url"),description:RA(n,"description"),price:+RA(n,"price"),currency:RA(n,"currency"),isHidden:r}};async function oP(n,r,o=3e4){return n={...n,images:n.images?await iLe(n.images,r,o):n.images},n}var iLe=async(n,r,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let l=e.url.toString();if(l.includes(".whatsapp.net"))return{url:l}}let{stream:a}=await Yh(e),A=eLe("sha256"),t=aLe(rLe(),"img"+nr()),s=ALe(t);for await(let l of a)A.update(l),s.write(l);let g=A.digest("base64"),{directPath:c}=await r(t,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await tLe.unlink(t).catch(l=>console.log("Error deleting temp file ",l)),{url:xh(c)}})),oLe=n=>{let r=ie(n,"image");return{requested:RA(r,"request_image_url"),original:RA(r,"original_image_url")}},nLe=n=>{let r=ie(n,"status_info");return{status:RA(r,"status"),canAppeal:RA(r,"can_appeal")==="true"}};var Ed=Le(ar(),1);import{randomBytes as lP}from"crypto";var Ni=null;try{Ni=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 ct(n,r,o){this.low=n|0,this.high=r|0,this.unsigned=!!o}ct.prototype.__isLong__;Object.defineProperty(ct.prototype,"__isLong__",{value:!0});function ra(n){return(n&&n.__isLong__)===!0}function f$(n){var r=Math.clz32(n&-n);return n?31-r:r}ct.isLong=ra;var y$={},m$={};function xc(n,r){var o,i,e;return r?(n>>>=0,(e=0<=n&&n<256)&&(i=m$[n],i)?i:(o=tt(n,0,!0),e&&(m$[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=y$[n],i)?i:(o=tt(n,n<0?-1:0,!1),e&&(y$[n]=o),o))}ct.fromInt=xc;function Ti(n,r){if(isNaN(n))return r?Vn:so;if(r){if(n<0)return Vn;if(n>=O$)return _$}else{if(n<=-D$)return Ra;if(n+1>=D$)return b$}return n<0?Ti(-n,r).neg():tt(n%yE|0,n/yE|0,r)}ct.fromNumber=Ti;function tt(n,r,o){return new ct(n,r,o)}ct.fromBits=tt;var bS=Math.pow;function sP(n,r,o){if(n.length===0)throw Error("empty string");if(typeof r=="number"?(o=r,r=!1):r=!!r,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return r?Vn:so;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return sP(n.substring(1),r,o).neg();for(var e=Ti(bS(o,8)),a=so,A=0;A>>0:this.low};be.toNumber=function(){return this.unsigned?(this.high>>>0)*yE+(this.low>>>0):this.high*yE+(this.low>>>0)};be.toString=function(r){if(r=r||10,r<2||36>>0,c=g.toString(r);if(A=s,A.isZero())return c+t;for(;c.length<6;)c="0"+c;t=""+c+t}};be.getHighBits=function(){return this.high};be.getHighBitsUnsigned=function(){return this.high>>>0};be.getLowBits=function(){return this.low};be.getLowBitsUnsigned=function(){return this.low>>>0};be.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ra)?64:this.neg().getNumBitsAbs();for(var r=this.high!=0?this.high:this.low,o=31;o>0&&(r&1<>21;return r?this.unsigned?!1:r===-1&&!(this.low===0&&this.high===-2097152):!0};be.isZero=function(){return this.high===0&&this.low===0};be.eqz=be.isZero;be.isNegative=function(){return!this.unsigned&&this.high<0};be.isPositive=function(){return this.unsigned||this.high>=0};be.isOdd=function(){return(this.low&1)===1};be.isEven=function(){return(this.low&1)===0};be.equals=function(r){return ra(r)||(r=Ri(r)),this.unsigned!==r.unsigned&&this.high>>>31===1&&r.high>>>31===1?!1:this.high===r.high&&this.low===r.low};be.eq=be.equals;be.notEquals=function(r){return!this.eq(r)};be.neq=be.notEquals;be.ne=be.notEquals;be.lessThan=function(r){return this.comp(r)<0};be.lt=be.lessThan;be.lessThanOrEqual=function(r){return this.comp(r)<=0};be.lte=be.lessThanOrEqual;be.le=be.lessThanOrEqual;be.greaterThan=function(r){return this.comp(r)>0};be.gt=be.greaterThan;be.greaterThanOrEqual=function(r){return this.comp(r)>=0};be.gte=be.greaterThanOrEqual;be.ge=be.greaterThanOrEqual;be.compare=function(r){if(ra(r)||(r=Ri(r)),this.eq(r))return 0;var o=this.isNegative(),i=r.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?r.high>>>0>this.high>>>0||r.high===this.high&&r.low>>>0>this.low>>>0?-1:1:this.sub(r).isNegative()?-1:1};be.comp=be.compare;be.negate=function(){return!this.unsigned&&this.eq(Ra)?Ra:this.not().add(fE)};be.neg=be.negate;be.add=function(r){ra(r)||(r=Ri(r));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=r.high>>>16,t=r.high&65535,s=r.low>>>16,g=r.low&65535,c=0,l=0,p=0,B=0;return B+=a+g,p+=B>>>16,B&=65535,p+=e+s,l+=p>>>16,p&=65535,l+=i+t,c+=l>>>16,l&=65535,c+=o+A,c&=65535,tt(p<<16|B,c<<16|l,this.unsigned)};be.subtract=function(r){return ra(r)||(r=Ri(r)),this.add(r.neg())};be.sub=be.subtract;be.multiply=function(r){if(this.isZero())return this;if(ra(r)||(r=Ri(r)),Ni){var o=Ni.mul(this.low,this.high,r.low,r.high);return tt(o,Ni.get_high(),this.unsigned)}if(r.isZero())return this.unsigned?Vn:so;if(this.eq(Ra))return r.isOdd()?Ra:so;if(r.eq(Ra))return this.isOdd()?Ra:so;if(this.isNegative())return r.isNegative()?this.neg().mul(r.neg()):this.neg().mul(r).neg();if(r.isNegative())return this.mul(r.neg()).neg();if(this.lt(w$)&&r.lt(w$))return Ti(this.toNumber()*r.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,t=r.high>>>16,s=r.high&65535,g=r.low>>>16,c=r.low&65535,l=0,p=0,B=0,Q=0;return Q+=A*c,B+=Q>>>16,Q&=65535,B+=a*c,p+=B>>>16,B&=65535,B+=A*g,p+=B>>>16,B&=65535,p+=e*c,l+=p>>>16,p&=65535,p+=a*g,l+=p>>>16,p&=65535,p+=A*s,l+=p>>>16,p&=65535,l+=i*c+e*g+a*s+A*t,l&=65535,tt(B<<16|Q,l<<16|p,this.unsigned)};be.mul=be.multiply;be.divide=function(r){if(ra(r)||(r=Ri(r)),r.isZero())throw Error("division by zero");if(Ni){if(!this.unsigned&&this.high===-2147483648&&r.low===-1&&r.high===-1)return this;var o=(this.unsigned?Ni.div_u:Ni.div_s)(this.low,this.high,r.low,r.high);return tt(o,Ni.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Vn:so;var i,e,a;if(this.unsigned){if(r.unsigned||(r=r.toUnsigned()),r.gt(this))return Vn;if(r.gt(this.shru(1)))return M$;a=Vn}else{if(this.eq(Ra)){if(r.eq(fE)||r.eq(nP))return Ra;if(r.eq(Ra))return fE;var A=this.shr(1);return i=A.div(r).shl(1),i.eq(so)?r.isNegative()?fE:nP:(e=this.sub(r.mul(i)),a=i.add(e.div(r)),a)}else if(r.eq(Ra))return this.unsigned?Vn:so;if(this.isNegative())return r.isNegative()?this.neg().div(r.neg()):this.neg().div(r).neg();if(r.isNegative())return this.div(r.neg()).neg();a=so}for(e=this;e.gte(r);){i=Math.max(1,Math.floor(e.toNumber()/r.toNumber()));for(var t=Math.ceil(Math.log(i)/Math.LN2),s=t<=48?1:bS(2,t-48),g=Ti(i),c=g.mul(r);c.isNegative()||c.gt(e);)i-=s,g=Ti(i,this.unsigned),c=g.mul(r);g.isZero()&&(g=fE),a=a.add(g),e=e.sub(c)}return a};be.div=be.divide;be.modulo=function(r){if(ra(r)||(r=Ri(r)),Ni){var o=(this.unsigned?Ni.rem_u:Ni.rem_s)(this.low,this.high,r.low,r.high);return tt(o,Ni.get_high(),this.unsigned)}return this.sub(this.div(r).mul(r))};be.mod=be.modulo;be.rem=be.modulo;be.not=function(){return tt(~this.low,~this.high,this.unsigned)};be.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};be.clz=be.countLeadingZeros;be.countTrailingZeros=function(){return this.low?f$(this.low):f$(this.high)+32};be.ctz=be.countTrailingZeros;be.and=function(r){return ra(r)||(r=Ri(r)),tt(this.low&r.low,this.high&r.high,this.unsigned)};be.or=function(r){return ra(r)||(r=Ri(r)),tt(this.low|r.low,this.high|r.high,this.unsigned)};be.xor=function(r){return ra(r)||(r=Ri(r)),tt(this.low^r.low,this.high^r.high,this.unsigned)};be.shiftLeft=function(r){return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r<32?tt(this.low<>>32-r,this.unsigned):tt(0,this.low<>>r|this.high<<32-r,this.high>>r,this.unsigned):tt(this.high>>r-32,this.high>=0?0:-1,this.unsigned)};be.shr=be.shiftRight;be.shiftRightUnsigned=function(r){return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r<32?tt(this.low>>>r|this.high<<32-r,this.high>>>r,this.unsigned):r===32?tt(this.high,0,this.unsigned):tt(this.high>>>r-32,0,this.unsigned)};be.shru=be.shiftRightUnsigned;be.shr_u=be.shiftRightUnsigned;be.rotateLeft=function(r){var o;return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r===32?tt(this.high,this.low,this.unsigned):r<32?(o=32-r,tt(this.low<>>o,this.high<>>o,this.unsigned)):(r-=32,o=32-r,tt(this.high<>>o,this.low<>>o,this.unsigned))};be.rotl=be.rotateLeft;be.rotateRight=function(r){var o;return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r===32?tt(this.high,this.low,this.unsigned):r<32?(o=32-r,tt(this.high<>>r,this.low<>>r,this.unsigned)):(r-=32,o=32-r,tt(this.low<>>r,this.high<>>r,this.unsigned))};be.rotr=be.rotateRight;be.toSigned=function(){return this.unsigned?tt(this.low,this.high,!1):this};be.toUnsigned=function(){return this.unsigned?this:tt(this.low,this.high,!0)};be.toBytes=function(r){return r?this.toBytesLE():this.toBytesBE()};be.toBytesLE=function(){var r=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,r&255,r>>>8&255,r>>>16&255,r>>>24]};be.toBytesBE=function(){var r=this.high,o=this.low;return[r>>>24,r>>>16&255,r>>>8&255,r&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};ct.fromBytes=function(r,o,i){return i?ct.fromBytesLE(r,o):ct.fromBytesBE(r,o)};ct.fromBytesLE=function(r,o){return new ct(r[0]|r[1]<<8|r[2]<<16|r[3]<<24,r[4]|r[5]<<8|r[6]<<16|r[7]<<24,o)};ct.fromBytesBE=function(r,o){return new ct(r[4]<<24|r[5]<<16|r[6]<<8|r[7],r[0]<<24|r[1]<<16|r[2]<<8|r[3],o)};typeof BigInt=="function"&&(ct.fromBigInt=function(r,o){var i=Number(BigInt.asIntN(32,r)),e=Number(BigInt.asIntN(32,r>>BigInt(32)));return tt(i,e,o)},ct.fromValue=function(r,o){return typeof r=="bigint"?ct.fromBigInt(r,o):Ri(r,o)},be.toBigInt=function(){var r=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new jn;return{mutex(r){return n.runExclusive(r)}}},N$=()=>{let n=new Map;return{async mutex(r,o){let i=n.get(r);i||(i={mutex:new jn,refCount:0},n.set(r,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(r)===i&&n.delete(r)}}}};function T$(n,r,o=10){let i=[],e=!1;return{enqueue:(A,t)=>{if(i.push({type:A,node:t}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&r.isWsOpen();){let{type:c,node:l}=i.shift(),p=n.get(c);if(!p){r.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await p(l).catch(B=>r.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await r.yieldToEventLoop())}e=!1})().catch(g=>r.onUnexpectedError(g,"processing offline nodes"))}}}var US=Le(ar(),1);var cg=Le(ar(),1);var _S=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(r){let o=[],i;if(r.tag==="devices"){Oa(r);let e=ie(r,"device-list"),a=ie(r,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:t}of e.content){let s=+t.id,g=+t["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(t.is_hosted&&t.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 An=class{withId(r){return this.id=r,this}withLid(r){return this.lid=r,this}withPhone(r){return this.phone=r,this}withUsername(r){return this.username=r,this}withUsernameKey(r){return this.usernameKey=r,this}withType(r){return this.type=r,this}withPersonaId(r){return this.personaId=r,this}};var NS=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(r){return r.phone?{tag:"contact",attrs:{},content:r.phone}:r.username?{tag:"contact",attrs:{username:r.username,...r.usernameKey?{pin:r.usernameKey}:{},...r.lid?{lid:r.lid}:{}}}:r.type?{tag:"contact",attrs:{type:r.type}}:{tag:"contact",attrs:{}}}parser(r){return r.tag==="contact"?(Oa(r),r?.attrs?.type==="in"):!1}};var TS=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(r){if(r.tag==="status"){Oa(r);let o=r?.content?.toString()??null,i=new Date(+(r?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):r.attrs?.code&&+r.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var RS=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(r){if(r.tag==="disappearing_mode"){Oa(r);let o=+r?.attrs.duration,i=new Date(+(r?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var kS=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(r){return null}parser(r){return r.tag==="username"?(Oa(r),typeof r.content=="string"?r.content:null):null}};var vS=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(r){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:r.personaId}}]}}parser(r){let o=ie(r,"bot"),i=ie(o,"profile"),e=ie(i,"commands"),a=ie(i,"prompts"),A=[],t=[];for(let s of mA(e,"command"))A.push({name:RA(s,"name"),description:RA(s,"description")});for(let s of mA(a,"prompt"))t.push(`${RA(s,"emoji")} ${RA(s,"text")}`);return{isDefault:!!ie(i,"default"),jid:r.attrs.jid,name:RA(i,"name"),attributes:RA(i,"attributes"),description:RA(i,"description"),category:RA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:RA(e,"description"),commands:A,prompts:t}}};var PS=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(r){return r.lid?{tag:"lid",attrs:{jid:r.lid}}:null}parser(r){return r.tag==="lid"?r.attrs.val:null}};var tn=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(r){return this.mode=r,this}withContext(r){return this.context=r,this}withUser(r){return this.users.push(r),this}parseUSyncQueryResult(r){if(r?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=ie(r,"usync"),a=e?ie(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,t)=>{let s=t?.attrs.jid;if(s){let g=Array.isArray(t?.content)?Object.fromEntries(t.content.map(c=>{let l=c.tag,p=o[l];return p?[l,p(c)]:[l,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new _S),this}withContactProtocol(){return this.protocols.push(new NS),this}withStatusProtocol(){return this.protocols.push(new TS),this}withDisappearingModeProtocol(){return this.protocols.push(new RS),this}withBotProfileProtocol(){return this.protocols.push(new vS),this}withLIDProtocol(){return this.protocols.push(new PS),this}withUsernameProtocol(){return this.protocols.push(new kS),this}};var lr=Le(ar(),1);import{randomBytes as cP}from"crypto";import{URL as ILe}from"url";import{promisify as lLe}from"util";var GS=class{constructor(r={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,r)}};import{EventEmitter as gLe}from"events";var FS=class extends gLe{constructor(r,o){super(),this.url=r,this.config=o,this.setMaxListeners(0)}};var LS=class extends FS{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===Hi.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===Hi.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===Hi.CLOSING}get isConnecting(){return this.socket?.readyState===Hi.CONNECTING}connect(){if(this.socket)return;this.socket=new Hi(this.url,{origin:jh,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let r=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of r)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let r=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await r,this.socket=null}send(r,o){return this.socket?.send(r,o),!!this.socket}};var gP=Le(ar(),1);var cLe=(n,r,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:uA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:r},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),ld=async(n,r,o,i,e)=>{let a=await cLe(n,r,i,e),A=ie(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(", "),l=s.errors[0],p=l.extensions?.error_code||400;throw new gP.Boom(`GraphQL server error: ${c}`,{statusCode:p,data:l})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let t=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new gP.Boom(`Failed to ${t}, unexpected response structure.`,{statusCode:400,data:a})};var R$=n=>{let{waWebSocketUrl:r,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:t,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:l}=n,p=new GS,B=0,Q=Fq(),f=()=>`${Q}${Se++}`;t&&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."),gd.map(oe=>n.shouldSyncHistoryMessage({syncType:oe})).filter(oe=>oe===!1).length===gd.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 r=="string"?new ILe(r):r;if(n.mobile||m.protocol==="tcp:")throw new lr.Boom("Mobile API is not supported anymore",{statusCode:yt.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let R=Ut.generateKeyPair(),k=c9({keyPair:R,NOISE_HEADER:l$,logger:i,routingInfo:A?.creds?.routingInfo}),G=new LS(m,n);G.connect();let K=lLe(G.send),x=async oe=>{if(!G.isOpen)throw new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed});let le=k.encodeFrame(oe);await dl(o,async(Be,eA)=>{try{await K.call(G,le),Be()}catch(IA){eA(IA)}})},H=oe=>{i.level==="trace"&&i.trace({xml:Zi(oe),msg:"xml send"});let le=tq(oe);return x(le)},q=async(oe,le=s)=>{let Be,eA;try{return await dl(le,(TA,wt)=>(Be=WA=>{TA(WA)},eA=WA=>{wt(WA||new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed}))},G.on(`TAG:${oe}`,Be),G.on("close",eA),G.on("error",eA),()=>wt(new lr.Boom("Query Cancelled"))))}catch(IA){if(IA instanceof lr.Boom&&IA.output?.statusCode===yt.timedOut){i?.warn?.({msgId:oe},"timed out waiting for message");return}throw IA}finally{Be&&G.off(`TAG:${oe}`,Be),eA&&(G.off("close",eA),G.off("error",eA))}},j=async(oe,le)=>{oe.attrs.id||(oe.attrs.id=f());let Be=oe.attrs.id,eA=await dl(le,async(IA,TA)=>{let wt=q(Be,le).catch(TA);H(oe).then(async()=>IA(await wt)).catch(TA)});return eA&&"tag"in eA&&Oa(eA),eA},F=async()=>{let oe=await j({tag:"iq",attrs:{to:uA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!ie(oe,"digest"))throw await Ye(),new Error("encrypt/get digest returned no digest node")},T=async()=>{let oe=(X.signedPreKey.keyId||0)+1,le=await Ff(X.signedIdentityKey,oe);await j({tag:"iq",attrs:{to:uA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[zh(le)]}]}),L.emit("creds.update",{signedPreKey:le})},V=async oe=>{if(oe.protocols.length===0)throw new lr.Boom("USyncQuery must have at least one protocol");let Be=oe.users.map(WA=>({tag:"user",attrs:{jid:WA.phone?void 0:WA.id},content:oe.protocols.map(Er=>Er.getUserElement(WA)).filter(Er=>Er!==null)})),eA={tag:"list",attrs:{},content:Be},IA={tag:"query",attrs:{},content:oe.protocols.map(WA=>WA.getQueryElement())},TA={tag:"iq",attrs:{to:uA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:oe.context,mode:oe.mode,sid:f(),last:"true",index:"0"},content:[IA,eA]}]},wt=await j(TA);return oe.parseUSyncQueryResult(wt)},U=async(...oe)=>{let le=new tn,Be=!1;for(let IA of oe)if(vA(IA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{Be||(Be=!0,le=le.withContactProtocol());let TA=`+${IA.replace("+","").split("@")[0]?.split(":")[0]}`;le.withUser(new An().withPhone(TA))}if(le.users.length===0)return[];let eA=await V(le);if(eA)return eA.list.filter(IA=>!!IA.contact).map(({contact:IA,id:TA})=>({jid:TA,exists:IA}))},b=async oe=>{let le=new tn().withLIDProtocol().withContext("background");for(let eA of oe)if(vA(eA)){i?.warn("LID user found in LID fetch call");continue}else le.withUser(new An().withId(eA));if(le.users.length===0)return[];let Be=await V(le);return Be?Be.list.filter(eA=>!!eA.lid).map(({lid:eA,id:IA})=>({pn:IA,lid:eA})):[]},L=j9(i),{creds:X}=A,pe=P9(A.keys,i,g),me=l({creds:X,keys:pe},i,b),qe,Se=1,Ge,je,Xe=!1,rA=[],nA=(oe,le)=>{i.error({err:oe},`unexpected error in '${le}'`)},Fe=async oe=>{if(!G.isOpen)throw new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed});let le,Be,eA=dl(o,(IA,TA)=>{le=IA,Be=IP(TA),G.on("frame",le),G.on("close",Be),G.on("error",Be)}).finally(()=>{G.off("frame",le),G.off("close",Be),G.off("error",Be)});return oe&&x(oe).catch(Be),eA},hA=async()=>{let oe={clientHello:{ephemeral:R.public}};oe=Ae.HandshakeMessage.fromObject(oe),i.info({browser:a,helloMsg:oe},"connected to WA");let le=Ae.HandshakeMessage.encode(oe).finish(),Be=await Fe(le),eA=Ae.HandshakeMessage.decode(Be);i.trace({handshake:eA},"handshake recv from WA");let IA=k.processHandshake(eA,X.noiseKey),TA;X.me?(TA=t9(X.me.id,n),i.info({node:TA},"logging in...")):(TA=r9(X,n),i.info({node:TA},"not logged in, attempting registration..."));let wt=k.encrypt(Ae.ClientPayload.encode(TA).finish());await x(Ae.HandshakeMessage.encode({clientFinish:{static:IA,payload:wt}}).finish()),await k.finishInit(),Ue()},Ce=async()=>{let oe=await j({tag:"iq",attrs:{id:f(),xmlns:"encrypt",type:"get",to:uA},content:[{tag:"count",attrs:{}}]});return+ie(oe,"count").attrs.value},ce=null,Ye=async(oe=cd)=>{if(ce){i.debug("Pre-key upload already in progress, waiting for completion"),await ce;return}let le=async Be=>{i.info({count:oe,retryCount:Be},"uploading pre-keys");let eA=await pe.transaction(async()=>{i.debug({requestedCount:oe},"generating pre-keys with requested count");let{update:IA,node:TA}=await $Z({creds:X,keys:pe},oe);return L.emit("creds.update",IA),TA},X?.me?.id||"upload-pre-keys");try{await j(eA),i.info({count:oe},"uploaded pre-keys successfully")}catch(IA){if(i.error({uploadError:IA.toString(),count:oe},"Failed to upload pre-keys to server"),Be<3){let TA=Math.min(1e3*Math.pow(2,Be),1e4);return i.info(`Retrying pre-key upload in ${TA}ms`),await new Promise(wt=>setTimeout(wt,TA)),le(Be+1)}throw IA}};ce=Promise.race([le(0),new Promise((Be,eA)=>setTimeout(()=>eA(new lr.Boom("Pre-key upload timeout",{statusCode:408})),h$))]);try{await ce}finally{ce=null}},ve=async()=>{let oe=X.nextPreKeyId-1;return oe<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await pe.get("pre-key",[oe.toString()]))[oe.toString()],currentPreKeyId:oe}},ue=async()=>{try{let oe=0,le=await Ce();le===0?oe=C$:oe=cd;let{exists:Be,currentPreKeyId:eA}=await ve();i.info(`${le} pre-keys found on server`),i.info(`Current prekey ID: ${eA}, exists in storage: ${Be}`);let IA=le<=oe,TA=!Be&&eA>0;if(IA||TA){let WA=[];IA&&WA.push(`server count low (${le})`),TA&&WA.push(`current prekey ${eA} missing from storage`),i.info(`Uploading PreKeys due to: ${WA.join(", ")}`),await Ye(oe)}else i.info(`PreKey validation passed - Server: ${le}, Current prekey ${eA} exists`)}catch(oe){i.error({error:oe},"Failed to check/upload pre-keys during initialization")}},aA=async oe=>{await k.decodeFrame(oe,le=>{qe=new Date;let Be=!1;if(Be=G.emit("frame",le),!(le instanceof Uint8Array)){let eA=le.attrs.id;i.level==="trace"&&i.trace({xml:Zi(le),msg:"recv xml"}),Be=G.emit(`${g$}${eA}`,le)||Be;let IA=le.tag,TA=le.attrs||{},wt=Array.isArray(le.content)?le.content[0]?.tag:"";for(let WA of Object.keys(TA))Be=G.emit(`${QE}${IA},${WA}:${TA[WA]},${wt}`,le)||Be,Be=G.emit(`${QE}${IA},${WA}:${TA[WA]}`,le)||Be,Be=G.emit(`${QE}${IA},${WA}`,le)||Be;Be=G.emit(`${QE}${IA},,${wt}`,le)||Be,Be=G.emit(`${QE}${IA}`,le)||Be,!Be&&i.level==="debug"&&i.debug({unhandled:!0,msgId:eA,fromMe:!1,frame:le},"communication recv")}})},iA=async oe=>{if(Xe){i.trace({trace:oe?.stack},"connection already closed");return}if(Xe=!0,i.info({trace:oe?.stack},oe?"connection errored":"connection closed"),clearInterval(Ge),clearTimeout(je),G.removeAllListeners("close"),G.removeAllListeners("open"),G.removeAllListeners("message"),me.close?.(),!G.isClosed&&!G.isClosing)try{await G.close()}catch{}for(let le of rA)try{await le(oe)}catch(Be){i.error({err:Be},"error in socket end handler")}L.emit("connection.update",{connection:"close",lastDisconnect:{error:oe,date:new Date}}),L.removeAllListeners("connection.update"),L.destroy()},$e=async()=>{if(G.isOpen)return;if(G.isClosed||G.isClosing)throw new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed});let oe,le;await new Promise((Be,eA)=>{oe=()=>Be(void 0),le=IP(eA),G.on("open",oe),G.on("close",le),G.on("error",le)}).finally(()=>{G.off("open",oe),G.off("close",le),G.off("error",le)})},Ue=()=>Ge=setInterval(()=>{qe||(qe=new Date),Date.now()-qe.getTime()>e+5e3?iA(new lr.Boom("Connection was lost",{statusCode:yt.connectionLost})):G.isOpen?j({tag:"iq",attrs:{id:f(),to:uA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(le=>{i.error({trace:le.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),yA=oe=>j({tag:"iq",attrs:{to:uA,xmlns:"passive",type:"set"},content:[{tag:oe,attrs:{}}]}),Ie=async oe=>{let le=A.creds.me?.id;le&&await H({tag:"iq",attrs:{to:uA,type:"set",id:f(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:le,reason:"user_initiated"}}]}),iA(new lr.Boom(oe||"Intentional Logout",{statusCode:yt.loggedOut}))},ye=async(oe,le)=>{let Be=le??Yq(cP(5));if(le&&le?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=Be,A.creds.me={id:Ft(oe,"s.whatsapp.net"),name:"~"},L.emit("creds.update",A.creds),await H({tag:"iq",attrs:{to:uA,type:"set",id:f(),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 _e()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:Iv(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function _e(){let oe=cP(32),le=cP(16),Be=await Lf(A.creds.pairingCode,oe),eA=wq(A.creds.pairingEphemeralKeyPair.public,Be,le);return Buffer.concat([oe,le,eA])}let DA=oe=>j({tag:"iq",attrs:{to:uA,id:f(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:oe}]});G.on("message",aA),G.on("open",async()=>{try{await hA()}catch(oe){i.error({err:oe},"error in validating connection"),iA(oe)}}),G.on("error",IP(iA)),G.on("close",()=>void iA(new lr.Boom("Connection Terminated",{statusCode:yt.connectionClosed}))),G.on("CB:xmlstreamend",()=>void iA(new lr.Boom("Connection Terminated by Server",{statusCode:yt.connectionClosed}))),G.on("CB:iq,type:set,pair-device",async oe=>{let le={tag:"iq",attrs:{to:uA,type:"result",id:oe.attrs.id}};await H(le);let Be=ie(oe,"pair-device"),eA=mA(Be,"ref"),IA=Buffer.from(X.noiseKey.public).toString("base64"),TA=Buffer.from(X.signedIdentityKey.public).toString("base64"),wt=X.advSecretKey,WA=c||6e4,Er=()=>{if(!G.isOpen)return;let Kt=eA.shift();if(!Kt){iA(new lr.Boom("QR refs attempts ended",{statusCode:yt.timedOut}));return}let rn=Kt.content.toString("utf-8"),an=V9(rn,IA,TA,wt,a);L.emit("connection.update",{qr:an}),je=setTimeout(Er,WA),WA=c||2e4};Er()}),G.on("CB:iq,,pair-success",async oe=>{i.debug("pair success recv");try{OA(oe);let{reply:le,creds:Be}=a9(oe,X);i.info({me:Be.me,platform:Be.platform},"pairing configured successfully, expect to restart the connection..."),L.emit("creds.update",Be),L.emit("connection.update",{isNewLogin:!0,qr:void 0}),await H(le),BA()}catch(le){i.info({trace:le.stack},"error in pairing"),iA(le)}}),G.on("CB:success",async oe=>{try{OA(oe),await ue(),await yA("active");try{await F()}catch(le){i.warn({e:le},"failed to run digest after login")}}catch(le){i.warn({err:le},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(je),L.emit("creds.update",{me:{...A.creds.me,lid:oe.attrs.lid}}),L.emit("connection.update",{connection:"open"}),BA(),oe.attrs.lid&&A.creds.me?.id){let le=oe.attrs.lid;process.nextTick(async()=>{try{let Be=A.creds.me.id;await me.lidMapping.storeLIDPNMappings([{lid:le,pn:Be}]);let{user:eA,device:IA}=lA(Be);await A.keys.set({"device-list":{[eA]:[IA?.toString()||"0"]}}),await me.migrateSession(Be,le),i.info({myPN:Be,myLID:le},"Own LID session created successfully")}catch(Be){i.error({error:Be,lid:le},"Failed to create own LID session")}})}}),G.on("CB:stream:error",oe=>{let[le]=bo(oe);i.error({reasonNode:le,fullErrorNode:oe},"stream errored out");let{reason:Be,statusCode:eA}=Uq(oe);iA(new lr.Boom(`Stream Errored (${Be})`,{statusCode:eA,data:le||oe}))}),G.on("CB:failure",oe=>{let le=+(oe.attrs.reason||500);iA(new lr.Boom("Connection Failure",{statusCode:le,data:oe.attrs}))}),G.on("CB:ib,,downgrade_webclient",()=>{iA(new lr.Boom("Multi-device beta not joined",{statusCode:yt.multideviceMismatch}))}),G.on("CB:ib,,offline_preview",async oe=>{i.info("offline preview received",JSON.stringify(oe)),await H({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),G.on("CB:ib,,edge_routing",oe=>{let le=ie(oe,"edge_routing"),Be=ie(le,"routing_info");Be?.content&&(A.creds.routingInfo=Buffer.from(Be?.content),L.emit("creds.update",A.creds))});let Te=!1;process.nextTick(()=>{X.me?.id&&(L.buffer(),Te=!0),L.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),G.on("CB:ib,,offline",oe=>{let Be=+(ie(oe,"offline")?.attrs.count||0);i.info(`handled ${Be} offline messages/notifications`),Te&&(L.flush(),i.trace("flushed events for initial buffer")),L.emit("connection.update",{receivedPendingNotifications:!0})}),L.on("creds.update",oe=>{let le=oe.me?.name;X.me?.name!==le&&(i.debug({name:le},"updated pushName"),H({tag:"presence",attrs:{name:le}}).catch(Be=>{i.warn({trace:Be.stack},"error in sending presence update on name change")})),Object.assign(X,oe)});let OA=({attrs:oe})=>{let le=oe?.t;if(!le)return;let Be=Number(le);if(Number.isNaN(Be)||Be<=0)return;let eA=Date.now();B=Be*1e3-eA,i.debug({offset:B},"calculated server time offset")},zA=()=>{let oe=3*aP.Day;return((Date.now()+B+oe)%aP.Week).toString()},BA=async()=>{if(!G.isOpen)return;let oe={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:zA()}}]};try{await H(oe)}catch(le){i.debug({error:le},"failed to send unified_session telemetry")}},rt=oe=>{rA.push(oe)},Jt=async()=>{let oe=await ld({},fr.REACHOUT_TIMELOCK,kr.xwa2_fetch_account_reachout_timelock,j,f),le={isActive:!!oe?.is_active,timeEnforcementEnds:oe?.time_enforcement_ends&&oe?.time_enforcement_ends!=="0"?new Date(parseInt(oe.time_enforcement_ends,10)*1e3):void 0,enforcementType:oe?.enforcement_type??Rs.DEFAULT};return L.emit("connection.update",{reachoutTimeLock:le}),le},NA=async()=>ld({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},fr.MESSAGE_CAPPING_INFO,kr.xwa2_message_capping_info,j,f);return{type:"md",ws:G,ev:L,authState:{creds:X,keys:pe},signalRepository:me,get user(){return A.creds.me},generateMessageTag:f,query:j,waitForMessage:q,waitForSocketOpen:$e,sendRawMessage:x,sendNode:H,logout:Ie,end:iA,registerSocketEndHandler:rt,onUnexpectedError:nA,uploadPreKeys:Ye,uploadPreKeysToServerIfRequired:ue,digestKeyBundle:F,rotateSignedPreKey:T,requestPairingCode:ye,updateServerTimeOffset:OA,sendUnifiedSession:BA,wamBuffer:p,waitForConnectionUpdate:Gq(L),sendWAMBuffer:DA,executeUSyncQuery:V,onWhatsApp:U,fetchAccountReachoutTimelock:Jt,fetchNewChatMessageCap:NA}};function IP(n){return r=>{n(new lr.Boom(`WebSocket Error (${r?.message})`,{statusCode:Kq(r),data:r}))}}var ELe=(n,r)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return r?.length&&(o.content=r),[o]},k$=n=>{let{logger:r,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:t}=n,s=R$(n),{ev:g,ws:c,authState:l,generateMessageTag:p,sendNode:B,query:Q,signalRepository:f,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:R}=s,k=f.lidMapping.getLIDForPN.bind(f.lidMapping),G,K={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},x=Qr.Connecting,H=zn(),q=zn(),j=zn(),F=zn(),T,V={initialBootstrapComplete:!1,recentSyncComplete:!1},U,b=new Set,L=n.placeholderResendCache||new xn({stdTTL:ng.MSG_RETRY,useClones:!1}),X=async Y=>{let{[Y]:z}=await l.keys.get("app-state-sync-key",[Y]);return z},pe=async(Y=!1)=>{if(!G||Y){let{content:z}=await Q({tag:"iq",attrs:{xmlns:"privacy",to:uA,type:"get"},content:[{tag:"privacy",attrs:{}}]});G=aT(z?.[0],"category")}return G},me=async(Y,z)=>{await Q({tag:"iq",attrs:{xmlns:"privacy",to:uA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:Y,value:z}}]}]})},qe=async Y=>{await me("messages",Y)},Se=async Y=>{await me("calladd",Y)},Ge=async Y=>{await me("last",Y)},je=async Y=>{await me("online",Y)},Xe=async Y=>{await me("profile",Y)},rA=async Y=>{await me("status",Y)},nA=async Y=>{await me("readreceipts",Y)},Fe=async Y=>{await me("groupadd",Y)},hA=async Y=>{await Q({tag:"iq",attrs:{xmlns:"disappearing_mode",to:uA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:Y.toString()}}]})},Ce=async()=>{let Y=await Q({tag:"iq",attrs:{xmlns:"bot",to:uA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),z=ie(Y,"bot"),ee=[];for(let te of mA(z,"section"))if(te.attrs.type==="all")for(let he of mA(te,"bot"))ee.push({jid:he.attrs.jid,personaId:he.attrs.persona_id});return ee},ce=async(...Y)=>{let z=new tn().withStatusProtocol();for(let te of Y)z.withUser(new An().withId(te));let ee=await s.executeUSyncQuery(z);if(ee)return ee.list},Ye=async(...Y)=>{let z=new tn().withDisappearingModeProtocol();for(let te of Y)z.withUser(new An().withId(te));let ee=await s.executeUSyncQuery(z);if(ee)return ee.list},ve=async(Y,z,ee)=>{let te;if(!Y)throw new cg.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");oA(Y)!==oA(l.creds.me.id)?te=oA(Y):te=void 0;let{img:he}=await Hm(z,ee);await Q({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:profile:picture",...te?{target:te}:{}},content:[{tag:"picture",attrs:{type:"image"},content:he}]})},ue=async Y=>{let z;if(!Y)throw new cg.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");oA(Y)!==oA(l.creds.me.id)?z=oA(Y):z=void 0,await Q({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:profile:picture",...z?{target:z}:{}}})},aA=async Y=>{await Q({tag:"iq",attrs:{to:uA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(Y,"utf-8")}]})},iA=async Y=>{await NA({pushNameSetting:Y},"")},$e=async()=>{let Y=await Q({tag:"iq",attrs:{xmlns:"blocklist",to:uA,type:"get"}}),z=ie(Y,"list");return mA(z,"item").map(ee=>ee.attrs.jid)},Ue=async(Y,z)=>{let ee=oA(Y),te,he;if(vA(ee)||yr(ee)){if(te=ee,z==="block"){let ge=await f.lidMapping.getPNForLID(ee);if(!ge)throw new cg.Boom(`Unable to resolve PN JID for LID: ${Y}`,{statusCode:400});he=oA(ge)}}else if(nt(ee)||Lt(ee)){let ge=await f.lidMapping.getLIDForPN(ee);if(!ge)throw new cg.Boom(`Unable to resolve LID for PN JID: ${Y}`,{statusCode:400});te=ge,z==="block"&&(he=oA(ee))}else throw new cg.Boom(`Invalid jid: ${Y}`,{statusCode:400});let se={action:z,jid:te};if(z==="block"){if(!he)throw new cg.Boom(`pn_jid required for block: ${Y}`,{statusCode:400});se.pn_jid=he}await Q({tag:"iq",attrs:{xmlns:"blocklist",to:uA,type:"set"},content:[{tag:"item",attrs:se}]})},yA=async Y=>{let z=await Q({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:Y}}]}]}),ee=ie(z,"business_profile"),te=ie(ee,"profile");if(te){let he=ie(te,"address"),se=ie(te,"description"),ge=ie(te,"website"),Ee=ie(te,"email"),Pe=ie(ie(te,"categories"),"category"),tA=ie(te,"business_hours"),CA=tA?mA(tA,"business_hours_config"):void 0,UA=ge?.content?.toString();return{wid:te.attrs?.jid,address:he?.content?.toString(),description:se?.content?.toString()||"",website:UA?[UA]:[],email:Ee?.content?.toString(),category:Pe?.content?.toString(),business_hours:{timezone:tA?.attrs?.timezone,business_config:CA?.map(({attrs:MA})=>MA)}}}},Ie=async(Y,z)=>{r.info({fromTimestamp:z},"clean dirty bits "+Y),await B({tag:"iq",attrs:{to:uA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:p()},content:[{tag:"clean",attrs:{type:Y,...z?{timestamp:z.toString()}:null}}]})},ye=Y=>({onMutation(z){O9(z,g,l.creds.me,Y?{accountSettings:l.creds.accountSettings}:void 0,r)}}),_e=g.createBufferedFunction(async(Y,z)=>{let ee=new Map,te=async Ee=>{if(ee.has(Ee))return ee.get(Ee)??void 0;let Pe=await X(Ee);return ee.set(Ee,Pe??null),Pe},he={},se={};await l.keys.transaction(async()=>{let Ee=new Set(Y),Pe={},tA=new Set;for(;Ee.size;){let CA={},UA=[];for(let jA of Ee){let gA=(await l.keys.get("app-state-sync-version",[jA]))[jA];gA?(gA=Uk(gA),typeof he[jA]>"u"&&(he[jA]=gA.version)):gA=qm(),CA[jA]=gA;let xA=tA.has(jA);xA&&tA.delete(jA),r.info(`resyncing ${jA} from v${gA.version}${xA?" (forcing snapshot)":""}`),UA.push({tag:"collection",attrs:{name:jA,version:gA.version.toString(),return_snapshot:(xA||!gA.version).toString()}})}let MA=await Q({tag:"iq",attrs:{to:uA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:UA}]}),LA=await m9(MA,n?.options);for(let jA in LA){let Oe=jA,{patches:gA,hasMorePatches:xA,snapshot:Kr}=LA[Oe];try{if(Kr){let{state:Yt,mutationMap:go}=await D9(Oe,Kr,te,he[Oe],e.snapshot,r);CA[Oe]=Yt,Object.assign(se,go),r.info(`restored state of ${Oe} from snapshot to v${Yt.version} with mutations`),await l.keys.set({"app-state-sync-version":{[Oe]:Yt}})}if(gA.length){let{state:Yt,mutationMap:go}=await Kk(Oe,gA,CA[Oe],te,n.options,he[Oe],r,e.patch);await l.keys.set({"app-state-sync-version":{[Oe]:Yt}}),r.info(`synced ${Oe} to v${Yt.version}`),he[Oe]=Yt.version,Object.assign(se,go)}xA?r.info(`${Oe} has more patches...`):Ee.delete(Oe)}catch(Yt){Pe[Oe]=(Pe[Oe]||0)+1;let go={name:Oe,attempt:Pe[Oe],version:CA[Oe].version,statusCode:Yt.output?.statusCode,errorType:Yt.name,error:Yt.stack};Xh(Yt)&&Pe[Oe]>=Hk?(r.warn(go,`${Oe} blocked on missing key from v${CA[Oe].version}, parking after ${Pe[Oe]} attempts`),b.add(Oe),Ee.delete(Oe)):Xh(Yt)?(r.info(go,`${Oe} blocked on missing key from v${CA[Oe].version}, retrying with snapshot`),tA.add(Oe)):Q9(Yt,Pe[Oe])?(r.warn(go,`failed to sync ${Oe} from v${CA[Oe].version}, giving up`),Ee.delete(Oe)):(r.info(go,`failed to sync ${Oe} from v${CA[Oe].version}, forcing snapshot retry`),tA.add(Oe))}}}},l?.creds?.me?.id||"resync-app-state");let{onMutation:ge}=ye(z);for(let Ee in se)ge(se[Ee])}),DA=async(Y,z="preview",ee)=>{let te=oA(Y),he=nt(te)||vA(te),se=l.creds.me,ge=se&&(te===oA(se.id)||se.lid&&te===oA(se.lid)),Ee;K.profilePicPrivacyToken&&he&&!ge&&(Ee=await iv({authState:l,jid:te,getLIDForPN:k})),Y=oA(Y);let Pe=await Q({tag:"iq",attrs:{target:Y,to:uA,type:"get",xmlns:"w:profile:picture"},content:ELe(z,Ee)},ee);return ie(Pe,"picture")?.attrs?.url},Te=async(Y,z,ee)=>{let te=await Q({tag:"call",attrs:{id:p(),to:"@call"},content:[{tag:"link_create",attrs:{media:Y},content:z?[{tag:"event",attrs:{start_time:String(z.startTime)}}]:void 0}]},ee);return ie(te,"link_create")?.attrs?.token},OA=async(Y,z)=>{let ee=l.creds.me,te=Y==="available";if(te||Y==="unavailable"){if(!ee.name){r.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:te}),te&&m(),await B({tag:"presence",attrs:{name:ee.name.replace(/@/g,""),type:Y}})}else{let{server:he}=lA(z);await B({tag:"chatstate",attrs:{from:he==="lid"?ee.lid:ee.id,to:z},content:[{tag:Y==="recording"?"composing":Y,attrs:Y==="recording"?{media:"audio"}:{}}]})}},zA=async Y=>{let z=oA(Y),te=nt(z)||vA(z)?await iv({authState:l,jid:z,getLIDForPN:k}):void 0;return B({tag:"presence",attrs:{to:Y,id:p(),type:"subscribe"},content:te})},BA=({tag:Y,attrs:z,content:ee})=>{let te,he=z.from,se=z.participant||z.from;if(!(a(he)&&he!==uA)){if(Y==="presence")te={lastKnownPresence:z.type==="unavailable"?"unavailable":"available",lastSeen:z.last&&z.last!=="deny"?+z.last:void 0,groupOnlineCount:z.count?+z.count:void 0};else if(Array.isArray(ee)){let[ge]=ee,Ee=ge.tag;Ee==="paused"&&(Ee="available"),ge.attrs?.media==="audio"&&(Ee="recording"),te={lastKnownPresence:Ee}}else r.error({tag:Y,attrs:z,content:ee},"recv invalid presence node");te&&g.emit("presence.update",{id:he,presences:{[se]:te}})}},rt=async Y=>{let z=Y.type,ee=l.creds.myAppStateKeyId;if(!ee)throw new cg.Boom("App state key not present!",{statusCode:400});let te,he;if(await j.mutex(async()=>{await l.keys.transaction(async()=>{r.debug({patch:Y},"applying app patch"),await _e([z],!1);let{[z]:se}=await l.keys.get("app-state-sync-version",[z]);te=se?Uk(se):qm(),he=await f9(Y,ee,te,X);let{patch:ge,state:Ee}=he,Pe={tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:z,version:(Ee.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:Ae.SyncdPatch.encode(ge).finish()}]}]}]};await Q(Pe),await l.keys.set({"app-state-sync-version":{[z]:Ee}})},l?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:se}=ye(!1),{mutationMap:ge}=await Kk(z,[{...he.patch,version:{version:he.state.version}}],te,X,n.options,void 0,r);for(let Ee in ge)se(ge[Ee])}},Jt=async()=>{let Y=await Q({tag:"iq",attrs:{to:uA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...l?.creds?.lastPropHash?{hash:l.creds.lastPropHash}:{}}}]}),z=ie(Y,"props"),ee={};z&&(z.attrs?.hash&&(l.creds.lastPropHash=z?.attrs?.hash,g.emit("creds.update",l.creds)),ee=aT(z,"prop"));let te=ee[10518]??ee.privacy_token_sending_on_all_1_on_1_messages;te!==void 0&&(K.privacyTokenOn1to1=te==="true"||te==="1");let he=ee[9666]??ee.profile_scraping_privacy_token_in_photo_iq;he!==void 0&&(K.profilePicPrivacyToken=he==="true"||he==="1");let se=ee[14303]??ee.lid_trusted_token_issue_to_lid;return se!==void 0&&(K.lidTrustedTokenIssueToLid=se==="true"||se==="1"),r.debug({serverProps:K},"fetched props"),ee},NA=(Y,z)=>{let ee=w9(Y,z);return rt(ee)},oe=Y=>NA({disableLinkPreviews:{isPreviewsDisabled:Y}},""),le=(Y,z,ee)=>NA({star:{messages:z,star:ee}},Y),Be=(Y,z)=>NA({contact:z},Y),eA=Y=>NA({contact:null},Y),IA=(Y,z)=>NA({addLabel:{...z}},Y),TA=(Y,z)=>NA({addChatLabel:{labelId:z}},Y),wt=(Y,z)=>NA({removeChatLabel:{labelId:z}},Y),WA=(Y,z,ee)=>NA({addMessageLabel:{messageId:z,labelId:ee}},Y),Er=(Y,z,ee)=>NA({removeMessageLabel:{messageId:z,labelId:ee}},Y),Kt=Y=>NA({quickReply:Y},""),rn=Y=>NA({quickReply:{timestamp:Y,deleted:!0}},""),an=async()=>{await Promise.all([Jt(),$e(),pe()])},Z=g.createBufferedFunction(async(Y,z)=>{if(g.emit("messages.upsert",{messages:[Y],type:z}),Y.pushName){let se=Y.key.fromMe?l.creds.me.id:Y.key.participant||Y.key.remoteJid;se=oA(se),Y.key.fromMe||g.emit("contacts.update",[{id:se,notify:Y.pushName,verifiedName:Y.verifiedBizName}]),Y.key.fromMe&&Y.pushName&&l.creds.me?.name!==Y.pushName&&g.emit("creds.update",{me:{...l.creds.me,name:Y.pushName}})}let ee=Jm(Y.message),te=ee?A(ee)&&gd.includes(ee.syncType):!1;if(ee&&te){let se=ee.syncType;se===Ae.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!V.initialBootstrapComplete&&(V.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:se,status:"complete",explicit:!0})),se===Ae.HistorySync.HistorySyncType.RECENT&&ee.progress===100&&!V.recentSyncComplete&&(V.recentSyncComplete=!0,clearTimeout(U),U=void 0,g.emit("messaging-history.status",{syncType:se,status:"complete",explicit:!0})),se===Ae.HistorySync.HistorySyncType.RECENT&&!V.recentSyncComplete&&(clearTimeout(U),U=setTimeout(()=>{V.recentSyncComplete||(V.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:Ae.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),U=void 0},p$))}ee&&x===Qr.AwaitingInitialSync&&(T&&(clearTimeout(T),T=void 0),te?(x=Qr.Syncing,r.info("Transitioned to Syncing state")):(x=Qr.Online,r.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let he=async()=>{if(x===Qr.Syncing){b.clear(),r.info("Doing app state sync"),await _e(JJ,!0),x=Qr.Online,r.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let se=(l.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:se})}};await Promise.all([(async()=>{te&&await he()})(),x9(Y,{signalRepository:f,shouldProcessHistoryMsg:te,placeholderResendCache:L,ev:g,creds:l.creds,keyStore:l.keys,logger:r,options:n.options,getMessage:t})]),Y.message?.protocolMessage?.appStateSyncKeyShare&&x===Qr.Syncing&&(r.info("App state sync key arrived, triggering app state sync"),await he())});return c.on("CB:presence",BA),c.on("CB:chatstate",BA),c.on("CB:ib,,dirty",async Y=>{let{attrs:z}=ie(Y,"dirty");switch(z.type){case"account_sync":if(z.timestamp){let{lastAccountSyncTimestamp:te}=l.creds;te&&await Ie("account_sync",te),te=+z.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:te})}break;case"groups":break;default:r.info({node:Y},"received unknown sync");break}}),g.on("connection.update",({connection:Y,receivedPendingNotifications:z})=>{if(Y==="close"&&(b.clear(),clearTimeout(U),U=void 0),Y==="open"&&(i&&an().catch(te=>y(te,"init queries")),OA(o?"available":"unavailable").catch(te=>y(te,"presence update requests"))),!z||x!==Qr.Connecting)return;if(V.initialBootstrapComplete=!1,V.recentSyncComplete=!1,clearTimeout(U),U=void 0,x=Qr.AwaitingInitialSync,r.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(Ae.Message.HistorySyncNotification.create({syncType:Ae.HistorySync.HistorySyncType.RECENT}))){r.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),x=Qr.Online,setTimeout(()=>g.flush(),0);return}if(l.creds.accountSyncCounter>0){r.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),x=Qr.Online,setTimeout(()=>g.flush(),0);return}r.info("First connection, awaiting history sync notification with a 20s timeout."),T&&clearTimeout(T),T=setTimeout(()=>{if(x===Qr.AwaitingInitialSync){r.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),x=Qr.Online,g.flush();let te=(l.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:te})}},2e4)}),g.on("creds.update",({myAppStateKeyId:Y})=>{if(!Y||b.size===0)return;if(x===Qr.Syncing){b.clear();return}let z=[...b];b.clear(),r.info({collections:z},"app state sync key arrived, re-syncing blocked collections"),_e(z,!1).catch(ee=>y(ee,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:Y,pn:z})=>{try{await f.lidMapping.storeLIDPNMappings([{lid:Y,pn:z}])}catch(ee){r.warn({lid:Y,pn:z,error:ee},"Failed to store LID-PN mapping")}}),R(()=>{T&&(clearTimeout(T),T=void 0),!n.placeholderResendCache&&L.close&&L.close(),x=Qr.Connecting,G=void 0}),{...s,serverProps:K,createCallLink:Te,getBotListV2:Ce,messageMutex:H,receiptMutex:q,appStatePatchMutex:j,notificationMutex:F,fetchPrivacySettings:pe,upsertMessage:Z,appPatch:rt,sendPresenceUpdate:OA,presenceSubscribe:zA,profilePictureUrl:DA,fetchBlocklist:$e,fetchStatus:ce,fetchDisappearingDuration:Ye,updateProfilePicture:ve,removeProfilePicture:ue,updateProfileStatus:aA,updateProfileName:iA,updateBlockStatus:Ue,updateDisableLinkPreviewsPrivacy:oe,updateCallPrivacy:Se,updateMessagesPrivacy:qe,updateLastSeenPrivacy:Ge,updateOnlinePrivacy:je,updateProfilePicturePrivacy:Xe,updateStatusPrivacy:rA,updateReadReceiptsPrivacy:nA,updateGroupsAddPrivacy:Fe,updateDefaultDisappearingMode:hA,getBusinessProfile:yA,resyncAppState:_e,chatModify:NA,cleanDirtyBits:Ie,addOrEditContact:Be,removeContact:eA,placeholderResendCache:L,addLabel:IA,addChatLabel:TA,removeChatLabel:wt,addMessageLabel:WA,removeMessageLabel:Er,star:le,addOrEditQuickReply:Kt,removeQuickReply:rn}};var v$=n=>{let r=k$(n),{authState:o,ev:i,query:e,upsertMessage:a}=r,A=async(g,c,l)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:l}),t=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return mE(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={},l=ie(g,"groups");if(l){let p=mA(l,"group");for(let B of p){let Q=mE({tag:"result",attrs:{},content:[B]});c[Q.id]=Q}}return r.ev.emit("groups.update",Object.values(c)),c};return r.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=ie(g,"dirty");c.type==="groups"&&(await s(),await r.cleanDirtyBits("groups"))}),{...r,groupMetadata:t,groupCreate:async(g,c)=>{let l=nr(),p=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:l},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return mE(p)},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:{}}]),l=ie(c,"membership_approval_requests");return mA(l,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,l)=>{let p=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:l,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=ie(p,"membership_requests_action"),Q=ie(B,l);return mA(Q,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,l)=>{let p=await A(g,"set",[{tag:l,attrs:{},content:c.map(f=>({tag:"participant",attrs:{jid:f}}))}]),B=ie(p,l);return mA(B,"participant").map(f=>({status:f.attrs.error||"200",jid:f.attrs.jid,content:f}))},groupUpdateDescription:async(g,c)=>{let p=(await t(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:nr()}:{delete:"true"},...p?{prev:p}:{}},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 ie(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return ie(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return ie(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 l=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=Ae.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:nr(r.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:QA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:Pr()},"notify"),l.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return mE(c)},groupToggleEphemeral:async(g,c)=>{let l=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[l])},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}},mE=n=>{let r=ie(n,"group");if(!r){let B=ie(n,"error");if(B){let Q=B.attrs.code?+B.attrs.code:500,f=B.attrs.text||"group metadata query failed";throw new US.Boom(f,{statusCode:Q,data:B})}throw new US.Boom("Invalid group metadata response: missing node",{data:n})}if(!r.attrs.id)throw new US.Boom("Invalid group metadata response: missing group id",{data:r});let o=ie(r,"description"),i,e,a,A,t,s;o&&(i=RA(o,"body"),a=o.attrs.participant?oA(o.attrs.participant):void 0,A=o.attrs.participant_pn?oA(o.attrs.participant_pn):void 0,t=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=r.attrs.id.includes("@")?r.attrs.id:Ft(r.attrs.id,"g.us"),c=ie(r,"ephemeral")?.attrs.expiration,l=RA(r,"member_add_mode")==="all_member_add";return{id:g,notify:r.attrs.notify,addressingMode:r.attrs.addressing_mode==="lid"?LC.LID:LC.PN,subject:r.attrs.subject,subjectOwner:r.attrs.s_o,subjectOwnerPn:r.attrs.s_o_pn,subjectOwnerUsername:r.attrs.s_o_username,subjectTime:+r.attrs.s_t,size:r.attrs.size?+r.attrs.size:mA(r,"participant").length,creation:+r.attrs.creation,owner:r.attrs.creator?oA(r.attrs.creator):void 0,ownerPn:r.attrs.creator_pn?oA(r.attrs.creator_pn):void 0,ownerUsername:r.attrs.creator_username||void 0,owner_country_code:r.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:t,descTime:s,linkedParent:ie(r,"linked_parent")?.attrs.jid||void 0,restrict:!!ie(r,"locked"),announce:!!ie(r,"announcement"),isCommunity:!!ie(r,"parent"),isCommunityAnnounce:!!ie(r,"default_sub_group"),joinApprovalMode:!!ie(r,"membership_approval_mode"),memberAddMode:l,participants:mA(r,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:vA(B.jid)&&nt(B.phone_number)?B.phone_number:void 0,lid:nt(B.jid)&&vA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var SE=Le(ar(),1);var pLe=n=>{let{id:r,thread_metadata:o,viewer_metadata:i}=n;return{id:r,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}},CLe=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,P$=n=>{let r=v$(n),{query:o,generateMessageTag:i}=r,e=(A,t,s)=>ld(A,t,s,o,i),a=async(A,t)=>{let s={newsletter_id:A,updates:{...t,settings:null}};return e(s,fr.UPDATE_METADATA,"xwa2_newsletter_update")};return{...r,newsletterCreate:async(A,t)=>{let g=await e({input:{name:A,description:t??null}},fr.CREATE,kr.xwa2_newsletter_create);return pLe(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},fr.SUBSCRIBERS,kr.xwa2_newsletter_subscribers),newsletterMetadata:async(A,t)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:t,type:A.toUpperCase()}},g=await e(s,fr.METADATA,kr.xwa2_newsletter_metadata);return CLe(g)},newsletterFollow:A=>e({newsletter_id:A},fr.FOLLOW,kr.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},fr.UNFOLLOW,kr.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},fr.MUTE,kr.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},fr.UNMUTE,kr.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,t)=>await a(A,{name:t}),newsletterUpdateDescription:async(A,t)=>await a(A,{description:t}),newsletterUpdatePicture:async(A,t)=>{let{img:s}=await Hm(t);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,t,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:t,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,t,s,g)=>{let c={count:t.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 t=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=ie(t,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},fr.ADMIN_COUNT,kr.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,t)=>{await e({newsletter_id:A,user_id:t},fr.CHANGE_OWNER,kr.xwa2_newsletter_change_owner)},newsletterDemote:async(A,t)=>{await e({newsletter_id:A,user_id:t},fr.DEMOTE,kr.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},fr.DELETE,kr.xwa2_newsletter_delete_v2)}}};var G$=n=>{let{logger:r,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:t,maxMsgRetryCount:s}=n,g=P$(n),{ev:c,authState:l,messageMutex:p,signalRepository:B,upsertMessage:Q,query:f,fetchPrivacySettings:y,sendNode:m,groupMetadata:R,groupToggleEphemeral:k,registerSocketEndHandler:G}=g,K=B.lidMapping.getLIDForPN.bind(B.lidMapping),x=new Set,H=n.userDevicesCache||new xn({stdTTL:ng.USER_DEVICES,useClones:!1}),q=zn(),j=t?new AS(r,s):null,F=N$(),T,V=Dk,U=async(Ce=!1)=>{let ce=await T;return(!ce||Ce||new Date().getTime()-ce.fetchDate.getTime()>ce.ttl*1e3)&&(T=(async()=>{let Ye=await f({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:uA},content:[{tag:"media_conn",attrs:{}}]}),ve=ie(Ye,"media_conn"),ue={hosts:mA(ve,"host").map(({attrs:aA})=>({hostname:aA.hostname,maxContentLengthBytes:+aA.maxContentLengthBytes})),auth:ve.attrs.auth,ttl:+ve.attrs.ttl,fetchDate:new Date};return r.debug("fetched media conn"),ue.hosts[0]&&(V=ue.hosts[0].hostname),ue})()),T},b=async(Ce,ce,Ye,ve)=>{if(!Ye||Ye.length===0)throw new SE.Boom("missing ids in receipt");let ue={tag:"receipt",attrs:{id:Ye[0]}};(ve==="read"||ve==="read-self")&&(ue.attrs.t=Pr().toString()),ve==="sender"&&(nt(Ce)||vA(Ce))?(ue.attrs.recipient=Ce,ue.attrs.to=ce):(ue.attrs.to=Ce,ce&&(ue.attrs.participant=ce)),ve&&(ue.attrs.type=ve);let iA=Ye.slice(1);iA.length&&(ue.content=[{tag:"list",attrs:{},content:iA.map($e=>({tag:"item",attrs:{id:$e}}))}]),r.debug({attrs:ue.attrs,messageIds:Ye},"sending receipt for messages"),await m(ue)},L=async(Ce,ce)=>{let Ye=KZ(Ce);for(let{jid:ve,participant:ue,messageIds:aA}of Ye)await b(ve,ue,aA,ce)},X=async Ce=>{let Ye=(await y()).readreceipts==="all"?"read":"read-self";await L(Ce,Ye)},pe=async(Ce,ce,Ye)=>{let ve=[];ce||r.debug("not using cache for devices");let ue=[],aA=Ce.map(Ie=>{let ye=lA(Ie),_e=ye?.user,DA=ye?.device;return typeof DA=="number"&&DA>=0&&_e?(ve.push({user:_e,device:DA,jid:Ie}),null):(Ie=oA(Ie),{jid:Ie,user:_e})}).filter(Ie=>Ie!==null),iA;if(ce&&H.mget){let Ie=aA.map(ye=>ye?.user).filter(Boolean);iA=await H.mget(Ie)}for(let{jid:Ie,user:ye}of aA)if(ce){let _e=iA?.[ye]||(H.mget?void 0:await H.get(ye));if(_e){let DA=_e.map(Te=>({...Te,jid:Ft(Te.user,Te.server,Te.device)}));ve.push(...DA),r.trace({user:ye},"using cache for devices")}else ue.push(Ie)}else ue.push(Ie);if(!ue.length)return ve;let $e=new Set;for(let Ie of ue)if(vA(Ie)||yr(Ie)){let ye=lA(Ie)?.user;ye&&$e.add(ye)}let Ue=new tn().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Ie of ue)Ue.withUser(new An().withId(Ie));let yA=await g.executeUSyncQuery(Ue);if(yA){let Ie=yA.list.filter(Te=>!!Te.lid);if(Ie.length>0){r.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Ie.map(Te=>({lid:Te.lid,pn:Te.id})));try{let Te=Ie.map(OA=>OA.lid);Te.length&&await qe(Te,!0)}catch(Te){r.warn({e:Te,count:Ie.length},"failed to assert sessions for newly mapped LIDs")}}let ye=XZ(yA?.list,l.creds.me.id,l.creds.me.lid,Ye),_e={};for(let Te of ye)_e[Te.user]=_e[Te.user]||[],_e[Te.user]?.push(Te);for(let[Te,OA]of Object.entries(_e)){let zA=$e.has(Te);for(let BA of OA){let rt=zA?Ft(Te,BA.server,BA.device):Ft(BA.user,BA.server,BA.device);ve.push({...BA,jid:rt}),r.debug({user:BA.user,device:BA.device,finalJid:rt,usedLid:zA},"Processed device with LID priority")}}await q.mutex(async()=>{if(H.mset)await H.mset(Object.entries(_e).map(([Te,OA])=>({key:Te,value:OA})));else for(let Te in _e)_e[Te]&&await H.set(Te,_e[Te])});let DA={};for(let[Te,OA]of Object.entries(_e))OA&&OA.length>0&&(DA[Te]=OA.map(zA=>zA.device?.toString()||"0"));if(Object.keys(DA).length>0)try{await l.keys.set({"device-list":DA}),r.debug({userCount:Object.keys(DA).length},"stored user device lists for bulk migration")}catch(Te){r.warn({error:Te},"failed to store user device lists")}}return ve},me=(Ce,ce)=>je(Ce,{protocolMessage:{type:Ae.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:ce?.slice(0,30),labelTimestamp:Pr()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),qe=async(Ce,ce)=>{let Ye=!1,ve=[...new Set(Ce)],ue=[];r.debug({jids:Ce},"assertSessions call with jids");for(let aA of ve)!ce&&(await B.validateSession(aA)).exists||ue.push(aA);if(ue.length){let aA=[...ue.filter($e=>!!vA($e)||!!yr($e)),...(await B.lidMapping.getLIDsForPNs(ue.filter($e=>!!nt($e)||!!Lt($e)))||[]).map($e=>$e.lid)];r.debug({jidsRequiringFetch:ue,wireJids:aA},"fetching sessions");let iA=await f({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:uA},content:[{tag:"key",attrs:{},content:aA.map($e=>{let Ue={jid:$e};return ce&&(Ue.reason="identity"),{tag:"user",attrs:Ue}})}]});await ZZ(iA,B),Ye=!0}return Ye},Se=async Ce=>{if(!l.creds.me?.id)throw new SE.Boom("Not authenticated");let ce={protocolMessage:{peerDataOperationRequestMessage:Ce,type:Ae.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},Ye=oA(l.creds.me.id);return await je(Ye,ce,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},Ge=async(Ce,ce,Ye,ve)=>{if(!Ce.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let ue=await a(ce,Ce),aA=Array.isArray(ue)?ue:Ce.map(_e=>({recipientJid:_e,message:ue})),iA=!1,$e=l.creds.me.id,Ue=l.creds.me?.lid,yA=Ue?lA(Ue)?.user:null,Ie=aA.map(async({recipientJid:_e,message:DA})=>{try{if(!_e)return null;let Te=DA;if(ve){let{user:rt}=lA(_e),{user:Jt}=lA($e),NA=yA;(rt===Jt||NA&&rt===NA)&&!(_e===$e||Ue&&_e===Ue)&&(Te=ve,r.debug({jid:_e,targetUser:rt},"Using DSM for own device"))}let OA=hl(Te),zA=_e;return await F.mutex(zA,async()=>{let{type:rt,ciphertext:Jt}=await B.encryptMessage({jid:_e,data:OA});return rt==="pkmsg"&&(iA=!0),{tag:"to",attrs:{jid:_e},content:[{tag:"enc",attrs:{v:"2",type:rt,...Ye||{}},content:Jt}]}})}catch(Te){return r.error({jid:_e,err:Te},"Failed to encrypt for recipient"),null}}),ye=(await Promise.all(Ie)).filter(_e=>_e!==null);if(Ce.length>0&&ye.length===0)throw new SE.Boom("All encryptions failed",{statusCode:500});return{nodes:ye,shouldIncludeDeviceIdentity:iA}},je=async(Ce,ce,{messageId:Ye,participant:ve,additionalAttributes:ue,additionalNodes:aA,useUserDevicesCache:iA,useCachedGroupMetadata:$e,statusJidList:Ue})=>{let yA=G9(l.creds),Ie=l.creds.me?.lid,ye=!!ve?.jid,_e=ye,DA="status@broadcast",{user:Te,server:OA}=lA(Ce),zA=OA==="g.us",BA=Ce===DA,rt=OA==="lid",Jt=OA==="newsletter",NA=zA||BA,oe=Ce;Ye=Ye||nr(yA),iA=iA!==!1,$e=$e!==!1&&!BA;let le=[],Be=BA?DA:oe,eA=[],IA=[],TA,wt={deviceSentMessage:{destinationJid:Be,message:ce},messageContextInfo:ce.messageContextInfo},WA={};if(ve){!zA&&!BA&&(ue={...ue,device_fanout:"false"});let{user:Er,device:Kt}=lA(ve.jid);IA.push({user:Er,device:Kt,jid:ve.jid})}return await l.keys.transaction(async()=>{let Er=rA(ce);if(Er&&(WA.mediatype=Er),Jt){let se=a?await a(ce,[]):ce,ge=xq(se);eA.push({tag:"plaintext",attrs:{},content:ge});let Ee={tag:"message",attrs:{to:Ce,id:Ye,type:Xe(ce),...ue||{}},content:eA};r.debug({msgId:Ye},`sending newsletter message to ${Ce}`),await m(Ee);return}if((Hr(ce)?.pinInChatMessage||Hr(ce)?.reactionMessage)&&(WA["decrypt-fail"]="hide"),NA&&!ye){let[se,ge]=await Promise.all([(async()=>{let gA=$e&&A?await A(Ce):void 0;return gA&&Array.isArray(gA?.participants)?r.trace({jid:Ce,participants:gA.participants.length},"using cached group metadata"):BA||(gA=await R(Ce)),gA})(),(async()=>!ve&&!BA?(await l.keys.get("sender-key-memory",[Ce]))[Ce]||{}:{})()]),Ee=se?se.participants.map(gA=>gA.id):[];se?.ephemeralDuration&&se.ephemeralDuration>0&&(ue={...ue,expiration:se.ephemeralDuration.toString()}),BA&&Ue&&Ee.push(...Ue);let Pe=await pe(Ee,!!iA,!1);IA.push(...Pe),zA&&(ue={...ue,addressing_mode:se?.addressingMode||"lid"});let tA=await a(ce);if(Array.isArray(tA))throw new SE.Boom("Per-jid patching is not supported in groups");let CA=hl(tA);TA=tA;let MA=(ue?.addressing_mode||se?.addressingMode||"lid")==="lid"&&Ie?Ie:yA,{ciphertext:LA,senderKeyDistributionMessage:jA}=await B.encryptGroupMessage({group:Be,data:CA,meId:MA}),Oe=[];for(let gA of IA){let xA=gA.jid;(!!!ge[xA]||ve)&&!yr(xA)&&!Lt(xA)&&gA.device!==99&&(Oe.push(xA),ge[xA]=!0)}if(Oe.length){r.debug({senderKeyJids:Oe},"sending new sender key");let gA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:jA,groupId:Be}};await qe(Oe);let Kr=await Ge(Oe,gA,WA);_e=_e||Kr.shouldIncludeDeviceIdentity,le.push(...Kr.nodes)}eA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...WA},content:LA}),await l.keys.set({"sender-key-memory":{[Ce]:ge}})}else{let se=yA;rt&&Ie?(se=Ie,r.debug({to:Ce,ownId:se},"Using LID identity for @lid conversation")):r.debug({to:Ce,ownId:se},"Using PN identity for @s.whatsapp.net conversation");let{user:ge}=lA(se);if(!ve){let gA=await a(ce,[Ce]);TA=Array.isArray(gA)?gA.find(xA=>xA.recipientJid===Ce)||gA[0]:gA}if(!ye){let gA=rt?"lid":"s.whatsapp.net";if(IA.push({user:Te,device:0,jid:Ft(Te,gA,0)}),Te!==ge){let xA=rt?"lid":"s.whatsapp.net",Kr=rt&&Ie?lA(Ie).user:lA(yA).user;IA.push({user:Kr,device:0,jid:Ft(Kr,xA,0)})}if(ue?.category!=="peer"){IA.length=0;let xA=rt&&Ie?Ft(lA(Ie)?.user,"lid",void 0):Ft(lA(yA)?.user,"s.whatsapp.net",void 0),Kr=await pe([xA,Ce],!0,!1);IA.push(...Kr),r.debug({deviceCount:IA.length,devices:IA.map(Yt=>`${Yt.user}:${Yt.device}@${lA(Yt.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let Ee=[],Pe=[],tA=[],{user:CA}=lA(yA),{user:UA}=Ie?lA(Ie):{user:null};for(let{user:gA,jid:xA}of IA){if(xA===yA||Ie&&xA===Ie){r.debug({jid:xA,meId:yA,meLid:Ie},"Skipping exact sender device (whatsmeow pattern)");continue}gA===CA||gA===UA?Pe.push(xA):tA.push(xA),Ee.push(xA)}await qe(Ee);let[{nodes:MA,shouldIncludeDeviceIdentity:LA},{nodes:jA,shouldIncludeDeviceIdentity:Oe}]=await Promise.all([Ge(Pe,wt||ce,WA),Ge(tA,ce,WA,wt)]);le.push(...MA),le.push(...jA),(Pe.length>0||tA.length>0)&&(WA.phash=kq([...Pe,...tA])),_e=_e||LA||Oe}if(ye){let se=vA(ve.jid),ge=lt(ve.jid,se?Ie:yA),Ee=ce;if(NA){let UA;if(Ie&&await B.hasSenderKey({group:Be,meId:Ie})?UA=Ie:await B.hasSenderKey({group:Be,meId:yA})&&(UA=yA),UA)try{let MA=await B.getSenderKeyDistributionMessage({group:Be,meId:UA});Ee={...ce,senderKeyDistributionMessage:{groupId:Be,axolotlSenderKeyDistributionMessage:MA}}}catch(MA){r.warn({err:MA,jid:Be},"failed to build SKDM for retry, sending without it")}}let Pe=ge?hl({deviceSentMessage:{destinationJid:Be,message:Ee}}):hl(Ee),{type:tA,ciphertext:CA}=await B.encryptMessage({data:Pe,jid:ve.jid});eA.push({tag:"enc",attrs:{v:"2",type:tA,count:ve.count.toString()},content:CA})}if(le.length)if(ue?.category==="peer"){let se=le[0]?.content?.[0];se&&eA.push(se)}else eA.push({tag:"participants",attrs:{},content:le});let Kt={tag:"message",attrs:{id:Ye,to:Be,type:Xe(ce),...ue||{}},content:eA};if(ve?ir(Be)?(Kt.attrs.to=Be,Kt.attrs.participant=ve.jid):lt(ve.jid,yA)?(Kt.attrs.to=ve.jid,Kt.attrs.recipient=Be):Kt.attrs.to=ve.jid:Kt.attrs.to=Be,_e&&(Kt.content.push({tag:"device-identity",attrs:{},content:Wh(l.creds.account,!0)}),r.debug({jid:Ce},"adding device identity")),!Jt&&!ye&&TA?.messageContextInfo?.messageSecret&&xm(TA))try{let se=hl(TA),ge={id:Ye,fromMe:!0,remoteJid:Be,participant:ve?.jid},Ee=await GZ(se,TA,ge);Ee&&(Kt.content.push(Ee),r.trace({jid:Ce},"added reporting token to message"))}catch(se){r.warn({jid:Ce,trace:se?.stack},"failed to attach reporting token")}let rn=ue?.category==="peer",an=!zA&&!ye&&!BA&&!Jt&&!rn,Z=an?await Zo(Be,K):Be,z=(an?await l.keys.get("tctoken",[Z]):{})[Z],ee=z?.token;if(ee?.length&&vc(z?.timestamp)){r.debug({jid:Be,timestamp:z?.timestamp},"tctoken expired, clearing"),ee=void 0;let se=z?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:z.senderTimestamp}:null;try{await l.keys.set({tctoken:{[Z]:se}})}catch(ge){r.debug({jid:Be,err:ge?.message},"failed to persist tctoken expiry cleanup")}}ee?.length&&g.serverProps.privacyTokenOn1to1&&Kt.content.push({tag:"tctoken",attrs:{},content:ee}),aA&&aA.length>0&&Kt.content.push(...aA),r.debug({msgId:Ye},`sending message to ${le.length} devices`),await m(Kt);let te=!!Hr(ce)?.protocolMessage,he=Be===XJ||eq(Be)||gl(Be);if(an&&!te&&!he&&K9(z?.senderTimestamp)&&!x.has(Z)){x.add(Z);let se=Pr(),ge=B.lidMapping.getPNForLID.bind(B.lidMapping);Ad(Be,g.serverProps.lidTrustedTokenIssueToLid,K,ge).then(Ee=>nA([Ee],se)).then(async Ee=>{await IE({result:Ee,fallbackJid:Z,keys:l.keys,getLIDForPN:K});let tA=(await l.keys.get("tctoken",[Z]))[Z],CA=await cE(l.keys,[Z]);await l.keys.set({tctoken:{[Z]:{token:Buffer.alloc(0),...tA,senderTimestamp:se},...CA}})}).catch(Ee=>{r.debug({jid:Be,err:Ee?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{x.delete(Z)})}j&&!ve&&j.addRecentMessage(Be,Ye,ce)},yA),Ye},Xe=Ce=>{let ce=Hr(Ce);return ce?ce.reactionMessage||ce.encReactionMessage?"reaction":ce.pollCreationMessage||ce.pollCreationMessageV2||ce.pollCreationMessageV3||ce.pollUpdateMessage?"poll":ce.eventMessage?"event":rA(ce)!==""?"media":"text":"text"},rA=Ce=>Ce.imageMessage?"image":Ce.videoMessage?Ce.videoMessage.gifPlayback?"gif":"video":Ce.audioMessage?Ce.audioMessage.ptt?"ptt":"audio":Ce.contactMessage?"vcard":Ce.documentMessage?"document":Ce.contactsArrayMessage?"contact_array":Ce.liveLocationMessage?"livelocation":Ce.stickerMessage?"sticker":Ce.listMessage?"list":Ce.listResponseMessage?"list_response":Ce.buttonsResponseMessage?"buttons_response":Ce.orderMessage?"order":Ce.productMessage?"product":Ce.interactiveResponseMessage?"native_flow_response":Ce.groupInviteMessage?"url":"",nA=async(Ce,ce)=>{let Ye=(ce??Pr()).toString();return await f({tag:"iq",attrs:{to:uA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:Ce.map(ue=>({tag:"token",attrs:{jid:oA(ue),t:Ye,type:"trusted_contact"}}))}]})},Fe=MZ(n,U),hA=ET(c,"messages.media-update");return G(()=>{!n.userDevicesCache&&H.close&&H.close(),T=void 0,j&&j.clear()}),{...g,userDevicesCache:H,devicesMutex:q,issuePrivacyTokens:nA,assertSessions:qe,relayMessage:je,sendReceipt:b,sendReceipts:L,readMessages:X,refreshMediaConn:U,getMediaHost:()=>V,waUploadToServer:Fe,fetchPrivacySettings:y,sendPeerDataOperationMessage:Se,createParticipantNodes:Ge,getUSyncDevices:pe,messageRetryManager:j,updateMemberLabel:me,updateMediaMessage:async Ce=>{let ce=xZ(Ce.message),Ye=ce.mediaKey,ve=l.creds.me.id,ue=_Z(Ce.key,Ye,ve),aA;if(await Promise.all([m(ue),hA(async iA=>{let $e=iA.find(Ue=>Ue.key.id===Ce.key.id);if($e){if($e.error)aA=$e.error;else try{let Ue=TZ($e.media,Ye,$e.key.id);if(Ue.result!==Ae.MediaRetryNotification.ResultType.SUCCESS){let yA=Ae.MediaRetryNotification.ResultType[Ue.result];throw new SE.Boom(`Media re-upload failed by device (${yA})`,{data:Ue,statusCode:wk(Ue.result)||404})}ce.directPath=Ue.directPath,ce.url=xh(ce.directPath,V),r.debug({directPath:Ue.directPath,key:$e.key},"media update successful")}catch(Ue){aA=Ue}return!0}})]),aA)throw aA;return c.emit("messages.update",[{key:Ce.key,update:{message:Ce.message}}]),Ce},sendMessage:async(Ce,ce,Ye={})=>{let ve=l.creds.me.id;if(typeof ce=="object"&&"disappearingMessagesInChat"in ce&&typeof ce.disappearingMessagesInChat<"u"&&ir(Ce)){let{disappearingMessagesInChat:ue}=ce;await k(Ce,typeof ue=="boolean"?ue?Vh:0:ue)}else{let ue=await UZ(Ce,ce,{logger:r,userJid:ve,getUrlInfo:_e=>H9(_e,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:r,uploadImage:i?Fe:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:Fe,mediaCache:n.mediaCache,options:n.options,messageId:nr(g.user?.id),...Ye}),aA="event"in ce&&!!ce.event,iA="delete"in ce&&!!ce.delete,$e="edit"in ce&&!!ce.edit,Ue="pin"in ce&&!!ce.pin,yA="poll"in ce&&!!ce.poll,Ie={},ye=[];return iA?ir(ce.delete?.remoteJid)&&!ce.delete?.fromMe?Ie.edit="8":Ie.edit="7":$e?Ie.edit="1":Ue?Ie.edit="2":yA?ye.push({tag:"meta",attrs:{polltype:"creation"}}):aA&&ye.push({tag:"meta",attrs:{event_type:"creation"}}),await je(Ce,ue.message,{messageId:ue.key.id,useCachedGroupMetadata:Ye.useCachedGroupMetadata,additionalAttributes:Ie,statusJidList:Ye.statusJidList,additionalNodes:ye}),n.emitOwnEvents&&process.nextTick(async()=>{await p.mutex(()=>Q(ue,"append"))}),ue}}}};var hLe=new Set(Object.values(Rs));function dLe(n){return typeof n=="string"&&hLe.has(n)}var F$=n=>{let{logger:r,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,t=G$(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:l,ws:p,messageMutex:B,notificationMutex:Q,receiptMutex:f,signalRepository:y,query:m,upsertMessage:R,resyncAppState:k,onUnexpectedError:G,assertSessions:K,sendNode:x,relayMessage:H,sendReceipt:q,uploadPreKeys:j,sendPeerDataOperationMessage:F,messageRetryManager:T,registerSocketEndHandler:V,issuePrivacyTokens:U,fetchAccountReachoutTimelock:b,placeholderResendCache:L}=t,X=y.lidMapping.getLIDForPN.bind(y.lidMapping),pe=zn(),me=n.msgRetryCounterCache||new xn({stdTTL:ng.MSG_RETRY,useClones:!1}),qe=n.callOfferCache||new xn({stdTTL:ng.CALL_OFFER,useClones:!1}),Se=new xn({stdTTL:5,useClones:!1}),Ge=!1,je=async(Z,Y,z)=>{if(!l.creds.me?.id)throw new Ed.Boom("Not authenticated");let ee={historySyncOnDemandRequest:{chatJid:Y.remoteJid,oldestMsgFromMe:Y.fromMe,oldestMsgId:Y.id,oldestMsgTimestampMs:z,onDemandMsgCount:Z},peerDataOperationRequestType:Ae.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return F(ee)},Xe=async(Z,Y)=>{if(!l.creds.me?.id)throw new Ed.Boom("Not authenticated");if(await L.get(Z?.id)){r.debug({messageKey:Z},"already requested resend");return}else await L.set(Z?.id,Y||!0);if(await ZC(2e3),!await L.get(Z?.id))return r.debug({messageKey:Z},"message received while resend requested"),"RESOLVED";let z={placeholderMessageResendRequest:[{messageKey:Z}],peerDataOperationRequestType:Ae.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await L.get(Z?.id)&&(r.debug({messageKey:Z},"PDO message without response after 8 seconds. Phone possibly offline"),await L.del(Z?.id))},8e3),F(z)},rA=async Z=>{let Y=ie(Z,"update");if(Y){let z=Y.attrs?.op_name;if(!z){r.warn({node:Zi(Z)},"mex notification missing op_name, fallback to legacy"),await hA(Z);return}let ee;try{ee=JSON.parse(Y.content.toString())}catch(he){r.error({err:he,opName:z},"failed to parse mex notification JSON");return}if(ee.errors?.length){r.warn({errors:ee.errors,opName:z},"mex notification has GQL errors");return}let te=ee.data;if(!te){r.warn({opName:z},"mex notification has null data");return}switch(r.debug({opName:z},"processing mex notification"),z){case"NotificationUserReachoutTimelockUpdate":nA(te);break;case"MessageCappingInfoNotification":Fe(te);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 hA(Z);break;default:r.debug({opName:z},"unhandled mex notification");break}return}await hA(Z)},nA=Z=>{let Y=Z.xwa2_notify_account_reachout_timelock;if(!Y){r.warn("reachout timelock notification missing payload");return}if(!Y.is_active){r.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:Rs.DEFAULT}});return}let z=Y.time_enforcement_ends?new Date(parseInt(Y.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),ee=dLe(Y.enforcement_type)?Y.enforcement_type:Rs.DEFAULT;r.info({enforcementType:ee,timeEnforcementEnds:z},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:z,enforcementType:ee}})},Fe=Z=>{let Y=Z.xwa2_notify_new_chat_messages_capping_info_update;if(!Y){r.warn("message capping notification missing payload");return}r.info({payload:Y},"received message capping update"),c.emit("message-capping.update",Y)},hA=async Z=>{let Y=ie(Z,"mex"),z=Y?.content?null:ie(Z,"update")||bo(Z)[0],ee=Y?.content?Y:z;if(!ee?.content){r.warn({node:Zi(Z)},"invalid mex newsletter notification");return}let te;try{let ge=ee.content;if(Array.isArray(ge)){r.warn({payloadNode:ee},"invalid mex newsletter notification payload format");return}let Ee=typeof ge=="string"?Buffer.from(ge,"binary"):Buffer.from(ge);te=JSON.parse(Ee.toString())}catch(ge){r.error({err:ge,node:Zi(Z)},"failed to parse mex newsletter notification");return}let he=te?.operation??ee?.attrs?.op_name,se=te?.updates;if(!se){let ge=te?.data?.xwa2_notify_linked_profiles;ge&&(se=[ge])}if(!se||!he){r.warn({data:te},"invalid mex newsletter notification content");return}switch(r.info({operation:he,updates:se},"got mex newsletter notification"),he){case"NotificationNewsletterUpdate":for(let ge of se)ge.jid&&ge.settings&&Object.keys(ge.settings).length>0&&c.emit("newsletter-settings.update",{id:ge.jid,update:ge.settings});break;case"NotificationNewsletterAdminPromote":for(let ge of se)ge.jid&&ge.user&&c.emit("newsletter-participants.update",{id:ge.jid,author:Z.attrs.from,user:ge.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let ge of se){let Ee=ge?.jid,Pe=Array.isArray(ge?.added_profiles)?ge.added_profiles:[],tA=[];for(let CA of Pe){let UA=typeof CA=="string"?CA:CA?.pn??CA?.jid??null;if(Ee&&UA){let MA={lid:Ee,pn:UA};c.emit("lid-mapping.update",MA),tA.push(MA)}}await y.lidMapping.storeLIDPNMappings(tA)}break;default:r.info({operation:he,data:te},"unhandled mex newsletter notification");break}},Ce=async Z=>{let Y=Z.attrs.from,z=bo(Z),ee=Z.attrs.participant;for(let te of z)switch(r.debug({from:Y,child:te},"got newsletter notification"),te.tag){case"reaction":{let he={id:Y,server_id:te.attrs.message_id,reaction:{code:RA(te,"reaction"),count:1}};c.emit("newsletter.reaction",he);break}case"view":{let he={id:Y,server_id:te.attrs.message_id,count:parseInt(te.content?.toString()||"0",10)};c.emit("newsletter.view",he);break}case"participant":{let he={id:Y,author:ee,user:te.attrs.jid,action:te.attrs.action,new_role:te.attrs.role};c.emit("newsletter-participants.update",he);break}case"update":{let he=ie(te,"settings");if(he){let se={},ge=ie(he,"name");ge?.content&&(se.name=ge.content.toString());let Ee=ie(he,"description");Ee?.content&&(se.description=Ee.content.toString()),c.emit("newsletter-settings.update",{id:Y,update:se})}break}case"message":{let he=ie(te,"plaintext");if(he?.content)try{let se=typeof he.content=="string"?Buffer.from(he.content,"binary"):Buffer.from(he.content),ge=Ae.Message.decode(se).toJSON(),Ee=Ae.WebMessageInfo.fromObject({key:{remoteJid:Y,id:te.attrs.message_id||te.attrs.server_id,fromMe:!1},message:ge,messageTimestamp:+te.attrs.t}).toJSON();await R(Ee,"append"),r.debug("Processed plaintext newsletter message")}catch(se){r.error({error:se},"Failed to decode plaintext newsletter message")}break}default:r.warn({node:Z,child:te},"Unknown newsletter notification child");break}},ce=async(Z,Y)=>{let z=W9(Z,Y,l.creds.me.id);r.debug({recv:{tag:Z.tag,attrs:Z.attrs},sent:z.attrs},"sent ack"),await x(z)},Ye=async(Z,Y)=>{let z={tag:"call",attrs:{from:l.creds.me.id,to:Y},content:[{tag:"reject",attrs:{"call-id":Z,"call-creator":Y,count:"0"},content:void 0}]};await m(z)},ve=async(Z,Y=!1)=>{let{fullMessage:z}=CT(Z,l.creds.me.id,l.creds.me.lid||""),{key:ee}=z,te=ee.id;if(T){if(T.hasExceededMaxRetries(te)){r.debug({msgId:te},"reached retry limit with new retry manager, clearing"),T.markRetryFailed(te);return}let LA=T.incrementRetryCount(te),jA=`${te}:${ee?.participant}`;await me.set(jA,LA)}else{let LA=`${te}:${ee?.participant}`,jA=await me.get(LA)||0;if(jA>=i){r.debug({retryCount:jA,msgId:te},"reached retry limit, clearing"),await me.del(LA);return}jA+=1,await me.set(LA,jA)}let he=`${te}:${ee?.participant}`,se=await me.get(he)||1,{account:ge,signedPreKey:Ee,signedIdentityKey:Pe}=l.creds,tA=Z.attrs.from,CA=!1,UA="";if(A&&T&&se>1)try{let LA=y.jidToSignalProtocolAddress(tA),jA=await y.validateSession(tA),Oe=T.shouldRecreateSession(tA,jA.exists);CA=Oe.recreate,UA=Oe.reason,CA&&(r.debug({fromJid:tA,retryCount:se,reason:UA},"recreating session for retry"),await l.keys.set({session:{[LA]:null}}),Y=!0)}catch(LA){r.warn({error:LA,fromJid:tA},"failed to check session recreation")}if(se<=2)if(T)T.schedulePhoneRequest(te,async()=>{try{let LA=await Xe(ee);r.debug(`sendRetryRequest: requested placeholder resend (${LA}) for message ${te} (scheduled)`)}catch(LA){r.warn({error:LA,msgId:te},"failed to send scheduled phone request")}});else{let LA=await Xe(ee);r.debug(`sendRetryRequest: requested placeholder resend for message ${LA}`)}let MA=Wh(ge,!0);await l.keys.transaction(async()=>{let LA={tag:"receipt",attrs:{id:te,type:"retry",to:Z.attrs.from},content:[{tag:"retry",attrs:{count:se.toString(),id:Z.attrs.id,t:Z.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:Rn(l.creds.registrationId)}]};if(Z.attrs.recipient&&(LA.attrs.recipient=Z.attrs.recipient),Z.attrs.participant&&(LA.attrs.participant=Z.attrs.participant),se>1||Y||CA){let{update:jA,preKeys:Oe}=await vk(l,1),[gA]=Object.keys(Oe),xA=Oe[+gA];LA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Tn)},{tag:"identity",attrs:{},content:Pe.public},kk(xA,+gA),zh(Ee),{tag:"device-identity",attrs:{},content:MA}]}),c.emit("creds.update",jA)}await x(LA),r.info({msgAttrs:Z.attrs,retryCount:se},"sent retry receipt")},l?.creds?.me?.id||"sendRetryRequest")},ue=new Set,aA=Z=>{(async()=>{let Y=oA(Z),z=await Zo(Y,X),te=(await l.keys.get("tctoken",[z]))?.[z]?.senderTimestamp;if(te==null||vc(te))return;r.debug({jid:Y,senderTimestamp:te},"identity changed, re-issuing tctoken");let he=y.lidMapping.getPNForLID.bind(y.lidMapping),se=await Ad(Y,t.serverProps.lidTrustedTokenIssueToLid,X,he),ge=await U([se],te);await IE({result:ge,fallbackJid:z,keys:l.keys,getLIDForPN:X,onNewJidStored:OA})})().catch(Y=>{r.debug({jid:Z,err:Y?.message},"failed to re-issue tctoken after identity change")})},iA=async Z=>{if(Z.attrs.from===uA){let z=Z.attrs.id;if(z&&ue.has(z))return;let te=+ie(Z,"count").attrs.value,he=te{let ee=Z.attrs.participant,te=Z.attrs.participant_pn,he=Z.attrs.participant_username,se=ie(Y,"participant")?.attrs?.jid||ee,ge=ie(Y,"participant")?.attrs?.phone_number||te;switch(Y?.tag){case"create":let Ee=mE(Y);z.messageStubType=QA.GROUP_CREATE,z.messageStubParameters=[Ee.subject],z.key={participant:Ee.owner,participantAlt:Ee.ownerPn},c.emit("chats.upsert",[{id:Ee.id,name:Ee.subject,conversationTimestamp:Ee.creation}]),c.emit("groups.upsert",[{...Ee,author:ee,authorPn:te,authorUsername:he}]);break;case"ephemeral":case"not_ephemeral":z.message={protocolMessage:{type:Ae.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(Y.attrs.expiration||0)}};break;case"modify":let Pe=mA(Y,"participant").map(Oe=>Oe.attrs.jid);z.messageStubParameters=Pe||[],z.messageStubType=QA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let tA=`GROUP_PARTICIPANT_${Y.tag.toUpperCase()}`;z.messageStubType=QA[tA];let CA=mA(Y,"participant").map(({attrs:Oe})=>({id:Oe.jid,phoneNumber:vA(Oe.jid)&&nt(Oe.phone_number)?Oe.phone_number:void 0,lid:nt(Oe.jid)&&vA(Oe.lid)?Oe.lid:void 0,username:Oe.participant_username||Oe.username||void 0,admin:Oe.type||null}));CA.length===1&&(lt(CA[0].id,ee)||lt(CA[0].id,te))&&Y.tag==="remove"&&(z.messageStubType=QA.GROUP_PARTICIPANT_LEAVE),z.messageStubParameters=CA.map(Oe=>JSON.stringify(Oe));break;case"subject":z.messageStubType=QA.GROUP_CHANGE_SUBJECT,z.messageStubParameters=[Y.attrs.subject];break;case"description":let UA=ie(Y,"body")?.content?.toString();z.messageStubType=QA.GROUP_CHANGE_DESCRIPTION,z.messageStubParameters=UA?[UA]:void 0;break;case"announcement":case"not_announcement":z.messageStubType=QA.GROUP_CHANGE_ANNOUNCE,z.messageStubParameters=[Y.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":z.messageStubType=QA.GROUP_CHANGE_RESTRICT,z.messageStubParameters=[Y.tag==="locked"?"on":"off"];break;case"invite":z.messageStubType=QA.GROUP_CHANGE_INVITE_LINK,z.messageStubParameters=[Y.attrs.code];break;case"member_add_mode":let MA=Y.content;MA&&(z.messageStubType=QA.GROUP_MEMBER_ADD_MODE,z.messageStubParameters=[MA.toString()]);break;case"membership_approval_mode":let LA=ie(Y,"group_join");LA&&(z.messageStubType=QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,z.messageStubParameters=[LA.attrs.state]);break;case"created_membership_requests":z.messageStubType=QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,z.messageStubParameters=[JSON.stringify({lid:se,pn:ge}),"created",Y.attrs.request_method];break;case"revoked_membership_requests":let jA=lt(se,ee);z.messageStubType=QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,z.messageStubParameters=[JSON.stringify({lid:se,pn:ge}),jA?"revoked":"rejected"];break}},Ue=async Z=>{let[Y]=bo(Z),z=oA(Z.attrs.from);if(!Y){r.debug({from:z},"devices notification missing child, skipping");return}let ee=Y.tag,te=Y.attrs.device_hash,he=mA(Y,"device");if(lt(z,l.creds.me.id)||lt(z,l.creds.me.lid)){let ge=he.map(Ee=>Ee.attrs.jid);r.info({deviceJids:ge},"got my own devices")}if(!he.length){r.debug({from:z,tag:ee},"no devices in notification, skipping");return}let se=[];for(let ge of he){let Ee=ge.attrs.jid;if(!Ee)continue;let Pe=lA(Ee);if(!Pe){r.debug({jid:Ee},"failed to decode device jid, skipping");continue}se.push({jid:Ee,user:Pe.user,server:Pe.server,device:Pe.device})}se.length&&await g.mutex(async()=>{let ge=new Map;for(let Ee of se){let Pe=ge.get(Ee.user)||[];Pe.push(Ee),ge.set(Ee.user,Pe)}for(let[Ee,Pe]of ge){if(ee==="update"){r.debug({user:Ee},`${Ee}'s device list updated, dropping cached devices`),await s?.del(Ee);continue}ee==="remove"&&await y.deleteSession(Pe.map(MA=>MA.jid));let tA=await s?.get(Ee)||[];if(!tA.length){r.debug({user:Ee,tag:ee},"device list not cached, deferring to USync refresh");continue}let CA=new Set(Pe.map(MA=>MA.device)),UA;switch(ee){case"add":r.info({deviceHash:te,count:Pe.length},"devices added"),UA=[...tA.filter(MA=>!CA.has(MA.device)),...Pe.map(MA=>({user:MA.user,server:MA.server,device:MA.device}))];break;case"remove":r.info({deviceHash:te,count:Pe.length},"devices removed"),UA=tA.filter(MA=>!CA.has(MA.device));break;default:r.debug({tag:ee},"Unknown device list change tag");continue}UA.length===0?await s?.del(Ee):await s?.set(Ee,UA)}})},yA=async Z=>{let Y={},[z]=bo(Z),ee=Z.attrs.type,te=oA(Z.attrs.from);switch(ee){case"newsletter":await Ce(Z);break;case"mex":await rA(Z);break;case"w:gp2":$e(Z,z,Y);break;case"mediaretry":let he=NZ(Z);c.emit("messages.media-update",[he]);break;case"encrypt":await iA(Z);break;case"devices":try{await Ue(Z)}catch(co){r.error({error:co,node:Z},"failed to handle devices notification")}break;case"server_sync":let se=ie(Z,"collection");if(se){let co=se.attrs.name;await k([co],!1)}break;case"picture":let ge=ie(Z,"set"),Ee=ie(Z,"delete");if(c.emit("contacts.update",[{id:oA(Z?.attrs?.from)||(ge||Ee)?.attrs?.hash||"",imgUrl:ge?"changed":"removed"}]),ir(te)){let co=ge||Ee;Y.messageStubType=QA.GROUP_CHANGE_ICON,ge&&(Y.messageStubParameters=[ge.attrs.id]),Y.participant=co?.attrs.author,Y.key={...Y.key||{},participant:ge?.attrs.author}}break;case"account_sync":if(z.tag==="disappearing_mode"){let co=+z.attrs.duration,Cd=+z.attrs.t;r.info({newDuration:co},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...l.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:co,ephemeralSettingTimestamp:Cd}}})}else if(z.tag==="blocklist"){let co=mA(z,"item");for(let{attrs:Cd}of co){let X$=[Cd.jid],$$=Cd.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:X$,type:$$})}}break;case"link_code_companion_reg":let Pe=ie(Z,"link_code_companion_reg"),tA=rt(vr(Pe,"link_code_pairing_ref")),CA=rt(vr(Pe,"primary_identity_pub")),UA=rt(vr(Pe,"link_code_pairing_wrapped_primary_ephemeral_pub")),MA=await BA(UA),LA=Ut.sharedKey(l.creds.pairingEphemeralKeyPair.private,MA),jA=lP(32),Oe=lP(32),gA=eo(LA,32,{salt:Oe,info:"link_code_pairing_key_bundle_encryption_key"}),xA=Buffer.concat([Buffer.from(l.creds.signedIdentityKey.public),CA,jA]),Kr=lP(12),Yt=sc(xA,gA,Kr,Buffer.alloc(0)),go=Buffer.concat([Oe,Kr,Yt]),W$=Ut.sharedKey(l.creds.signedIdentityKey.private,CA),Z$=Buffer.concat([LA,W$,jA]);l.creds.advSecretKey=Buffer.from(eo(Z$,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:uA,type:"set",id:t.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:l.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:go},{tag:"companion_identity_public",attrs:{},content:l.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:tA}]}]}),l.creds.registered=!0,c.emit("creds.update",l.creds);break;case"privacy_token":await zA(Z);break}if(Object.keys(Y).length)return Y},Ie=new Set,ye=(async()=>{try{let Z=await $m(l.keys);for(let Y of Z)Ie.add(Y);r.debug({count:Ie.size},"loaded tctoken index")}catch(Z){r.warn({err:Z?.message},"failed to load tctoken index")}})(),_e;async function DA(){_e&&(clearTimeout(_e),_e=void 0);let Z=await cE(l.keys,Ie);return l.keys.set({tctoken:Z})}function Te(){_e&&clearTimeout(_e),_e=setTimeout(()=>{_e=void 0,DA().catch(Z=>{r.warn({err:Z?.message},"failed to save tctoken index")})},5e3)}function OA(Z){Z&&Z!==sg&&!Ie.has(Z)&&(Ie.add(Z),Te())}let zA=async Z=>{if(!ie(Z,"tokens"))return;let z=oA(Z.attrs.from),te=(Z.attrs.sender_lid&&vA(oA(Z.attrs.sender_lid))?oA(Z.attrs.sender_lid):void 0)??await Zo(z,X);r.debug({from:z,storageJid:te},"processing privacy token notification"),await IE({result:Z,fallbackJid:te,keys:l.keys,getLIDForPN:X,onNewJidStored:OA})};async function BA(Z){let Y=rt(Z),z=Y.slice(0,32),ee=await Lf(l.creds.pairingCode,z),te=Y.slice(32,48),he=Y.slice(48,80);return Oq(he,ee,te)}function rt(Z){if(Z===void 0)throw new Ed.Boom("Invalid buffer",{statusCode:400});return Z instanceof Buffer?Z:Buffer.from(Z)}let Jt=async(Z,Y)=>{let z=`${Z}:${Y}`;return(await me.get(z)||0){let z=`${Z}:${Y}`,ee=(await me.get(z)||0)+1;await me.set(z,ee)},oe=async(Z,Y,z,ee)=>{let te=Z.remoteJid,he=Z.participant||te,se=+z.attrs.count||1,ge=Y[0],Ee=[];for(let Oe of Y){let gA;if(T){let xA=T.getRecentMessage(te,Oe);xA&&(gA=xA.message,r.debug({jid:te,id:Oe},"found message in retry cache"),T.markRetrySuccess(Oe))}gA||(gA=await e({...Z,id:Oe}),gA&&(r.debug({jid:te,id:Oe},"found message via getMessage"),T&&T.markRetrySuccess(Oe))),Ee.push(gA)}let Pe=!lA(he)?.device,tA=y.jidToSignalProtocolAddress(he),CA=!1,UA=WZ(ee);if(UA)try{await y.injectE2ESession({jid:he,session:UA}),CA=!0,r.debug({participant:he,retryCount:se},"injected session from retry receipt key bundle")}catch(Oe){r.warn({error:Oe,participant:he},"failed to inject session from retry receipt")}if(!CA){let Oe=vs(ee,"registration",4);if(typeof Oe=="number"&&Number.isInteger(Oe)){let gA=await y.getSessionInfo(he);gA&&gA.registrationId!==0&&gA.registrationId!==Oe&&(r.info({participant:he,stored:gA.registrationId,received:Oe},"reg id mismatch on retry without bundle, deleting session"),await l.keys.set({session:{[tA]:null}}))}}let MA=2;if(ge&&T){let Oe=await y.getSessionInfo(he);Oe&&(se===MA?T.saveBaseKey(tA,ge,Oe.baseKey):se>MA&&(T.hasSameBaseKey(tA,ge,Oe.baseKey)&&(r.warn({participant:he,retryCount:se},"base key collision on retry, forcing fresh session"),await l.keys.set({session:{[tA]:null}})),T.deleteBaseKey(tA,ge)))}let LA=!1,jA="";if(A&&T&&se>1&&!CA)try{let Oe=await y.validateSession(he),gA=T.shouldRecreateSession(he,Oe.exists);LA=gA.recreate,jA=gA.reason,LA&&(r.debug({participant:he,retryCount:se,reason:jA},"recreating session for outgoing retry"),await l.keys.set({session:{[tA]:null}}))}catch(Oe){r.warn({error:Oe,participant:he},"failed to check session recreation for outgoing retry")}CA||await K([he],!0),ir(te)&&await l.keys.set({"sender-key-memory":{[te]:null}}),r.debug({participant:he,sendToAll:Pe,shouldRecreateSession:LA,recreateReason:jA,injectedFromBundle:CA},"prepared session for retry resend");for(let[Oe,gA]of Ee.entries())if(Y[Oe])if(gA&&await Jt(Y[Oe],he)){await NA(Y[Oe],he);let xA={messageId:Y[Oe]};Pe?xA.useUserDevicesCache=!1:xA.participant={jid:he,count:+z.attrs.count},await H(Z.remoteJid,gA,xA)}else r.debug({jid:Z.remoteJid,id:Y[Oe]},"recv retry request, but message not available")},le=async Z=>{let{attrs:Y,content:z}=Z,ee=Y.from.includes("lid"),te=lt(Y.participant||Y.from,ee?l.creds.me?.lid:l.creds.me?.id),he=!te||ir(Y.from)?Y.from:Y.recipient,se=!Y.recipient||(Y.type==="retry"||Y.type==="sender")&&te,ge={remoteJid:he,id:"",fromMe:se,participant:Y.participant},Ee=[Y.id];if(Array.isArray(z)){let Pe=mA(z[0],"item");Ee.push(...Pe.map(tA=>tA.attrs.id))}try{await Promise.all([f.mutex(async()=>{let Pe=Lq(Y.type);if(typeof Pe<"u"&&(Pe>=Ae.WebMessageInfo.Status.SERVER_ACK||!te))if(ir(he)||_n(he)){if(Y.participant){let tA=Pe===Ae.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",Ee.map(CA=>({key:{...ge,id:CA},receipt:{userJid:oA(Y.participant),[tA]:+Y.t}})))}}else c.emit("messages.update",Ee.map(tA=>({key:{...ge,id:tA},update:{status:Pe,messageTimestamp:or(+(Y.t??0))}})));if(Y.type==="retry"){ge.participant=ge.participant||Y.from;let tA=ie(Z,"retry");if(Ee[0]&&ge.participant&&await Jt(Ee[0],ge.participant))if(ge.fromMe)try{await NA(Ee[0],ge.participant),r.debug({attrs:Y,key:ge},"recv retry request"),await oe(ge,Ee,tA,Z)}catch(CA){r.error({key:ge,ids:Ee,trace:CA instanceof Error?CA.stack:"Unknown error"},"error in sending message again")}else r.info({attrs:Y,key:ge},"recv retry for not fromMe message");else r.info({attrs:Y,key:ge},"will not send message again, as sent too many times")}})])}finally{await ce(Z).catch(Pe=>r.error({ackErr:Pe},"failed to ack receipt"))}},Be=async Z=>{let Y=Z.attrs.from;try{await Promise.all([Q.mutex(async()=>{let z=await yA(Z);if(z){let ee=lt(Z.attrs.participant||Y,l.creds.me.id),{senderAlt:te,addressingMode:he}=Yf(Z);z.key={remoteJid:Y,fromMe:ee,participant:Z.attrs.participant,participantAlt:te,participantUsername:Z.attrs.participant_username,addressingMode:he,id:Z.attrs.id,...z.key||{}},z.participant??(z.participant=Z.attrs.participant),z.messageTimestamp=+Z.attrs.t;let se=Ae.WebMessageInfo.fromObject(z);await R(se,"append")}})])}finally{await ce(Z).catch(z=>r.error({ackErr:z},"failed to ack notification"))}},eA=async Z=>{if(ie(Z,"enc")?.attrs.type==="msmsg"){r.debug({key:Z.attrs.key},"ignored msmsg"),await ce(Z,Ic.MissingMessageSecret);return}let z=!1;try{let{fullMessage:ee,category:te,author:he,decrypt:se}=qq(Z,l.creds.me.id,l.creds.me.lid||"",y,r),ge=ee.key.participantAlt||ee.key.remoteJidAlt;if(ge){let Ee=lA(ge)?.server,Pe=ee.key.participant||ee.key.remoteJid;Ee==="lid"?await y.lidMapping.getPNForLID(ge)||(await y.lidMapping.storeLIDPNMappings([{lid:ge,pn:Pe}]),await y.migrateSession(Pe,ge)):(await y.lidMapping.storeLIDPNMappings([{lid:Pe,pn:ge}]),await y.migrateSession(ge,Pe))}await B.mutex(async()=>{if(await se(),ee.key?.remoteJid&&ee.key?.id&&ee.message&&T&&T.addRecentMessage(ee.key.remoteJid,ee.key.id,ee.message),ee.messageStubType===Ae.WebMessageInfo.StubType.CIPHERTEXT&&ee.category!=="peer"){if(ee?.messageStubParameters?.[0]===jq)return z=!0,ce(Z,Ic.ParsingError);if(ee.messageStubParameters?.[0]===Kf){let Pe=ie(Z,"unavailable")?.attrs?.type;if(Pe==="bot_unavailable_fanout"||Pe==="hosted_unavailable_fanout"||Pe==="view_once_unavailable_fanout")return r.debug({msgId:ee.key.id,unavailableType:Pe},"skipping placeholder resend for excluded unavailable type"),z=!0,ce(Z);let tA=Pr()-or(ee.messageTimestamp);if(tA>I$)return r.debug({msgId:ee.key.id,messageAge:tA},"skipping placeholder resend for old message"),z=!0,ce(Z);let CA={remoteJid:ee.key.remoteJid,fromMe:ee.key.fromMe,id:ee.key.id,participant:ee.key.participant},UA={key:ee.key,messageTimestamp:ee.messageTimestamp,pushName:ee.pushName,participant:ee.participant,verifiedBizName:ee.verifiedBizName};Xe(CA,UA).then(MA=>{MA&&MA!=="RESOLVED"&&(r.debug({msgId:ee.key.id,requestId:MA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:ee.key,update:{messageStubParameters:[Kf,MA]}}]))}).catch(MA=>{r.warn({err:MA,msgId:ee.key.id},"failed to request placeholder resend for unavailable message")}),z=!0,await ce(Z)}else{if(_n(ee.key.remoteJid)){let Ee=Pr()-or(ee.messageTimestamp);if(Ee>c$)return r.debug({msgId:ee.key.id,messageAge:Ee,remoteJid:ee.key.remoteJid},"skipping retry for expired status message"),z=!0,ce(Z)}r.debug("[handleMessage] Attempting retry request for failed decryption"),await pe.mutex(async()=>{try{if(!p.isOpen){r.debug({node:Z},"Connection closed, skipping retry");return}let Ee=ie(Z,"enc");await ve(Z,!Ee),o&&await ZC(o)}catch(Ee){r.error({err:Ee},"Failed to send retry")}z=!0,await ce(Z,Ic.UnhandledError)})}}else if(T&&ee.key.id&&T.cancelPendingPhoneRequest(ee.key.id),ks(ee.key.remoteJid))z=!0,await ce(Z),r.debug({key:ee.key},"processed newsletter message without receipts");else{let Pe,tA=ee.key.participant;if(te==="peer"?Pe="peer_msg":ee.key.fromMe?(Pe="sender",(vA(ee.key.remoteJid)||vA(ee.key.remoteJidAlt))&&(tA=he)):Ge||(Pe="inactive"),z=!0,await q(ee.key.remoteJid,tA,[ee.key.id],Pe),Jm(ee.message)){let UA=oA(ee.key.remoteJid);await q(UA,void 0,[ee.key.id],"hist_sync")}}Y9(ee,l.creds.me.id,l.creds.me.lid),await R(ee,Z.attrs.offline?"append":"notify")})}catch(ee){r.error({error:ee,node:Zi(Z)},"error in handling message"),z||await ce(Z,Ic.UnhandledError).catch(te=>r.error({ackErr:te},"failed to ack message after error"))}},IA=async Z=>{try{let{attrs:Y}=Z,[z]=bo(Z);if(!z)throw new Ed.Boom("Missing call info in call node");let ee=Hq(z),te=z.attrs["call-id"],he=z.attrs.from||z.attrs["call-creator"],se={chatId:Y.from,from:he,callerPn:z.attrs.caller_pn,id:te,date:new Date(+Y.t*1e3),offline:!!Y.offline,status:ee};if(ee==="relaylatency"){let Ee=z.attrs.latency||z.attrs.latency_ms||z.attrs["latency-ms"],Pe=Ee?Number(Ee):void 0;Number.isFinite(Pe)&&(se.latencyMs=Pe)}ee==="offer"&&(se.isVideo=!!ie(z,"video"),se.isGroup=z.attrs.type==="group"||!!z.attrs["group-jid"],se.groupJid=z.attrs["group-jid"],await qe.set(se.id,se));let ge=await qe.get(se.id);ge&&(se.isVideo=ge.isVideo,se.isGroup=ge.isGroup,se.callerPn=se.callerPn||ge.callerPn),(ee==="reject"||ee==="accept"||ee==="timeout"||ee==="terminate")&&await qe.del(se.id),c.emit("call",[se])}catch(Y){r.error({error:Y,node:Zi(Z)},"error in handling call")}finally{await ce(Z).catch(Y=>r.error({ackErr:Y},"failed to ack call"))}},TA=async({attrs:Z})=>{let Y={remoteJid:Z.from,fromMe:!0,id:Z.id};if(Z.error){let z=Z.error===String(Ic.SenderReachoutTimelocked);if(Z.error===pT.MessageAccountRestriction){r.warn({msgId:Z.id,from:Z.from},"error 463: account restricted or missing tctoken for contact");let ee=Z.from;ee&&!rn.has(ee)&&(rn.add(ee),(async()=>{try{let te=y.lidMapping.getPNForLID.bind(y.lidMapping),he=await Zo(ee,X),se=await Ad(ee,t.serverProps.lidTrustedTokenIssueToLid,X,te),ge=await U([se],Pr());await IE({result:ge,fallbackJid:he,keys:l.keys,getLIDForPN:X,onNewJidStored:OA}),r.debug({from:ee},"completed 463 token recovery issuance")}catch(te){r.debug({from:ee,err:te?.message},"failed 463 token recovery issuance")}finally{rn.delete(ee)}})())}else Z.error===pT.SmaxInvalid?r.warn({msgId:Z.id,from:Z.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):z?(await b().catch(ee=>r.warn({err:ee},"failed to fetch reachout timelock")),r.warn({attrs:Z},"received error in ack")):r.warn({attrs:Z},"received error in ack");c.emit("messages.update",[{key:Y,update:{status:sl.ERROR,messageStubParameters:z?[Z.error,Jq]:[Z.error]}}])}},wt=async(Z,Y,z)=>{c.buffer(),await ee(),c.flush();function ee(){return z(Z,!1).catch(te=>G(te,Y))}},WA=T$(new Map([["message",eA],["call",IA],["receipt",le],["notification",Be]]),{isWsOpen:()=>p.isOpen,onUnexpectedError:G,yieldToEventLoop:()=>new Promise(Z=>setImmediate(Z))}),Er=async(Z,Y,z,ee)=>{let te=Y.attrs.from,he=te;if(Z==="receipt"&&te){let ge=Y.attrs,Ee=ge.from.includes("lid");he=!lt(ge.participant||ge.from,Ee?l.creds.me?.lid:l.creds.me?.id)||ir(ge.from)?ge.from:ge.recipient}if(he&&he!==uA&&a(he)){await ce(Y,Z==="message"?Ic.UnhandledError:void 0);return}!!Y.attrs.offline?WA.enqueue(Z,Y):await wt(Y,z,ee)};p.on("CB:message",async Z=>{await Er("message",Z,"processing message",eA)}),p.on("CB:call",async Z=>{await Er("call",Z,"handling call",IA)}),p.on("CB:receipt",async Z=>{await Er("receipt",Z,"handling receipt",le)}),p.on("CB:notification",async Z=>{await Er("notification",Z,"handling notification",Be)}),p.on("CB:ack,class:message",Z=>{TA(Z).catch(Y=>G(Y,"handling bad ack"))}),c.on("call",async([Z])=>{if(Z&&(Z.status==="timeout"||Z.status==="offer"&&Z.isGroup)){let Y={key:{remoteJid:Z.chatId,id:Z.id,fromMe:!1},messageTimestamp:Pr(Z.date)};Z.status==="timeout"?Z.isGroup?Y.messageStubType=Z.isVideo?QA.CALL_MISSED_GROUP_VIDEO:QA.CALL_MISSED_GROUP_VOICE:Y.messageStubType=Z.isVideo?QA.CALL_MISSED_VIDEO:QA.CALL_MISSED_VOICE:Y.message={call:{callKey:Buffer.from(Z.id)}};let z=Ae.WebMessageInfo.fromObject(Y);await R(z,Z.offline?"append":"notify")}});let Kt=0,rn=new Set;c.on("connection.update",({isOnline:Z,connection:Y})=>{if(typeof Z<"u"&&(Ge=Z,r.trace(`sendActiveReceipts set to "${Ge}"`)),Y==="close"&&_e){clearTimeout(_e),_e=void 0;try{Promise.resolve(DA()).catch(()=>{})}catch{}}if(Z){let z=Date.now(),ee=1440*60*1e3;z-Kt>=ee&&(Kt=z,an())}}),V(()=>{!n.msgRetryCounterCache&&me.close&&me.close(),!n.callOfferCache&&qe.close&&qe.close(),Se.close(),Ge=!1});async function an(){try{await ye;let Z=await $m(l.keys),Y=new Set(Ie);for(let ge of Z)Y.add(ge);if(!Y.size)return;let z=[...Y],ee=await l.keys.get("tctoken",z),te={},he=new Set,se=0;for(let ge of z){let Ee=ee[ge];if(!Ee){se++;continue}let Pe=!!Ee.token?.length,tA=Pe&&vc(Ee.timestamp),CA=Ee.senderTimestamp!==void 0,UA=CA&&vc(Ee.senderTimestamp),MA=Pe&&!tA,LA=CA&&!UA;!MA&&!LA?(te[ge]=null,se++):tA&&LA?(te[ge]={token:Buffer.alloc(0),senderTimestamp:Ee.senderTimestamp},he.add(ge),se++):he.add(ge)}if(se===0)return;await l.keys.set({tctoken:{...te,[sg]:{token:Buffer.from(JSON.stringify([...he]))}}}),Ie.clear();for(let ge of he)Ie.add(ge);r.debug({mutated:se,remaining:he.size},"pruned expired tctokens")}catch(Z){r.warn({err:Z?.message},"failed to prune expired tctokens")}}return{...t,sendMessageAck:ce,sendRetryRequest:ve,rejectCall:Ye,fetchMessageHistory:je,requestPlaceholderResend:Xe,messageRetryManager:T}};var L$=n=>{let r=F$(n),{authState:o,query:i,waUploadToServer:e}=r,a=async Q=>{let f=[],y=["address","email","description"];return f.push(...y.filter(R=>Q[R]!==void 0&&Q[R]!==null).map(R=>({tag:R,attrs:{},content:Q[R]}))),Q.websites!==void 0&&f.push(...Q.websites.map(R=>({tag:"website",attrs:{},content:R}))),Q.hours!==void 0&&f.push({tag:"business_hours",attrs:{timezone:Q.hours.timezone},content:Q.hours.days.map(R=>{let k={tag:"business_hours_config",attrs:{day_of_week:R.day,mode:R.mode}};return R.mode==="specific_hours"?{...k,attrs:{...k.attrs,open_time:R.openTimeInMinutes,close_time:R.closeTimeInMinutes}}:k})}),await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:f}]})},A=async Q=>{let{fileSha256:f,filePath:y}=await Um(Q,"biz-cover-photo"),m=f.toString("base64"),{meta_hmac:R,fbid:k,ts:G}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(k),op:"update",token:R,ts:String(G)}}]}]}),k},t=async Q=>await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:Q}}]}]}),s=async({jid:Q,limit:f,cursor:y})=>{Q=Q||o.creds.me?.id,Q=oA(Q);let m=[{tag:"limit",attrs:{},content:Buffer.from((f||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 R=await i({tag:"iq",attrs:{to:uA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:Q,allow_shop_source:"true"},content:m}]});return u$(R)},g=async(Q,f=51)=>{Q=Q||o.creds.me?.id,Q=oA(Q);let y=await i({tag:"iq",attrs:{to:uA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:Q},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(f.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(f.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return B$(y)},c=async(Q,f)=>{let y=await i({tag:"iq",attrs:{to:uA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:Q},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(f)}]}]});return Q$(y)},l=async(Q,f)=>{f=await oP(f,e);let y=iP(Q,f),m=await i({tag:"iq",attrs:{to:uA,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"}]}]}),R=ie(m,"product_catalog_edit"),k=ie(R,"product");return Id(k)},p=async Q=>{Q.isHidden=!!Q.isHidden,Q=await oP(Q,e);let f=iP(void 0,Q),y=await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[f,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=ie(y,"product_catalog_add"),R=ie(m,"product");return Id(R)},B=async Q=>{let f=await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:Q.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(ie(f,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...r,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:p,productDelete:B,productUpdate:l,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:t}};var U$=n=>{let r=L$(n),{authState:o,ev:i,query:e,upsertMessage:a}=r,A=async(l,p,B)=>e({tag:"iq",attrs:{type:p,xmlns:"w:g2",to:l},content:B}),t=async l=>{let p=await A(l,"get",[{tag:"query",attrs:{request:"interactive"}}]);return EP(p)},s=async()=>{let l=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),p={},B=ie(l,"communities");if(B){let Q=mA(B,"community");for(let f of Q){let y=EP({tag:"result",attrs:{},content:[f]});p[y.id]=y}}return r.ev.emit("groups.update",Object.values(p)),p};async function g(l){sd.info({node:l},"parseGroupResult");let p=ie(l,"group");if(p)try{sd.info({groupNode:p},"groupNode");let B=await r.groupMetadata(`${p.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:l=>l!==null?{value:l}:null};return r.ws.on("CB:ib,,dirty",async l=>{let{attrs:p}=ie(l,"dirty");p.type==="communities"&&(await s(),await r.cleanDirtyBits("groups"))}),{...r,communityMetadata:t,communityCreate:async(l,p)=>{let B=lT().substring(0,12),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:l},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(p||"","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(Q)},communityCreateGroup:async(l,p,B)=>{let Q=nr(),f=await A("@g.us","set",[{tag:"create",attrs:{subject:l,key:Q},content:[...p.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(f)},communityLeave:async l=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:l}}]}])},communityUpdateSubject:async(l,p)=>{await A(l,"set",[{tag:"subject",attrs:{},content:Buffer.from(p,"utf-8")}])},communityLinkGroup:async(l,p)=>{await A(p,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:l}}]}]}])},communityUnlinkGroup:async(l,p)=>{await A(p,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:l}}]}])},communityFetchLinkedGroups:async l=>{let p=l,B=!1,Q=await r.groupMetadata(l);Q.linkedParent?p=Q.linkedParent:B=!0;let f=await A(p,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=ie(f,"sub_groups");if(m){let R=mA(m,"group");for(let k of R)y.push({id:k.attrs.id?Ft(k.attrs.id,"g.us"):void 0,subject:k.attrs.subject||"",creation:k.attrs.creation?Number(k.attrs.creation):void 0,owner:k.attrs.creator?oA(k.attrs.creator):void 0,size:k.attrs.size?Number(k.attrs.size):void 0})}return{communityJid:p,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async l=>{let p=await A(l,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=ie(p,"membership_approval_requests");return mA(B,"membership_approval_request").map(f=>f.attrs)},communityRequestParticipantsUpdate:async(l,p,B)=>{let Q=await A(l,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:p.map(R=>({tag:"participant",attrs:{jid:R}}))}]}]),f=ie(Q,"membership_requests_action"),y=ie(f,B);return mA(y,"participant").map(R=>({status:R.attrs.error||"200",jid:R.attrs.jid}))},communityParticipantsUpdate:async(l,p,B)=>{let Q=await A(l,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:p.map(m=>({tag:"participant",attrs:{jid:m}}))}]),f=ie(Q,B);return mA(f,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(l,p)=>{let Q=(await t(l)).descId??null;await A(l,"set",[{tag:"description",attrs:{...p?{id:lT()}:{delete:"true"},...Q?{prev:Q}:{}},content:p?[{tag:"body",attrs:{},content:Buffer.from(p,"utf-8")}]:void 0}])},communityInviteCode:async l=>{let p=await A(l,"get",[{tag:"invite",attrs:{}}]);return ie(p,"invite")?.attrs.code},communityRevokeInvite:async l=>{let p=await A(l,"set",[{tag:"invite",attrs:{}}]);return ie(p,"invite")?.attrs.code},communityAcceptInvite:async l=>{let p=await A("@g.us","set",[{tag:"invite",attrs:{code:l}}]);return ie(p,"community")?.attrs.jid},communityRevokeInviteV4:async(l,p)=>!!await A(l,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:p}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(l,p)=>{l=typeof l=="string"?{remoteJid:l}:l;let B=await A(p.groupJid,"set",[{tag:"accept",attrs:{code:p.inviteCode,expiration:p.inviteExpiration.toString(),admin:l.remoteJid}}]);return l.id&&(p=Ae.Message.GroupInviteMessage.fromObject(p),p.inviteExpiration=0,p.inviteCode="",i.emit("messages.update",[{key:l,update:{message:{groupInviteMessage:p}}}])),await a({key:{remoteJid:p.groupJid,id:nr(r.user?.id),fromMe:!1,participant:l.remoteJid},messageStubType:QA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:l.remoteJid,messageTimestamp:Pr()},"notify"),B.attrs.from}),communityGetInviteInfo:async l=>{let p=await A("@g.us","get",[{tag:"invite",attrs:{code:l}}]);return EP(p)},communityToggleEphemeral:async(l,p)=>{let B=p?{tag:"ephemeral",attrs:{expiration:p.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(l,"set",[B])},communitySettingUpdate:async(l,p)=>{await A(l,"set",[{tag:p,attrs:{}}])},communityMemberAddMode:async(l,p)=>{await A(l,"set",[{tag:"member_add_mode",attrs:{},content:p}])},communityJoinApprovalMode:async(l,p)=>{await A(l,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:p}}]}])},communityFetchAllParticipating:s}},EP=n=>{let r=ie(n,"community"),o=ie(r,"description"),i,e;o&&(i=RA(o,"body"),e=o.attrs.id);let a=r.attrs.id?.includes("@")?r.attrs.id:Ft(r.attrs.id||"","g.us"),A=ie(r,"ephemeral")?.attrs.expiration,t=RA(r,"member_add_mode")==="all_member_add";return{id:a,subject:r.attrs.subject||"",subjectOwner:r.attrs.s_o,subjectTime:Number(r.attrs.s_t||0),size:mA(r,"participant").length,creation:Number(r.attrs.creation||0),owner:r.attrs.creator?oA(r.attrs.creator):void 0,desc:i,descId:e,linkedParent:ie(r,"linked_parent")?.attrs.jid||void 0,restrict:!!ie(r,"locked"),announce:!!ie(r,"announcement"),isCommunity:!!ie(r,"parent"),isCommunityAnnounce:!!ie(r,"default_sub_community"),joinApprovalMode:!!ie(r,"membership_approval_mode"),memberAddMode:t,participants:mA(r,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:RA(r,"addressing_mode")}};var uLe=n=>{let r={...E$,...n};return U$(r)},H$=uLe;var K$=H$;var BLe=Object.freeze({key:"whatsapp",label:"WhatsApp",connectionLabel:" Web \u5173\u8054\u8BBE\u5907"}),HS=class extends lo{constructor(r){super({...r,descriptor:BLe})}};import{chmod as Y$,mkdir as QLe,readdir as fLe}from"node:fs/promises";var yLe=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),mLe=6e4;function x$(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function SLe(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function DLe(n){let r=n;if(typeof r=="string"){if(!/^\d+$/.test(r))return null;r=Number(r)}else typeof r=="bigint"?r=Number(r):r&&typeof r=="object"&&(r=Number(r.valueOf()));return Number.isFinite(r)&&r>=0?r*1e3:null}async function pP(n){await QLe(n,{recursive:!0,mode:448}),await Y$(n,448);let r=await fLe(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(r.filter(o=>o.isFile()).map(o=>Y$(`${n}/${o.name}`,384).catch(()=>{})))}function wLe(n,r){let o=n.user??r.creds.me,i=oA(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):"WhatsApp\u673A\u5668\u4EBA"}}async function KS({authDir:n,onQr:r,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=K$,loadAuthState:t=U9}={}){if(!n||typeof r!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await pP(n);let s=Date.now(),{state:g,saveCreds:c}=await t(n),l=g.keys.set.bind(g.keys);g.keys.set=async j=>{await l(j),await pP(n)};let p=!1,B=!1,Q,f,y=Promise.resolve(),m=null,R=0,k=null,G=new Promise((j,F)=>{Q=j,f=F}),K=j=>{B||(B=!0,f(j))},x=async()=>{p||(p=!0,R+=1,K(x$()),await k?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},H=async()=>{p||(p=!0,R+=1,K(x$()),await k?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let j=++R,F=!1,T=A({auth:g,browser:tS.macOS("DeepSeek Harness"),logger:yLe,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=T;let V=()=>{!F||!g.creds.me||B||y.then(()=>{p||B||j!==R||!F||!g.creds.me||(B=!0,Q(wLe(T,g)))}).catch(U=>K(U))};T.ev.on("creds.update",()=>{p||j!==R||(y=y.then(async()=>{await c(),await pP(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),V())}),T.ev.on("connection.update",U=>{if(!(p||j!==R)&&(typeof U.qr=="string"&&U.qr&&r(U.qr),U.connection==="open"&&(F=!0,V()),U.connection==="close")){let b=SLe(U.lastDisconnect?.error);if(b===yt.restartRequired){k??=y.then(async()=>{p||j!==R||(await T.end(void 0).catch(()=>{}),!(p||j!==R)&&q())}).catch(pe=>K(pe)).finally(()=>{k=null});return}let L=b===yt.loggedOut,X=Object.assign(new Error(L?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:L?"logged-out":"connection-closed"});B?i?.({error:X,loggedOut:L}):K(X)}}),T.ev.on("messages.upsert",({messages:U,type:b})=>{if(!(p||j!==R||b!=="notify"&&b!=="append"||typeof o!="function"))for(let L of Array.isArray(U)?U:[]){if(b==="append"){let X=DLe(L?.messageTimestamp);if(X===null||X{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await x():e.addEventListener("abort",()=>void x(),{once:!0})),Object.freeze({get socket(){return m},ready:G,close:x,logout:H})}var j$=new Set(["image/jpeg","image/png","image/webp","image/gif"]),OLe=5*1024*1024,CP=15e3,MLe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],bLe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]);function _Le(n){let r=n;for(let o=0;o<5&&r&&typeof r=="object";o+=1){let i=MLe.find(e=>r[e]?.message);if(!i)return!1;if(bLe.has(i))return!0;r=r[i].message}return!1}function NLe(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 RLe(n){if(Number.isSafeInteger(n)&&n>=0)return n;let r;try{r=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(r)&&r>=0?r:void 0}async function kLe(n,r,{signal:o,maxBytes:i=OLe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(CP),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>r(n,"stream",{options:{signal:a}})),t=await new Promise((l,p)=>{let B=!1,Q=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",f),y(m),!0),f=()=>Q(p,a.reason);a.addEventListener("abort",f,{once:!0}),A.then(y=>{Q(l,y)||y?.destroy?.()},y=>Q(p,y)),a.aborted&&f()}).catch(l=>{throw o?.aborted?o.reason??l:e.aborted?new XA("image-download-failed",`WhatsApp image download timed out after ${CP} ms`,"\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"):l}),s=[],g=0,c=()=>t?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let l of t){a.throwIfAborted();let p=Buffer.from(l);if(g+=p.length,g>i)throw t.destroy?.(),new XA("image-too-large",`WhatsApp image exceeded ${i} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");s.push(p)}}catch(l){throw o?.aborted?o.reason??l:e.aborted?new XA("image-download-failed",`WhatsApp image stream timed out after ${CP} ms`,"\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"):l}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function vLe(n,r,o,{viewOnce:i=!1}={}){let e,a;if(!i&&r?.imageMessage&&r.imageMessage.viewOnce!==!0)e=r.imageMessage;else if(r?.documentMessage){let t=typeof r.documentMessage.mimetype=="string"?r.documentMessage.mimetype.toLowerCase():"";if(!j$.has(t))return null;e=r.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return j$.has(A)?{name:a,mediaType:A,size:RLe(e.fileLength),load:t=>kLe(n,o,t)}:null}function PLe(n,r,{download:o=YZ}={}){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"),t=n.key.fromMe===!0,s=t&&!A&&[i,e].some(y=>y&<(y,r));if(t&&!s)return null;let g=s?r:A?n.key.participant:i;if(typeof g!="string"||!g)return null;let c=_Le(n.message),l=Hr(n.message),p=NLe(l),B=Array.isArray(p?.mentionedJid)&&p.mentionedJid.some(y=>lt(y,r)),Q=typeof p?.participant=="string"&<(p.participant,r),f=vLe(n,l,o,{viewOnce:c});return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:TLe(l),images:f?[f]:[],addressed:!A||B||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s}}}var hP=class{#e=new Map;has(r){return this.#A(),this.#e.has(r)}remember(r){if(!(typeof r!="string"||!r))for(this.#A(),this.#e.set(r,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#A(){let r=Date.now();for(let[o,i]of this.#e)i>r||this.#e.delete(o)}},dP=class{#e;#A;#t=new Map;constructor(r,o){this.#e=r,this.#A=o}async sendText(r,o){await this.#r(r.jid);let i=null;for(let[e,a]of ii(o,4e3).entries())i=await this.#e.sendMessage(r.jid,{text:a},e===0&&r.quoted?{quoted:r.quoted}:void 0),this.#A.remember(i?.key?.id);return i}async sendTyping(r){!r.selfChat&&r.quoted?.key&&await this.#e.readMessages([r.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",r.jid),await this.#r(r.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",r.jid).catch(()=>{this.#r(r.jid)})},2e4);o.unref?.(),this.#t.set(r.jid,o)}async close(){let r=[...this.#t.keys()];await Promise.allSettled(r.map(o=>this.#r(o)))}async#r(r,o=!0){let i=this.#t.get(r);i&&clearInterval(i),this.#t.delete(r),o&&await this.#e.sendPresenceUpdate("paused",r).catch(()=>{})}};function GLe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var pd=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=GLe();#a=null;#i=null;#o=null;#c=null;#l=null;constructor({config:r,authDir:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=3e4,createSession:s=KS}){if(!r||!o||!i||!e||typeof s!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s}get status(){return structuredClone(this.#I)}async start(){return this.#I.ready&&this.#i?this.status:this.#l?this.#l:(this.#l=this.#p().finally(()=>{this.#l=null}),this.#l)}async#p(){await this.stop(),this.#I.startedAt=new Date().toISOString(),this.#I.connectionState="connecting",this.#I.lastError=null,await this.#t.ensureRunning(),this.#I.harnessReachable=!0;let r=new AbortController;this.#a=r;let o=new hP,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#s({authDir:this.#A,signal:r.signal,logger:this.#g,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async c=>{let l=PLe(c,this.#e.accountJid);!l||o.has(l.providerMessageId)||!this.#c||(this.#I.lastCheckedAt=Date.now(),await this.#c.accept(l))},onDisconnect:({error:c})=>{r.signal.aborted||(this.#I.ready=!1,this.#I.connectionState="failed",this.#I.lastError=c?.message??"WhatsApp Web connection closed")}});this.#i=a;let A,t=await Promise.race([a.ready,e,new Promise((c,l)=>{A=setTimeout(()=>l(new Error("WhatsApp Web did not connect in time")),this.#E)})]).finally(()=>clearTimeout(A));if(!lt(t.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new dP(a.socket,o);this.#o=s,this.#c=new HS({bot:s,harness:this.#t,state:this.#r,status:this.#I,logger:this.#g,replyTimeoutMs:this.#n,signal:r.signal});let g=Date.now();return this.#I.ready=!0,this.#I.connectionState="connected",this.#I.lastCheckedAt=g,this.#I.lastConnectedAt=g,this.status}catch(a){throw this.#I.ready=!1,this.#I.connectionState="failed",this.#I.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#i?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(r){if(!this.#I.ready||!this.#o){let o=new Error("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw o.code="test-target-unavailable",o}if(typeof r!="string"||!r.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#o.sendText({jid:this.#e.accountJid,selfChat:!0},r),{sent:!0}}async stop(){let r=this.#i,o=this.#o,i=this.#c;return this.#a?.abort(),this.#a=null,this.#i=null,this.#o=null,this.#c=null,await o?.close().catch(()=>{}),await r?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#I.ready=!1,this.#I.connectionState="idle",this.status}};var HLe=/^[a-f0-9-]{36}$/;function KLe(n,r){if(r!==void 0)return new URL(r);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-im WhatsApp requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function YLe(n){let r=Wn(n.dshHome??process.env.DSH_HOME??DE(ULe(),".dsh")),o=Wn(n.dataDir??DE(r,"integrations","dsh-whatsapp")),i=Wn(n.authDir??DE(o,"auth")),e=a=>{if(!HLe.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return Wn(i,a)};return{config:Wn(n.configPath??DE(o,"config.json")),bots:Wn(n.botsDir??DE(o,"bots")),workspaces:Wn(n.workspacesPath??DE(o,"workspaces.json")),authPath:e}}async function uP(n,r={},o={}){if(!n?.webServer)throw new TypeError("dsh-im WhatsApp requires ctx.webServer");let i=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,e=o.ConfigStore??rf,a=o.StateStore??of,A=o.HarnessClient??af,t=o.Controller??NC,s=o.Runtime??pd,g=o.createSession??KS,c=o.createConnectionSupervisor??eI,l=YLe(r),p=await new e(l.config).load(),B=Wn(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(F=>F.botId)),await Promise.all(y.map(F=>f.ensure(F.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=new Map,k=F=>Wn(l.bots,F,"state.json"),G=async F=>{let T=R.get(F);return T||(T=await new a(k(F)).load(),R.set(F,T)),T},K=zr(n,o.commandExecutor),x=new A({baseUrl:KLe(n.webServer,r.harnessBaseUrl),workspace:B,agentPreset:r.agentPreset??"standard",autostart:!1,dshBin:r.dshBin??"dsh",...K?{commandExecutor:K}:{}}),H=new t({configStore:m,authPath:l.authPath,createSession:g,logger:i,createRuntime:async({botId:F,config:T,authDir:V})=>{let U=await G(F);await f.ensure(F);let b=qr(x,{botId:F,workspaces:f,state:U});return new s({config:T,authDir:V,harness:b.harness,state:b.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??3e4,createSession:g,logger:{error:(...L)=>i.error?.(`[${F}]`,...L),warn:(...L)=>i.warn?.(`[${F}]`,...L),info:(...L)=>i.info?.(`[${F}]`,...L),debug:(...L)=>i.debug?.(`[${F}]`,...L)}})},deleteAuth:F=>FLe(l.authPath(F),{recursive:!0,force:!0}),deleteState:async({botId:F})=>{let T=R.get(F);if(R.delete(F),T&&typeof T.remove=="function")await T.remove();else try{await LLe(k(F))}catch(V){if(V?.code!=="ENOENT")throw V}}}),q=Vr(H,{workspaces:f,stateFor:G}),j=c({channel:"whatsapp",controller:q,harness:x,logger:i,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:q,ready:j.ready,async close(){await j.close(),await q.close(),x.stopManagedProcess()}}}import xLe from"qrcode";var J$="/whatsapp",pa=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),q$=Object.freeze(Object.values(pa)),jLe=new Set(["qrValue","accountJid","authDirectory"]);function fP(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function YS(n,r){return fP(n)&&Object.keys(n).every(o=>r.includes(o))}function BP(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function JLe(n,r){return fP(r)?[pa.status,pa.beginProvisioning].includes(n)?YS(r,[])?null:`${n} does not accept fields.`:[pa.pollProvisioning,pa.cancelProvisioning].includes(n)?YS(r,["attemptId"])&&BP(r.attemptId)?null:`${n} requires an attemptId.`:n===pa.reconnectBot?YS(r,["botId","sendTest"])&&BP(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.":n===pa.deleteBot?YS(r,["botId","confirm"])&&BP(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===pa.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown WhatsApp endpoint.":"Payload must be an object."}function wE(n){if(Array.isArray(n))return n.map(wE);if(!fP(n))return n;let r={};for(let[o,i]of Object.entries(n))jLe.has(o)||(r[o]=wE(i));return r}async function qLe(n){return xLe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function QP(n,r){return!n||typeof n.qrValue!="string"?wE(n):wE({...n,qrCodeDataUrl:await r(n.qrValue)})}async function xS(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await QP(o.provisioning,r)),wE(o)}function V$(n,{encodeQr:r=qLe}={}){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(()=>r(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(!q$.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let t=JLe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===pa.status)s=await xS(await n.status(),i);else if(e===pa.beginProvisioning)s=await QP(await n.startProvisioning(),i);else if(e===pa.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 QP(g,i)}else if(e===pa.cancelProvisioning)s=wE(await n.cancelProvisioning(a.attemptId));else if(e===pa.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 xS(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(p=>p?.botId===a.botId&&p.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let p=new Error("Connection test is unavailable");throw p.code="test-target-unavailable",p}await n.sendConnectionTest(a.botId)}catch(p){c=p}s={...s,testMessage:Ot(c)}}}else if(e===pa.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await xS(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await xS(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=Xr(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 jS(n,r,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(J$,V$(r,o),{authority:Wr(i)})}async function z$(n,r={}){if(r?.controller)return jS(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await uP(n,r,r.internals??{}),i=jS(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close WhatsApp Web connections"),i}var VLe="dsh-im-host",zLe=["connection","credentials","webServer","typertGateway"];function Zn(n,r){let o=n[r]??{};return n.rpcAuthority===void 0?o:{...o,rpcAuthority:n.rpcAuthority}}function WLe(n={}){let r=n.applyFeishu??J1,o=n.applyWeixin??oj,i=n.applyDingtalk??dG,e=n.applyWecom??K3,a=n.applyQq??r3,A=n.applySlack??d3,t=n.applyTelegram??w3,s=n.applyDiscord??bG,g=n.applyWhatsapp??z$;return Object.freeze({name:VLe,inject:zLe,async apply(c,l={}){await r(c,Zn(l,"feishu")),await o(c,Zn(l,"weixin")),await i(c,Zn(l,"dingtalk")),await e(c,Zn(l,"wecom")),await a(c,Zn(l,"qq")),await A(c,Zn(l,"slack")),await t(c,Zn(l,"telegram")),await s(c,Zn(l,"discord")),await g(c,Zn(l,"whatsapp"))}})}async function aEA(n,r={}){return WLe().apply(n,r)}export{aEA as apply,WLe as createImHostPlugin,zLe as inject,VLe as name}; +${n.stack}`:i}function ISe(n){n<1028||(Nn[n]=xC,xC=n)}function KC(n,r){return n=n>>>0,cl().subarray(n/1,n/1+r)}var nc=null;function Ke(){return(nc===null||nc.buffer.detached===!0||nc.buffer.detached===void 0&&nc.buffer!==$.memory.buffer)&&(nc=new DataView($.memory.buffer)),nc}function Wt(n,r){return n=n>>>0,pSe(n,r)}var YC=null;function cl(){return(YC===null||YC.byteLength===0)&&(YC=new Uint8Array($.memory.buffer)),YC}function we(n){return Nn[n]}function zt(n,r){try{return n.apply(this,r)}catch(o){$.__wbindgen_export3(Je(o))}}var Nn=new Array(1024).fill(void 0);Nn.push(void 0,null,!0,!1);var xC=Nn.length;function Xi(n){return n==null}function lSe(n,r,o,i){let e={a:n,b:r,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let t=e.a;e.a=0;try{return i(t,e.b,...A)}finally{e.a=t,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,Bq.unregister(e))},Bq.register(a,e,e),a}function st(n,r){let o=r(n.length*1,1)>>>0;return cl().set(n,o/1),_A=n.length,o}function Qq(n,r){let o=r(n.length*4,4)>>>0,i=Ke();for(let e=0;e>>0;return cl().subarray(s,s+t.length).set(t),_A=t.length,s}let i=n.length,e=r(i,1)>>>0,a=cl(),A=0;for(;A127)break;a[e+A]=t}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let t=cl().subarray(e+A,e+i),s=jC.encodeInto(n,t);A+=s.written,e=o(e,i,A,1)>>>0}return _A=A,e}function EA(n){let r=we(n);return ISe(n),r}var _f=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});_f.decode();var ESe=2146435072,sT=0;function pSe(n,r){return sT+=r,sT>=ESe&&(_f=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),_f.decode(),sT=r),_f.decode(cl().subarray(n,n+r))}var jC=new TextEncoder;"encodeInto"in jC||(jC.encodeInto=function(n,r){let o=jC.encode(n);return r.set(o),{read:n.length,written:o.length}});var _A=0,CSe,$;function hSe(n,r){return $=n.exports,CSe=r,nc=null,YC=null,$}function yq(n){if($!==void 0)return $;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let r=sSe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,r);return hSe(o,n)}var dSe=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 mq(n){let r=atob(n),o=new Uint8Array(r.length);for(let i=0;in.length===33?n:Buffer.concat([Tn,n]),Ut={generateKeyPair:()=>{let{pubKey:n,privKey:r}=Fs.generateKeyPair();return{private:Buffer.from(r),public:Buffer.from(n.slice(1))}},sharedKey:(n,r)=>{let o=Fs.calculateAgreement(di(r),n);return Buffer.from(o)},sign:(n,r)=>Fs.calculateSignature(n,r),verify:(n,r,o)=>{try{return Fs.verifySignature(di(n),r,o),!0}catch{return!1}}},Ff=(n,r)=>{let o=Ut.generateKeyPair(),i=di(o.public),e=Ut.sign(n.private,i);return{keyPair:o,signature:e,keyId:r}},Dq=16;function sc(n,r,o,i){let e=cT("aes-256-gcm",r,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function gc(n,r,o,i){let e=IT("aes-256-gcm",r,o),a=n.slice(0,n.length-Dq),A=n.slice(n.length-Dq);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function wq(n,r,o){let i=cT("aes-256-ctr",r,o);return Buffer.concat([i.update(n),i.final()])}function Oq(n,r,o){let i=IT("aes-256-ctr",r,o);return Buffer.concat([i.update(n),i.final()])}function Mq(n,r){return DSe(n.subarray(16),r,n.subarray(0,16))}function DSe(n,r,o){let i=IT("aes-256-cbc",r,o);return Buffer.concat([i.update(n),i.final()])}function bq(n,r){let o=SSe(16),i=cT("aes-256-cbc",r,o);return Buffer.concat([o,i.update(n),i.final()])}function Ao(n,r,o="sha256"){return mSe(o,r).update(n).digest()}function pl(n){return ySe("sha256").update(n).digest()}async function Lf(n,r){let i=new TextEncoder().encode(n),e=new Uint8Array(r instanceof Uint8Array?r:new Uint8Array(r)),a=await Sq.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await Sq.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var WC={replacer:(n,r)=>Buffer.isBuffer(r)||r instanceof Uint8Array||r?.type==="Buffer"?{type:"Buffer",data:Buffer.from(r?.data||r).toString("base64")}:r,reviver:(n,r)=>{if(typeof r=="object"&&r!==null&&r.type==="Buffer"&&typeof r.data=="string")return Buffer.from(r.data,"base64");if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=Object.keys(r);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(r);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return r}},Cl=(n,r="me")=>(n?.fromMe?r:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",Tq=n=>n==null||n==="",OSe=n=>{let o=(zC(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},Rq=n=>{let r=new Uint8Array(n);if(r.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=r[r.length-1];if(o>r.length)throw new Error(`unpad given ${r.length} bytes, but pad is ${o}`);return new Uint8Array(r.buffer,r.byteOffset,r.length-o)},kq=n=>(n.sort(),"2:"+pl(Buffer.from(n.join(""))).toString("base64").slice(0,6)),hl=n=>OSe(Ae.Message.encode(n).finish()),vq=()=>Uint16Array.from(zC(2))[0]&16383,Rn=(n,r=4)=>{let o=n,i=new Uint8Array(r);for(let e=r-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},or=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,Pr=(n=new Date)=>Math.floor(n.getTime()/1e3);var ZC=n=>Pq(n).delay,Pq=n=>{let r=new Error().stack,o,i;return{delay:new Promise((A,t)=>{o=setTimeout(A,n),i=t}),cancel:()=>{clearTimeout(o),i(new Uf.Boom("Cancelled",{statusCode:500,data:{stack:r}}))}}};async function dl(n,r){if(!n)return new Promise(r);let o=new Error().stack,{delay:i,cancel:e}=Pq(n);return new Promise((A,t)=>{i.then(()=>t(new Uf.Boom("Timed Out",{statusCode:yt.timedOut,data:{stack:o}}))).catch(s=>t(s)),r(A,t)}).finally(e)}var nr=n=>{let r=Buffer.alloc(44);if(r.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=lA(n);e?.user&&(r.write(e.user,8),r.write("@c.us",8+e.user.length))}return zC(16).copy(r,28),"3EB0"+wSe("sha256").update(r).digest().toString("hex").toUpperCase().substring(0,18)},lT=()=>"3EB0"+zC(18).toString("hex").toUpperCase();function ET(n,r){return async(o,i)=>{let e,a;await dl(i,(A,t)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&t(g?.error||new Uf.Boom("Connection Closed",{statusCode:yt.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(r,e)}).finally(()=>{n.off(r,e),n.off("connection.update",a)})}}var Gq=n=>ET(n,"connection.update");var Fq=()=>{let n=zC(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},MSe={sender:Ae.WebMessageInfo.Status.SERVER_ACK,played:Ae.WebMessageInfo.Status.PLAYED,read:Ae.WebMessageInfo.Status.READ,"read-self":Ae.WebMessageInfo.Status.READ},Lq=n=>{let r=MSe[n];return typeof n>"u"?Ae.WebMessageInfo.Status.DELIVERY_ACK:r},bSe={conflict:yt.connectionReplaced},Uq=n=>{let[r]=bo(n),o=r?.tag||"unknown",i=+(n.attrs.code||bSe[o]||yt.badSession);return i===yt.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},Hq=({tag:n,attrs:r})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":r.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},_q="Unexpected server response: ",Kq=n=>{let r=500;if(n?.message?.includes(_q)){let o=+n?.message.slice(_q.length);!Number.isNaN(o)&&o>=400&&(r=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(r=408);return r};function Hf(n){for(let r in n)typeof n[r]>"u"&&delete n[r];return n}var Nq="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function Yq(n){let r=0,o=0,i=[];for(let e of n)for(r=r<<8|e&255,o+=8;o>=5;)i.push(Nq.charAt(r>>>o-5&31)),o-=5;return o>0&&i.push(Nq.charAt(r<<5-o&31)),i.join("")}function xq(n){return Ae.Message.encode(n).finish()}var cc=Le(ar(),1);var _Se=async(n,r)=>vA(n)||yr(n)?n:await r.lidMapping.getLIDForPN(n)||n,NSe=async(n,r,o,i,e)=>{let{senderAlt:a}=Yf(n);if(a&&vA(a)&&nt(r)&&i===r)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:r}]),await o.migrateSession(r,a),e.debug({sender:r,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:r,senderAlt:a,error:A},"Failed to store LID mapping")}},Kf="Message absent from node",jq="Key used already or never filled",Jq="Your account has been restricted",TSe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},Ic={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},pT={MessageAccountRestriction:"463",SmaxInvalid:"479"},Yf=n=>{let r,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(r=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(r=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:r,recipientAlt:o}};function CT(n,r,o){let i,e,a,A=!1,t=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!t)throw new cc.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new cc.Boom("Invalid message stanza: missing from attribute",{data:n});let l=Yf(n),p=m=>lt(m,r),B=m=>lt(m,o);if(nt(s)||vA(s)||yr(s)||Lt(s)){if(c&&!gl(c)){if(!p(s)&&!B(s))throw new cc.Boom("receipient present, but msg not from me",{data:n});(p(s)||B(s))&&(A=!0),e=c}else(p(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(ir(s)){if(!g)throw new cc.Boom("No participant in group message");(p(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(HC(s)){if(!g)throw new cc.Boom("No participant in group message");let m=p(g);_n(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(ks(s))i="newsletter",e=s,a=s,(p(s)||B(s))&&(A=!0);else throw new cc.Boom("Unknown message type",{data:n});let Q=n?.attrs?.notify,f={remoteJid:e,remoteJidAlt:ir(e)?void 0:l.senderAlt,remoteJidUsername:ir(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:t,participant:g,participantAlt:ir(e)?l.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:l.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:f,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:Q,broadcast:HC(s)};return f.fromMe&&(y.status=Ae.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var qq=(n,r,o,i,e)=>{let{fullMessage:a,author:A,sender:t}=CT(n,r,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:l}of n.content){if(g==="verified_name"&&l instanceof Uint8Array){let Q=Ae.VerifiedNameCertificate.decode(l),f=Ae.VerifiedNameCertificate.Details.decode(Q.details);a.verifiedBizName=f.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"||!(l instanceof Uint8Array))continue;s+=1;let p,B=await _Se(A,i);g!=="plaintext"&&await NSe(n,A,i,B,e);try{let Q=g==="plaintext"?"plaintext":c.type;switch(Q){case"skmsg":p=await i.decryptGroupMessage({group:t,authorJid:A,msg:l});break;case"pkmsg":case"msg":p=await i.decryptMessage({jid:B,type:Q,ciphertext:l});break;case"plaintext":p=l;break;default:throw new Error(`Unknown e2e type: ${Q}`)}let f=Ae.Message.decode(Q!=="plaintext"?Rq(p):p);if(f=f.deviceSentMessage?.message||f,f.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:f.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,f):a.message=f}catch(Q){let f={key:a.key,err:Q,messageType:g==="plaintext"?"plaintext":c.type,sender:t,author:A,isSessionRecordError:RSe(Q)};e.error(f,"failed to decrypt message"),a.messageStubType=Ae.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[Q.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=Ae.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[Kf])}}};function RSe(n){let r=n?.message||n?.toString()||"";return TSe.sessionRecordErrors.some(o=>r.includes(o))}var Yn=Le(ar(),1);import{randomBytes as bk}from"crypto";import{promises as _k}from"fs";var ro=Le(ar(),1);import{exec as RTe}from"child_process";import*as qa from"crypto";import{once as aE}from"events";import{createReadStream as Lm,createWriteStream as fk,promises as oE}from"fs";import{tmpdir as QZ}from"os";import{join as Gm}from"path";import{Readable as Kh,Transform as kTe}from"stream";import{URL as yk}from"url";var mk=()=>QZ(),fZ=async()=>{let[n,r]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(iz(),az)).catch(()=>{})]);if(r)return{sharp:r};if(n)return{jimp:n};throw new ro.Boom("No image processing library available")},vTe=n=>`WhatsApp ${RZ[n]} Keys`,Um=async(n,r,o)=>{let{stream:i}=await Yh(n);o?.debug("got stream for raw upload");let e=qa.createHash("sha256"),a=Gm(QZ(),r+nr()),A=fk(a),t=0;try{for await(let g of i)t+=g.length,e.update(g),A.write(g)||await aE(A,"drain");A.end(),await aE(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:t}}catch(s){A.destroy(),i.destroy();try{await oE.unlink(a)}catch{}throw s}};async function yZ(n,r){if(!n)throw new ro.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=eo(n,112,{info:vTe(r)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var PTe=async(n,r,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${r}`;RTe(A,t=>{t?a(t):e()})}),Sk=async(n,r=32)=>{n instanceof Kh&&(n=await Fm(n));let o=await fZ();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(r).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:r,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new ro.Boom("No image processing library available")},GTe=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),Hm=async(n,r)=>{let o,{width:i=640,height:e=640}=r||{};if(Buffer.isBuffer(n))o=n;else{let{stream:t}=await Yh(n);o=await Fm(t)}let a=await fZ(),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 t=await a.jimp.Jimp.read(o),s=Math.min(t.width,t.height);A=t.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 ro.Boom("No image processing library available");return{img:await A}};async function mZ(n){let r=await Promise.resolve().then(()=>(uZ(),dZ)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await r.parseBuffer(n,void 0,i):typeof n=="string"?o=await r.parseFile(n,i):o=await r.parseStream(n,void 0,i),o.format.duration}async function SZ(n,r){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let p=Lm(n);i=await Fm(p)}else i=await Fm(n);let a=(await o(i)).getChannelData(0),A=64,t=Math.floor(a.length/A),s=[];for(let p=0;pp*g);return new Uint8Array(c.map(p=>Math.floor(100*p)))}catch(o){r?.debug("Failed to generate waveform: "+o)}}var BZ=n=>{let r=new Kh({read:()=>{}});return r.push(n),r.push(null),r},Fm=async n=>{let r=[];for await(let o of n)r.push(o);return n.destroy(),Buffer.concat(r)},Yh=async(n,r)=>{if(Buffer.isBuffer(n))return{stream:BZ(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:BZ(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await Km(n.url,r),type:"remote"}:{stream:Lm(n.url),type:"file"}};async function DZ(n,r,o){let i,e;if(r==="image"){let{buffer:a,original:A}=await Sk(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(r==="video"){let a=Gm(mk(),nr()+".jpg");try{await PTe(n,a,"00:00:00",{width:32,height:32}),i=(await oE.readFile(a)).toString("base64"),await oE.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var Km=async(n,r={})=>{let o=await fetch(n.toString(),{dispatcher:r.dispatcher,method:"GET",headers:r.headers});if(!o.ok)throw new ro.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof Kh?o.body:Kh.fromWeb(o.body)},wZ=async(n,r,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await Yh(n,e);o?.debug("fetched media stream");let t=qa.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await yZ(t,r),l=Gm(mk(),r+nr()+"-enc"),p=fk(l),B,Q;i&&(Q=Gm(mk(),r+nr()+"-original"),B=fk(Q));let f=0,y=qa.createCipheriv("aes-256-cbc",s,g),m=qa.createHmac("sha256",c).update(g),R=qa.createHash("sha256"),k=qa.createHash("sha256"),G=async K=>{k.update(K),m.update(K),p.write(K)||await aE(p,"drain")};try{for await(let F of a){if(f+=F.length,A==="remote"&&e?.maxContentLength&&f+F.length>e.maxContentLength)throw new ro.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(F)||await aE(B,"drain")),R.update(F),await G(y.update(F))}await G(y.final());let K=m.digest().slice(0,10);k.update(K);let x=R.digest(),H=k.digest();p.write(K);let q=aE(p,"finish"),j=B?aE(B,"finish"):Promise.resolve();return p.end(),B?.end?.(),a.destroy(),await q,await j,o?.debug("encrypted data successfully"),{mediaKey:t,originalFilePath:Q,encFilePath:l,mac:K,fileEncSha256:H,fileSha256:x,fileLength:f}}catch(K){p.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),R.destroy(),k.destroy(),a.destroy();try{await oE.unlink(l),Q&&await oE.unlink(Q)}catch(x){o?.error({err:x},"failed deleting tmp files")}throw K}},Dk="mmg.whatsapp.net",iE=16,Qk=n=>Math.floor(n/iE)*iE,xh=(n,r=Dk)=>`https://${r}${n}`,FTe=n=>{if(n)try{return new yk(n).host}catch{return}},nE=async({mediaKey:n,directPath:r,url:o},i,e={})=>{let a=e.host??FTe(o),A=r?xh(r,a):o;if(!A)throw new ro.Boom("No valid media URL or directPath present in message",{statusCode:400});let t=await yZ(n,i);return LTe(A,t,e)},LTe=async(n,{cipherKey:r,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,t=0,s=!1;if(i){let m=Qk(i||0);m&&(t=m-iE,A=m,s=!0)}let g=e?Qk(e||0)+iE:void 0,c=a?.headers?a.headers:void 0,l={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:jh};(t||g)&&(l.Range=`bytes=${t}-`,g&&(l.Range+=g));let p=await Km(n,{...a||{},headers:l}),B=Buffer.from([]),Q,f=(m,R)=>{if(i||e){let k=A>=i?void 0:Math.max(i-A,0),G=A+m.lengththis.push(x)),k()}catch(x){k(x)}},final(m){try{f(Q.final(),R=>this.push(R)),m()}catch(R){m(R)}}});return p.pipe(y,{end:!0})};var UTe=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",OZ=async({url:n,filePath:r,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new yk(n),t=A.protocol==="https:"?await import("https"):await import("http"),g=(await oE.stat(r)).size;return new Promise((c,l)=>{let p=t.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},Q=>{if(Q.statusCode&&Q.statusCode>=300&&Q.statusCode<400&&Q.headers.location){Q.resume();let y=new yk(Q.headers.location,n).toString();c(OZ({url:y,filePath:r,headers:o,timeoutMs:i,agent:e},a+1));return}let f="";Q.on("data",y=>f+=y),Q.on("end",()=>{try{c(JSON.parse(f))}catch{c(void 0)}})});p.on("error",l),p.on("timeout",()=>{p.destroy(),l(new Error("Upload timeout"))});let B=Lm(r);B.pipe(p),B.on("error",Q=>{p.destroy(),l(Q)})})},HTe=async({url:n,filePath:r,headers:o,timeoutMs:i,agent:e})=>{let a=Lm(r),A=Kh.toWeb(a),t=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...t?{dispatcher:t}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},KTe=async(n,r)=>UTe()?(r?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),OZ(n)):(r?.debug("Using web-standard Fetch API for upload"),HTe(n)),MZ=({customUploadHosts:n,fetchAgent:r,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:t,timeoutMs:s})=>{let g=await e(!1),c,l=[...n,...g.hosts];t=GTe(t);let B={...(()=>{let Q=i?.headers;return Q?Array.isArray(Q)?Object.fromEntries(Q):Q:{}})(),"Content-Type":"application/octet-stream",Origin:jh};for(let{hostname:Q}of l){o.debug(`uploading to "${Q}"`);let f=encodeURIComponent(g.auth),y=`https://${Q}${Ok[A]}/${t}?auth=${f}&token=${t}`,m;try{if(m=await KTe({url:y,filePath:a,headers:B,timeoutMs:s,agent:r},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(R){let k=Q===l[g.hosts.length-1]?.hostname;o.warn({trace:R?.stack,uploadResult:m},`Error in uploading to ${Q} ${k?"":", retrying..."}`)}}if(!c)throw new ro.Boom("Media upload failed on all hosts",{statusCode:500});return c},bZ=n=>eo(n,32,{info:"WhatsApp Media Retry Notification"}),_Z=(n,r,o)=>{let i={stanzaId:n.id},e=Ae.ServerErrorReceipt.encode(i).finish(),a=qa.randomBytes(12),A=bZ(r),t=sc(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:oA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:t},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},NZ=n=>{let r=ie(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:r.attrs.jid,fromMe:r.attrs.from_me==="true",participant:r.attrs.participant}},i=ie(n,"error");if(i){let e=+i.attrs.code;o.error=new ro.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:wk(e)})}else{let e=ie(n,"encrypt"),a=vr(e,"enc_p"),A=vr(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new ro.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},TZ=({ciphertext:n,iv:r},o,i)=>{let e=bZ(o),a=gc(n,e,r,Buffer.from(i));return Ae.MediaRetryNotification.decode(a)},wk=n=>YTe[n],YTe={[Ae.MediaRetryNotification.ResultType.SUCCESS]:200,[Ae.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[Ae.MediaRetryNotification.ResultType.NOT_FOUND]:404,[Ae.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as xTe}from"crypto";var jTe=[{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}]}],vZ=n=>{let r=new Map;for(let o of n)r.set(o.f,{m:o.m,children:o.s?vZ(o.s):void 0});return r},JTe=vZ(jTe),qTe=new Map,VTe="Report Token",Ym={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},xm=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,zTe=(n,r,o,i,e)=>{let a=Buffer.concat([Buffer.from(r,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return eo(e,32,{info:a.toString("latin1")})},PZ=(n,r)=>{let o=[],i=0;for(;i>3,A=e.value&7,t=i;i+=e.bytes;let s=r.get(a),g=l=>l>n.length?!1:(o.push({num:a,bytes:n.subarray(t,l)}),i=l,!0),c=l=>l>n.length?!1:(i=l,!0);if(A===Ym.VARINT){let l=Mk(n,i);if(!l.ok)return null;let p=i+l.bytes;if(!s){if(!c(p))return null;continue}if(!g(p))return null;continue}if(A===Ym.FIXED64){let l=i+8;if(!s){if(!c(l))return null;continue}if(!g(l))return null;continue}if(A===Ym.FIXED32){let l=i+4;if(!s){if(!c(l))return null;continue}if(!g(l))return null;continue}if(A===Ym.BYTES){let l=Mk(n,i);if(!l.ok)return null;let p=i+l.bytes,B=p+l.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let Q=PZ(n.subarray(p,B),s.children??qTe);if(Q===null)return null;if(Q.length>0){let f=kZ(e.value),y=kZ(Q.length);o.push({num:a,bytes:Buffer.concat([f,y,Q])})}i=B;continue}o.push({num:a,bytes:n.subarray(t,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)))},Mk=(n,r)=>{let o=0,i=0,e=0;for(;r+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},kZ=n=>{let r=[],o=n>>>0;for(;o>127;)r.push(o&127|128),o>>>=7;return r.push(o),Buffer.from(r)},GZ=async(n,r,o)=>{let i=r.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=zTe(VTe,o.id,e,a,i),t=PZ(n,JTe);if(!t||t.length===0)return null;let s=xTe("sha256",A).update(t).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var WTe={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},FZ={image:Ae.Message.ImageMessage,video:Ae.Message.VideoMessage,audio:Ae.Message.AudioMessage,sticker:Ae.Message.StickerMessage,document:Ae.Message.DocumentMessage},ZTe=n=>n.match(qZ)?.[0],XTe=async(n,r,o)=>{let i=ZTe(n);if(r&&i)try{return await r(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},LZ=async n=>{let r;if(typeof n=="number")r=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),r=parseInt(o,16),r}},Jh=async(n,r)=>{let o=r.logger,i;for(let x of VZ)x in n&&(i=x);if(!i)throw new Yn.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&&!!r.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=WTe[i]),a){let x=await r.mediaCache.get(a);if(x){o?.debug({cacheableKey:a},"got media cache hit");let H=Ae.Message.decode(x),q=`${i}Message`;return Object.assign(H[q],{...e,media:void 0}),H}}if(!!r.jid&&ks(r.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:x,fileSha256:H,fileLength:q}=await Um(e.media,r.mediaTypeOverride||i,o),j=H.toString("base64"),{mediaUrl:F,directPath:T}=await r.upload(x,{fileEncSha256B64:j,mediaType:i,timeoutMs:r.mediaUploadTimeoutMs});await _k.unlink(x);let V=Ae.Message.fromObject({[`${i}Message`]:FZ[i].fromObject({url:F,directPath:T,fileSha256:H,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 r.mediaCache.set(a,Ae.Message.encode(V).finish())),V}let t=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=r.backgroundColor&&i==="audio"&&e.ptt===!0,l=t||s,{mediaKey:p,encFilePath:B,originalFilePath:Q,fileEncSha256:f,fileSha256:y,fileLength:m}=await wZ(e.media,r.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:l,opts:r.options}),R=f.toString("base64"),[{mediaUrl:k,directPath:G}]=await Promise.all([(async()=>{let x=await r.upload(B,{fileEncSha256B64:R,mediaType:i,timeoutMs:r.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),x})(),(async()=>{try{if(s){let{thumbnail:x,originalImageDimensions:H}=await DZ(Q,i,r);e.jpegThumbnail=x,!e.width&&H&&(e.width=H.width,e.height=H.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}t&&(e.seconds=await mZ(Q),o?.debug("computed audio duration")),g&&(e.waveform=await SZ(Q,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await LZ(r.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(x){o?.warn({trace:x.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await _k.unlink(B),Q&&await _k.unlink(Q),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),K=Ae.Message.fromObject({[`${i}Message`]:FZ[i].fromObject({url:k,directPath:G,mediaKey:p,fileEncSha256:f,fileSha256:y,fileLength:m,mediaKeyTimestamp:Pr(),...e,media:void 0})});return e.ptv&&(K.ptvMessage=K.videoMessage,delete K.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await r.mediaCache.set(a,Ae.Message.encode(K).finish())),K},$Te=n=>{n=n||0;let r={ephemeralMessage:{message:{protocolMessage:{type:Ae.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return Ae.Message.fromObject(r)},eRe=(n,r)=>{let o=n.message;if(!o)throw new Yn.Boom("no content in message",{statusCode:400});o=Hr(o),o=Ae.Message.decode(Ae.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!r?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},Or=(n,r)=>typeof n=="object"&&n!==null&&r in n&&n[r]!==null&&n[r]!==void 0;function Tc(n,r){return typeof n=="object"&&n!==null&&r in n&&n[r]!==null}var ARe=async(n,r)=>{var o,i;let e={};if(Or(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await XTe(n.text,r.getUrlInfo,r.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let t=A.highQualityThumbnail;t&&(a.thumbnailDirectPath=t.directPath,a.mediaKey=t.mediaKey,a.mediaKeyTimestamp=t.mediaKeyTimestamp,a.thumbnailWidth=t.width,a.thumbnailHeight=t.height,a.thumbnailSha256=t.fileSha256,a.thumbnailEncSha256=t.fileEncSha256)}r.backgroundColor&&(a.backgroundArgb=await LZ(r.backgroundColor)),r.font&&(a.font=r.font),e.extendedTextMessage=a}else if(Or(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new Yn.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=Ae.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=Ae.Message.ContactsArrayMessage.create(n.contacts)}else if(Or(n,"location"))e.locationMessage=Ae.Message.LocationMessage.create(n.location);else if(Or(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=Ae.Message.ReactionMessage.create(n.react);else if(Or(n,"delete"))e.protocolMessage={key:n.delete,type:Ae.Message.ProtocolMessage.Type.REVOKE};else if(Or(n,"forward"))e=eRe(n.forward,n.force);else if(Or(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?Vh:0:n.disappearingMessagesInChat;e=$Te(a)}else if(Or(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,r.getProfilePicUrl){let a=await r.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:r?.options?.dispatcher});if(A.ok){let t=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=t}}}}else if(Or(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(Or(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:Ae.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(Tc(n,"ptv")&&n.ptv){let{videoMessage:a}=await Jh({video:n.video},r);e.ptvMessage=a}else if(Or(n,"product")){let{imageMessage:a}=await Jh({image:n.product.productImage},r);e.productMessage=Ae.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(Or(n,"listReply"))e.listResponseMessage={...n.listReply};else if(Or(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&r.getCallLink){let A=await r.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?JZ:jZ)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||bk(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(Or(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new Yn.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new Yn.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||bk(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 Or(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:Or(n,"sharePhoneNumber")?e.protocolMessage={type:Ae.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:Or(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:Or(n,"limitSharing")?e.protocolMessage={type:Ae.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await Jh(n,r);if(Tc(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),Tc(n,"mentions")&&n.mentions?.length||Tc(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(Tc(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:Ae.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),Tc(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 Tc(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:Ae.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),xm(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=bk(32))),Ae.Message.create(e)},tRe=(n,r,o)=>{o.timestamp||(o.timestamp=new Date);let i=Hr(r),e=qh(i),a=Pr(o.timestamp),{quoted:A,userJid:t}=o;if(A&&!ks(n)){let g=A.key.fromMe?t:A.participant||A.key.participant||A.key.remoteJid,c=Hr(A.message),l=qh(c);c=Ae.Message.create({[l]:c[l]});let p=c[l];typeof p=="object"&&p&&"contextInfo"in p&&delete p.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=oA(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"&&!ks(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||Vh}),r=Ae.Message.create(r);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||nr()},message:r,messageTimestamp:a,messageStubParameters:[],participant:ir(n)||_n(n)?t:void 0,status:sl.PENDING};return Ae.WebMessageInfo.fromObject(s)},UZ=async(n,r,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),tRe(n,await ARe(r,{...o,jid:n}),o)),qh=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},Hr=n=>{if(!n)return;for(let o=0;o<5;o++){let i=r(n);if(!i)break;n=i.message}return n;function r(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},HZ=n=>{let r=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=Hr(n),n?.buttonsMessage?r(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?r(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?r(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?r(n?.templateMessage?.fourRowTemplate):n};var Nk=(n,r)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===r.userJid);o?Object.assign(o,r):n.userReceipt.push(r)},Tk=(n,r)=>{let o=Cl(r.key),i=(n.reactions||[]).filter(e=>Cl(e.key)!==o);r.text=r.text||"",i.push(r),n.reactions=i};var KZ=n=>{let r={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;r[A]||(r[A]={jid:o,participant:e,messageIds:[]}),r[A].messageIds.push(i)}return Object.values(r)},rRe=[410,404],YZ=async(n,r,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&rRe.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=HZ(n.message);if(!A)throw new Yn.Boom("No message present",{statusCode:400,data:n});let t=qh(A),s=t?.replace("Message",""),g=A[t];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new Yn.Boom(`"${t}" 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 l=await nE(c,s,o);if(r==="buffer"){let p=[];for await(let B of l)p.push(B);return Buffer.concat(p)}return l}},xZ=n=>{n=HZ(n);let r=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!r)throw new Yn.Boom("given message is not a media message",{statusCode:400,data:n});return r};var jm=Le(ar(),1);import{createHash as nRe}from"crypto";function aRe(n,r){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:di(r)}),iRe=async({get:n},r,o)=>{let i=[];for(let e=r;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=r-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=Ut.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,r]}},zh=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:Rn(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),kk=(n,r)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:Rn(r,3)},{tag:"value",attrs:{},content:n.public}]}),Rk=n=>typeof n=="number"&&Number.isInteger(n),WZ=n=>{let r=ie(n,"keys");if(!r)return null;let o=vr(r,"type");if(!o||o.length!==1||o[0]!==Tn[0])return null;let i=vr(r,"identity"),e=ie(r,"skey");if(!i||i.length!==32||!e)return null;let a=vs(n,"registration",4);if(!Rk(a))return null;let A=vr(e,"value"),t=vr(e,"signature"),s=vs(e,"id",3);if(!A||A.length!==32||!t||!Rk(s))return null;let g=ie(r,"key"),c;if(g){let l=vr(g,"value"),p=vs(g,"id",3);if(!l||l.length!==32||!Rk(p))return null;c={keyId:p,publicKey:di(l)}}return{registrationId:a,identityKey:di(i),signedPreKey:{keyId:s,publicKey:di(A),signature:t},preKey:c}},ZZ=async(n,r)=>{let o=A=>A?{keyId:vs(A,"id",3),publicKey:di(vr(A,"value")),signature:vr(A,"signature")}:void 0,i=mA(ie(n,"list"),"user");for(let A of i)Oa(A);let a=aRe(i,100);for(let A of a)for(let t of A){let s=ie(t,"skey"),g=ie(t,"key"),c=vr(t,"identity"),l=t.attrs.jid,p=vs(t,"registration",4);await r.injectE2ESession({jid:l,session:{registrationId:p,identityKey:di(c),signedPreKey:o(s),preKey:o(g)}})}},XZ=(n,r,o,i)=>{let{user:e,device:a}=lA(r),A=[];for(let t of n){let{devices:s,id:g}=t,c=lA(g),{user:l,server:p}=c,{domainType:B}=c,Q=s?.deviceList;if(Array.isArray(Q))for(let{id:f,keyIndex:y,isHosted:m}of Q)(!i||f!==0)&&(e!==l&&o!==l||a!==f)&&(f===0||y)&&(m&&(B=B===ut.LID?ut.HOSTED_LID:ut.HOSTED),A.push({user:l,device:f,domainType:B,server:$J(p,B)}))}return A},vk=async({creds:n,keys:r},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=oRe(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await r.set({"pre-key":i});let t=await iRe(r,a[0],a[0]+a[1]);return{update:A,preKeys:t}},$Z=async(n,r)=>{let{creds:o}=n,{update:i,preKeys:e}=await vk(n,r),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:uA},content:[{tag:"registration",attrs:{},content:Rn(o.registrationId)},{tag:"type",attrs:{},content:Tn},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>kk(e[+A],+A))},zh(o.signedPreKey)]};return{update:i,node:a}};var sRe=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?Ae.ClientPayload.UserAgent.Platform.ANDROID:Ae.ClientPayload.UserAgent.Platform.WEB,releaseChannel:Ae.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),e9={"Mac OS":Ae.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:Ae.ClientPayload.WebInfo.WebSubPlatform.WIN32},gRe=n=>{let r=Ae.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&e9[n.browser[0]]&&n.browser[1]==="Desktop"&&(r=e9[n.browser[0]]),{webSubPlatform:r}},A9=n=>{let r={connectType:Ae.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:Ae.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:sRe(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(r.webInfo=gRe(n)),n.pushName&&(r.pushName=n.pushName),r},t9=(n,r)=>{let{user:o,device:i}=lA(n),e={...A9(r),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return Ae.ClientPayload.fromObject(e)},cRe=n=>{let r=n.toUpperCase();return r==="ANDROID"?Ae.DeviceProps.PlatformType.ANDROID_PHONE:Ae.DeviceProps.PlatformType[r]||Ae.DeviceProps.PlatformType.CHROME},r9=({registrationId:n,signedPreKey:r,signedIdentityKey:o},i)=>{let e=nRe("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:cRe(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=Ae.DeviceProps.encode(a).finish(),t={...A9(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:Rn(n),eKeytype:Tn,eIdent:o.public,eSkeyId:Rn(r.keyId,3),eSkeyVal:r.keyPair.public,eSkeySig:r.signature}};return Ae.ClientPayload.fromObject(t)},a9=(n,{advSecretKey:r,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=ie(n,"pair-success"),A=ie(a,"device-identity"),t=ie(a,"platform"),s=ie(a,"device"),g=ie(a,"biz");if(!A||!s)throw new jm.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,l=s.attrs.jid,p=s.attrs.lid,{details:B,hmac:Q,accountType:f}=Ae.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);f!==void 0&&f===Ae.ADVEncryptionType.HOSTED&&(y=Pk);let m=Ao(Buffer.concat([y,B]),Buffer.from(r,"base64"));if(Buffer.compare(Q,m)!==0)throw new jm.Boom("Invalid account signature");let R=Ae.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:k,accountSignature:G,details:K}=R,x=Ae.ADVDeviceIdentity.decode(K),H=x.deviceType===Ae.ADVEncryptionType.HOSTED?Pk:i9,q=Buffer.concat([H,K,o.public]);if(!Ut.verify(k,q,G))throw new jm.Boom("Failed to verify account signature");let j=Buffer.concat([o9,K,o.public,k]);R.deviceSignature=Ut.sign(o.private,j);let F=zZ(p,k),T=Wh(R,!1),V={tag:"iq",attrs:{to:uA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":x.keyIndex.toString()},content:T}]}]};return{creds:{account:R,me:{id:l,name:c,lid:p},signalIdentities:[...i||[],F],platform:t?.attrs.name},reply:V}},Wh=(n,r)=>(n={...n},(!r||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),Ae.ADVSignedDeviceIdentity.encode(n).finish());var sE=Le(ar(),1);var g9=12,n9=Buffer.alloc(0),s9=n=>{let r=new ArrayBuffer(g9);return new DataView(r).setUint32(8,n),new Uint8Array(r)},Gk=class{constructor(r,o){this.encKey=r,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(g9)}encrypt(r){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,sc(r,this.encKey,this.iv,n9)}decrypt(r){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,gc(r,this.decKey,this.iv,n9)}},c9=({keyPair:{private:n,public:r},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(I9),A=a.byteLength===32?a:pl(a),t=A,s=A,g=A,c=0,l=!1,p=Buffer.alloc(0),B=null,Q=!1,f=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=pl(Buffer.concat([A,q])))},R=q=>{if(B)return B.encrypt(q);let j=sc(q,s,s9(c++),A);return m(j),j},k=q=>{if(B)return B.decrypt(q);let j=gc(q,g,s9(c++),A);return m(q),j},G=q=>{let j=eo(Buffer.from(q),64,{salt:t,info:""});return[j.subarray(0,32),j.subarray(32)]},K=q=>{let[j,F]=G(q);t=j,s=F,g=F,c=0},x=async()=>{Q=!0;let[q,j]=G(new Uint8Array(0));B=new Gk(q,j),Q=!1,i.trace("Noise handler transitioned to Transport state"),f&&(i.trace({length:p.length},"Flushing buffered frames after transport ready"),await H(f),f=null)},H=async q=>{let j;for(;;){if(p.length<3||(j=p[0]<<16|p[1]<<8|p[2],p.length{m(q.ephemeral),K(Ut.sharedKey(n,q.ephemeral));let F=k(q.static);K(Ut.sharedKey(n,F));let T=k(q.payload),{intermediate:V,leaf:U}=Ae.CertChain.decode(T);if(!U?.details||!U?.signature)throw new sE.Boom("invalid noise leaf certificate",{statusCode:400});if(!V?.details||!V?.signature)throw new sE.Boom("invalid noise intermediate certificate",{statusCode:400});let b=Ae.CertChain.NoiseCertificate.Details.decode(V.details),{issuerSerial:L}=b,X=Ut.verify(b.key,U.details,U.signature),pe=Ut.verify(Fk.PUBLIC_KEY,V.details,V.signature);if(!X)throw new sE.Boom("noise certificate signature invalid",{statusCode:400});if(!pe)throw new sE.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(L!==Fk.SERIAL)throw new sE.Boom("certification match failed",{statusCode:400});let me=R(j.public);return K(Ut.sharedKey(j.private,q.ephemeral)),me},encodeFrame:q=>{B&&(q=B.encrypt(q));let j=q.byteLength,F=l?0:y.length,T=Buffer.allocUnsafe(F+3+j);return l||(T.set(y),l=!0),T[F]=j>>>16&255,T[F+1]=j>>>8&255,T[F+2]=j&255,T.set(q,F+3),T},decodeFrame:async(q,j)=>{if(Q){p=Buffer.concat([p,q]),f=j;return}p.length===0?p=Buffer.from(q):p=Buffer.concat([p,q]),await H(j)}}};import{pipeline as IRe}from"stream/promises";import{promisify as lRe}from"util";import{createInflate as ERe,inflate as pRe}from"zlib";var CRe=lRe(pRe),hRe=n=>{for(let r of n){let o=r.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(nt(i)||Lt(i)))return i}},dRe=async(n,r)=>{let o=await nE(n,"md-msg-hist",{options:r}),i=ERe(),e=[];i.on("data",t=>e.push(t)),await IRe(o,i);let a=Buffer.concat(e);return Ae.HistorySync.decode(a)},uRe=(n,r)=>{let o=[],i=[],e=[],a=[];r?.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 Ae.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case Ae.HistorySync.HistorySyncType.RECENT:case Ae.HistorySync.HistorySyncType.FULL:case Ae.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 t=A.id,s=vA(t)||yr(t),g=nt(t)||Lt(t);if(s&&A.pnJid)a.push({lid:t,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:t});else if(s&&!A.pnJid){let l=hRe(A.messages||[]);l&&a.push({lid:t,pn:l})}let c=A.messages||[];delete A.messages;for(let l of c){let p=l.message;o.push(p),A.messages?.length||(A.messages=[{message:p}]),!p.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=or(p.messageTimestamp)),(p.messageStubType===QA.BIZ_PRIVACY_MODE_TO_BSP||p.messageStubType===QA.BIZ_PRIVACY_MODE_TO_FB)&&p.messageStubParameters?.[0]&&i.push({id:p.key.participant||p.key.remoteJid,verifiedName:p.messageStubParameters?.[0]})}e.push(A)}break;case Ae.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}},l9=async(n,r,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=Ae.HistorySync.decode(await CRe(n.initialHistBootstrapInlinePayload)):i=await dRe(n,r),uRe(i,o)},Jm=n=>(n?Hr(n):void 0)?.protocolMessage?.historySyncNotification;var Mi=Le(ar(),1);var Wo;(function(n){n.Chat="label_jid",n.Message="label_message"})(Wo||(Wo={}));var E9=new Il;var p9=(n,r,o)=>{let i=[];if(!r)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=nt(r),A=a?r:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:r,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&vA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:r}}),i},C9=(n,r)=>{for(let o of r)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var Zh=n=>{let r=fq(n);return{indexKey:r.indexKey,valueEncryptionKey:r.valueEncryptionKey,valueMacKey:r.valueMacKey,snapshotMacKey:r.snapshotMacKey,patchMacKey:r.patchMacKey}},h9=(n,r,o,i)=>{let e=n===Ae.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 t=new Uint8Array(8);t[7]=A.length;let s=new Uint8Array(A.length+r.length+t.length);return s.set(A,0),s.set(r,A.length),s.set(t,A.length+r.length),Ao(s,i,"sha512").subarray(0,32)},d9=n=>{let r=Buffer.alloc(8);return r.writeUint32BE(n,4),r},u9=({indexValueMap:n,hash:r})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let t=Buffer.from(e).toString("base64"),s=n[t];if(A===Ae.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[t]}else o.push(a),n[t]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=E9.subtractThenAdd(r,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},Lk=(n,r,o,i)=>{let e=Buffer.concat([n,d9(r),Buffer.from(o,"utf-8")]);return Ao(e,i,"sha256")},B9=(n,r,o,i,e)=>{let a=Buffer.concat([n,...r,d9(o),Buffer.from(i,"utf-8")]);return Ao(a,e)},qm=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),Uk=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),Hk=2,Xh=n=>n?.data?.isMissingKey===!0,Q9=(n,r)=>r>=Hk||n?.name==="TypeError",f9=async({type:n,index:r,syncAction:o,apiVersion:i,operation:e},a,A,t)=>{let s=a?await t(a):void 0;if(!s)throw new Mi.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(r)),l=Ae.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),p=Ae.SyncActionData.encode(l).finish(),B=Zh(s.keyData),Q=bq(p,B.valueEncryptionKey),f=h9(e,Q,g,B.valueMacKey),y=Ao(c,B.indexKey),m=u9(A);m.mix({indexMac:y,valueMac:f,operation:e}),Object.assign(A,m.finish()),A.version+=1;let R=Lk(A.hash,A.version,n,B.snapshotMacKey),k={patchMac:B9(R,[f],A.version,n,B.patchMacKey),snapshotMac:R,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([Q,f])},keyId:{id:g}}}]},G=y.toString("base64");return A.indexValueMap[G]={valueMac:f},{patch:k,state:A}},y9=async(n,r,o,i,e)=>{let a=u9(r),A=new Map;for(let s of n){let g="operation"in s?s.operation:Ae.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,l;try{l=await t(c.keyId.id)}catch(R){if(Xh(R))throw R;continue}let p=c.value.blob,B=p.subarray(0,-32),Q=p.subarray(-32);if(e){let R=h9(g,B,c.keyId.id,l.valueMacKey);if(Buffer.compare(R,Q)!==0)continue}let f;try{f=Mq(B,l.valueEncryptionKey)}catch{continue}let y=Ae.SyncActionData.decode(f);if(e){let R=Ao(y.index,l.indexKey);if(Buffer.compare(R,c.index.blob)!==0)throw new Mi.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:Q,operation:g})}return a.finish();async function t(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let l=await o(g);if(!l)throw new Mi.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let p=Zh(l.keyData);return A.set(g,p),p}},BRe=async(n,r,o,i,e,a)=>{if(a){let t=Buffer.from(n.keyId.id).toString("base64"),s=await i(t);if(!s)throw new Mi.Boom(`failed to find key "${t}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=Zh(s.keyData),c=n.mutations.map(p=>p.record.value.blob.slice(-32)),l=B9(n.snapshotMac,c,or(n.version.version),r,g.patchMacKey);if(Buffer.compare(l,n.patchMac)!==0)throw new Mi.Boom("Invalid patch mac")}return await y9(n.mutations,o,i,e,a)},m9=async(n,r)=>{let o=ie(n,"sync"),i=mA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=ie(a,"patches"),t=mA(A||a,"patch"),s=ie(a,"snapshot"),g=[],c=a.attrs.name,l=a.attrs.has_more_patches==="true",p;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=Ae.ExternalBlobReference.decode(s.content),Q=await S9(B,r);p=Ae.SyncdSnapshot.decode(Q)}for(let{content:B}of t)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let Q=Ae.SyncdPatch.decode(B);Q.version||(Q.version={version:+a.attrs.version+1}),g.push(Q)}e[c]={patches:g,hasMorePatches:l,snapshot:p}})),e},S9=async(n,r)=>{let o=await nE(n,"md-app-state",{options:r}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},QRe=async(n,r)=>{let o=await S9(n,r);return Ae.SyncdMutations.decode(o)},D9=async(n,r,o,i,e=!0,a)=>{let A=qm();A.version=or(r.version.version);let t={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await y9(r.records,A,o,s?l=>{let p=l.syncAction.index?.toString();t[p]=l}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let l=Buffer.from(r.keyId.id).toString("base64"),p=await o(l);if(!p)throw new Mi.Boom(`failed to find key "${l}" to decode mutation`,{data:{isMissingKey:!0}});let B=Zh(p.keyData),Q=Lk(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(r.mac,Q)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:t}},Kk=async(n,r,o,i,e,a,A,t=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of r){let{version:l,keyId:p,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:l},"downloading external patch");let m=await QRe(c.externalMutations,e);A?.debug({name:n,version:l,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let Q=or(l.version);s.version=Q;let f=typeof a>"u"||Q>a,y;try{y=await BRe(c,n,s,i,f?m=>{let R=m.syncAction.index?.toString();g[R]=m}:()=>{},t)}catch(m){if(Xh(m))throw m;A?.warn({name:n,version:Q,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,t){let m=Buffer.from(p.id).toString("base64"),R=await i(m);if(!R)throw new Mi.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let k=Zh(R.keyData),G=Lk(s.hash,s.version,n,k.snapshotMacKey);if(Buffer.compare(B,G)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},w9=(n,r)=>{let o=Ae.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 Mi.Boom("Incomplete key",{statusCode:400,data:s});if(ir(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new Mi.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!or(s.messageTimestamp))throw new Mi.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=oA(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",r],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",r],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",r],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:t}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:t,messageTimestamp:a}},index:["deleteMessageForMe",r,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",r,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",r],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",r],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",r,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",r,"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:[Wo.Chat,n.addChatLabel.labelId,r],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Wo.Chat,n.removeChatLabel.labelId,r],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Wo.Message,n.addMessageLabel.labelId,r,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Wo.Message,n.removeMessageLabel.labelId,r,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new Mi.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},O9=(n,r,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:t},index:[s,g,c,l]}=n;if(t?.muteAction)r.emit("chats.update",[{id:g,muteEndTime:t.muteAction?.muted?or(t.muteAction.muteEndTimestamp):null,conditional:p(g,void 0)}]);else if(t?.archiveChatAction||s==="archive"||s==="unarchive"){let Q=t?.archiveChatAction,f=Q?Q.archived:s==="archive",y=A?.unarchiveChats?Q?.messageRange:void 0;r.emit("chats.update",[{id:g,archived:f,conditional:p(g,y)}])}else if(t?.markChatAsReadAction){let Q=t.markChatAsReadAction,f=a&&Q.read;r.emit("chats.update",[{id:g,unreadCount:f?null:Q?.read?0:-1,conditional:p(g,Q?.messageRange)}])}else if(t?.deleteMessageForMeAction||s==="deleteMessageForMe")r.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:l==="1"}]});else if(t?.contactAction){let Q=p9(t.contactAction,g,e);C9(r,Q)}else if(t?.pushNameSetting){let Q=t?.pushNameSetting?.name;Q&&o?.name!==Q&&r.emit("creds.update",{me:{...o,name:Q}})}else if(t?.pinAction)r.emit("chats.update",[{id:g,pinned:t.pinAction?.pinned?or(t.timestamp):null,conditional:p(g,void 0)}]);else if(t?.unarchiveChatsSetting){let Q=!!t.unarchiveChatsSetting.unarchiveChats;r.emit("creds.update",{accountSettings:{unarchiveChats:Q}}),e?.info(`archive setting updated => '${t.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=Q)}else if(t?.starAction||s==="star"){let Q=t?.starAction?.starred;typeof Q!="boolean"&&(Q=n.index[n.index.length-1]==="1"),r.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:l==="1"},update:{starred:Q}}])}else if(t?.deleteChatAction||s==="deleteChat")a||r.emit("chats.delete",[g]);else if(t?.labelEditAction){let{name:Q,color:f,deleted:y,predefinedId:m}=t.labelEditAction;r.emit("labels.edit",{id:g,name:Q,color:f,deleted:y,predefinedId:m?String(m):void 0})}else t?.labelAssociationAction?r.emit("labels.association",{type:t.labelAssociationAction.labeled?"add":"remove",association:s===Wo.Chat?{type:Wo.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:Wo.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):t?.localeSetting?.locale?r.emit("settings.update",{setting:"locale",value:t.localeSetting.locale}):t?.timeFormatAction?r.emit("settings.update",{setting:"timeFormat",value:t.timeFormatAction}):t?.pnForLidChatAction?t.pnForLidChatAction.pnJid&&r.emit("lid-mapping.update",{lid:g,pn:t.pnForLidChatAction.pnJid}):t?.privacySettingRelayAllCalls?r.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:t.privacySettingRelayAllCalls}):t?.statusPrivacy?r.emit("settings.update",{setting:"statusPrivacy",value:t.statusPrivacy}):t?.lockChatAction?r.emit("chats.lock",{id:g,locked:!!t.lockChatAction.locked}):t?.privacySettingDisableLinkPreviewsAction?r.emit("settings.update",{setting:"disableLinkPreviews",value:t.privacySettingDisableLinkPreviewsAction}):t?.notificationActivitySettingAction?.notificationActivitySetting?r.emit("settings.update",{setting:"notificationActivitySetting",value:t.notificationActivitySettingAction.notificationActivitySetting}):t?.lidContactAction?r.emit("contacts.upsert",[{id:g,name:t.lidContactAction.fullName||t.lidContactAction.firstName||t.lidContactAction.username||void 0,username:t.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):t?.privacySettingChannelsPersonalisedRecommendationAction?r.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:t.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function p(Q,f){return a?y=>{let m=y.historySets.chats[Q]||y.chatUpserts[Q];if(m)return f?B(m,f):!0}:void 0}function B(Q,f){let y=Number(f?.lastMessageTimestamp||f?.lastSystemMessageTimestamp||0),m=Number(Q?.lastMessageRecvTimestamp||0);return y>=m}};var fRe=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,r){let o=(...i)=>{this.off(n,o),r(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let r=this._eventListeners.get(n);return r?r.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,r){let o=this._eventListeners.get(n)??[];return o.unshift(r),this._eventListeners.set(n,o),this}prependOnceListener(n,r){let o=(...i)=>{this.off(n,o),r(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,r){return this.on(n,r),this}on(n,r){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(r)),this}removeListener(n,r){return this.off(n,r),this}off(n,r){let o=this._eventListeners.get(n)??[],i=o.indexOf(r);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...r){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...r),o=!0;if(n===this._errorEvent){let e=r[0]instanceof Error?r[0]:new Error(`${r[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,r),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 r of this._eventListeners.values())r.length>n&&r.splice(n)}getAllListeners(){let n=[];for(let r of this._eventListeners.values())n=[...n,...r];return n}sendLog(n,r){if(!this._logger)return;let o;switch(typeof r=="string"?o=r:Array.isArray(r)&&r.length>0&&r[0]instanceof Error?o=r[0].message:r instanceof Error?o=r.message:Array.isArray(r)&&r.length>0&&typeof r[0]?.message=="string"?o=r[0].message:o=JSON.stringify(r),n){case"error":{this._logger.error?.(o,{event:n,data:r});break}case"warn":{this._logger.warn?.(o,{event:n,data:r});break}case"trace":{this._logger.trace?.(o,{event:n,data:r});break}case"debug":{this._logger.debug?.(o,{event:n,data:r});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:r});break}default:{this._logger.info?.(o,{event:n,data:r});break}}}},ig=class extends fRe{_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 r=n.trim().toLocaleLowerCase();if(!r.startsWith("before")&&!r.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 r=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${r?`: ${r}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,r){this.onHookEntry({event:n,handler:r})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let r=this._hooks.get(n.event);r?r.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,r){this.onHookEntry({event:n,handler:r})}onHooks(n){for(let r of n)this.onHook(r.event,r.handler)}prependHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(r):this._hooks.set(n,[r])}prependOnceHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),r(...i));this.prependHook(n,o)}onceHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),r(...i));this.onHook(n,o)}removeHook(n,r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(r);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let r of n)this.removeHook(r.event,r.handler)}async hook(n,...r){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...r)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...r){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(...r)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...r){await this.hook(`before:${n}`,...r)}async afterHook(n,...r){await this.hook(`after:${n}`,...r)}async callHook(n,...r){await this.hook(n,...r)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var yRe=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,r){if(this._enabled){if(this._store.has(n)){this._store.set(n,r);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,r)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},mRe=class{get name(){return"crc32"}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;r=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)}},Vm=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let r=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}},SRe=class{get name(){return"djb2"}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;r=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)}},DRe=class{get name(){return"fnv1"}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;r=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)}},wRe=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let r;if(n instanceof Uint8Array)r=n;else if(n instanceof ArrayBuffer)r=new Uint8Array(n);else if(n instanceof DataView)r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;r=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=r.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,r){if(Math.imul)return Math.imul(n,r);let o=n>>>16&65535,i=n&65535,e=r>>>16&65535,a=r&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,r){return n<>>32-r}},ORe=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 r of n)this._providers.set(r.name,r)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,r){let o=r?.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)}},Yk=class extends ig{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new ORe;_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 yRe(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,r){let o={data:n,algorithm:r?.algorithm??this._defaultAlgorithm,maxLength:r?.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 l=c;r?.maxLength&&l.length>r.maxLength&&(l=l.substring(0,r.maxLength));let p={hash:l,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",p),p.hash}}let A=new TextEncoder().encode(i),t=this._providers.get(o.algorithm);t||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),t=new Vm({algorithm:this._defaultAlgorithm}));let s=await t.toHash(A);this._cache.enabled&&this._cache.set(e,s),r?.maxLength&&s.length>r?.maxLength&&(s=s.substring(0,r.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,r={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=r;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),t=Number.parseInt(A,16),s=i-o+1;return o+t%s}toHashSync(n,r){let o={data:n,algorithm:r?.algorithm??this._defaultAlgorithmSync,maxLength:r?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let l=this._cache.get(a);if(l!==void 0){let p=l;r?.maxLength&&p.length>r.maxLength&&(p=p.substring(0,r.maxLength));let B={hash:p,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let t=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(t);this._cache.enabled&&this._cache.set(a,g),r?.maxLength&&g.length>r?.maxLength&&(g=g.substring(0,r.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,r={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=r;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),t=Number.parseInt(A,16),s=i-o+1;return o+t%s}loadProviders(n,r={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);r.includeBase&&(this.providers.add(new Vm({algorithm:"SHA-256"})),this.providers.add(new Vm({algorithm:"SHA-384"})),this.providers.add(new Vm({algorithm:"SHA-512"})),this.providers.add(new mRe),this.providers.add(new SRe),this.providers.add(new DRe),this.providers.add(new wRe))}};var Jk=n=>{let r;if(n!==void 0){if(typeof n=="number")r=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":r=a;break;case"s":r=a*1e3;break;case"m":r=a*1e3*60;break;case"h":r=a*1e3*60*60;break;case"hr":r=a*1e3*60*60;break;case"d":r=a*1e3*60*60*24;break;default:r=Number(n)}}else r=Number(n)}return r}},Rc=(n,r)=>{r??=new Date;let o=Jk(n);return o===void 0?r.getTime():r.getTime()+o};var $h=(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 xk(n,r={algorithm:"djb2",serialize:JSON.stringify}){let o=r?.algorithm??"djb2",i=(r?.serialize??JSON.stringify)(n);return new Yk().toHashSync(i,{algorithm:o})}function M9(n,r={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=r?.min??0,i=r?.max??10,e=r?.algorithm??"djb2",a=r?.serialize??JSON.stringify,A=r?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let t=a(n);return new Yk().toNumberSync(t,{algorithm:e,min:o,max:i,hashLength:A})}function qk(n,r){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=r;return(...A)=>{let t=MRe(n,A,{keyPrefix:i,serialize:a});r.createKey&&(t=r.createKey(n,A,r));let s=e.get(t);if(s===void 0)try{s=n(...A),e.set(t,s,o)}catch(g){e.emit("error",g),r.cacheErrors&&e.set(t,g,o)}return s}}function Vk(n,r,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=r()}catch(a){throw new zm(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new zm(a,"store")}}catch(a){let A=a instanceof zm?a.context:void 0,t=a instanceof zm?a.error:a;if(o.cache.emit("error",t),o.cacheErrors&&A==="function")try{o.cache.set(i,t,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw t}return e}function MRe(n,r,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${xk(r,{serialize:e})}`:`${n.name}::${xk(r,{serialize:e})}`}var zm=class{error;context;constructor(n,r){this.error=n,this.context=r}};var og=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,r=1){this._enabled&&(this._counters[n]+=r,this.touch())}decrement(n,r=1){this._enabled&&(this._counters[n]-=r,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 r=[],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(r.includes(e))continue;r.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,r,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[r]+=o,this.touch()}mostUsedKeys(n=100,r){return this.sortedKeyEntries(r,"desc").slice(0,n)}leastUsedKeys(n=100,r){return this.sortedKeyEntries(r,"asc").slice(0,n)}keyStats(n){let r=this._trackedKeys.get(n);return r?this.toKeyEntry(n,r):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,r){let o=r.hits+r.misses;return{key:n,count:this.totalOf(r),hits:r.hits,misses:r.misses,gets:r.gets,sets:r.sets,deletes:r.deletes,hitRate:o===0?0:r.hits/o}}sortedKeyEntries(n,r){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=r==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,t=n?a[n]:a.count;return A!==t?(A-t)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=r)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,r){for(let[o,i]of Object.entries(r)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let r=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){r.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=r}applyEvent(n,r){if(this._enabled){if(typeof n=="function"){n(this,...r);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var bRe=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},zk=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let r=new bRe(n);this.head?(r.next=this.head,this.head.prev=r,this.head=r):this.head=this.tail=r,this.nodesMap.set(n,r)}moveToFront(n){let r=this.nodesMap.get(n);if(!r||this.head===r)return;r.prev&&(r.prev.next=r.next);r.next&&(r.next.prev=r.prev);r===this.tail&&(this.tail=r.prev),r.prev=void 0,r.next=this.head;this.head&&(this.head.prev=r),this.head=r,this.tail??=r}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 r=this.nodesMap.get(n);return r?(r.prev?r.prev.next=r.next:(this.head=r.next,this.head&&(this.head.prev=void 0)),r.next?r.next.prev=r.prev:(this.tail=r.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var b9=16777216,Wk=class extends ig{_lru=new zk;_storeHashSize=16;_storeHashAlgorithm=$h.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new og({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 ${b9} 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 ${b9} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new zk;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let r of this._store)n+=r.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 r of this._store)for(let o of r.keys()){let i=r.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),r.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let r of this._store)for(let o of r.values()){if(this.hasExpired(o)){this.recordExpiration(o),r.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 r=this.getStore(n),o=r.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),r.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 r=[];for(let o of n)r.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:r}),r}getRaw(n){let r=this.getStore(n),o=r.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),r.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let r=[];for(let o of n)r.push(this.getRaw(o));return r}set(n,r,o){let i={key:n,value:r,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=Rc(A.ttl);s!==void 0&&(a=s)}}else{let s=Rc(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=Rc(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 t={key:i.key,value:i.value,expires:a};e.set(i.key,t),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let r of n)this.set(r.key,r.value,r.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let r=[];for(let o of n){let i=this.get(o);r.push(!!i)}return r}take(n){let r=this.get(n);if(r)return this.delete(n),r}takeMany(n){let r=[];for(let o of n)r.push(this.take(o));return r}delete(n){this.hookSync("BEFORE_DELETE",n);let r=this.getStore(n);if(this._stats.enabled){let o=r.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}r.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let r of n)this.delete(r);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new zk,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let r=this.getKeyStoreHash(n);return this._store[r]||=new Map,this._store[r]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):M9(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 r of n.values())r.expires&&Date.now()>r.expires&&(this.recordExpiration(r),n.delete(r.key),this.lruRemove(r.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,r){return qk(n,{ttl:r?.ttl??this._ttl,keyPrefix:r?.keyPrefix,createKey:r?.createKey,cache:this})}getOrSet(n,r,o){return Vk(n,r,{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 PRe=class extends ig{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new og({enabled:!0});_cacheable=new Wk;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,r,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:r,ttl:a}),this.emit("set",i,r,e),this._stats.incrementKSize(i),this._stats.incrementVSize(r),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 r of n)this.set(r.key,r.value,r.ttl);return!0}get(n){let r=this.store.get(this.formatKey(n));if(r){if(r.ttl>0){if(r.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 Rc(n);let r=Date.now(),o=n*1e3;return r+o}checkData(){for(let[n,r]of this.store.entries())r.ttl>0&&r.ttl{let a={resolve:i,reject:e,weight:r,priority:o},A=N9(this._queue,t=>o<=t.priority);A===-1&&r<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(r){return FRe(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(r=1,o=0){if(r<=0)throw new Error(`invalid weight ${r}: must be positive`);return this._couldLockImmediately(r,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[r-1]||(this._weightedWaiters[r-1]=[]),LRe(this._weightedWaiters[r-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(r){this._value=r,this._dispatchQueue()}release(r=1){if(r<=0)throw new Error(`invalid weight ${r}: must be positive`);this._value+=r,this._dispatchQueue()}cancel(){this._queue.forEach(r=>r.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(r){let o=this._value;this._value-=r.weight,r.resolve([o,this._newReleaser(r.weight)])}_newReleaser(r){let o=!1;return()=>{o||(o=!0,this.release(r))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let r=this._value;r>0;r--){let o=this._weightedWaiters[r-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[r-1]=[])}else{let r=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<=r);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(r,o){return(this._queue.length===0||this._queue[0].priorityr.priority<=i.priority);n.splice(o+1,0,r)}function N9(n,r){for(let o=n.length-1;o>=0;o--)if(r(n[o]))return o;return-1}var URe=function(n,r,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 t(c){try{g(i.next(c))}catch(l){A(l)}}function s(c){try{g(i.throw(c))}catch(l){A(l)}}function g(c){c.done?a(c.value):e(c.value).then(t,s)}g((i=i.apply(n,r||[])).next())})},jn=class{constructor(r){this._semaphore=new Zk(1,r)}acquire(){return URe(this,arguments,void 0,function*(r=0){let[,o]=yield this._semaphore.acquire(1,r);return o})}runExclusive(r,o=0){return this._semaphore.runExclusive(()=>r(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(r=0){return this._semaphore.waitForUnlock(1,r)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as jRe}from"crypto";var $k=Le(R9(),1);var ev=class n extends Error{name="TimeoutError";constructor(r,o){super(r,o),Error.captureStackTrace?.(this,n)}},k9=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function Av(n,r){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=r,t,s,c=new Promise((l,p)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){p(k9(A));return}if(A&&(s=()=>{p(k9(A))},A.addEventListener("abort",s,{once:!0})),n.then(l,p),o===Number.POSITIVE_INFINITY)return;let B=new ev;t=a.setTimeout.call(void 0,()=>{if(i){try{l(i())}catch(Q){p(Q)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?l():e instanceof Error?p(e):(B.message=e??`Promise timed out after ${o} milliseconds`,p(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,t),t=void 0},c}function tv(n,r,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],r)<=0?(i=++A,e-=a+1):e=a}return i}var YRe=100,gE=class{#e=[];#A=0;enqueue(r,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:r};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 t=tv(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(t,0,A)}setPriority(r,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===r);if(i===-1)throw new ReferenceError(`No promise function with the id "${r}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:r})}remove(r){let o=this.#e.findIndex((i,e)=>eYRe&&this.#A>this.#e.length/2&&this.#t(),r?.run}filter(r){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${r.intervalCap?.toString()??""}\` (${typeof r.intervalCap})`);if(r.interval===void 0||!(Number.isFinite(r.interval)&&r.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${r.interval?.toString()??""}\` (${typeof r.interval})`);if(r.strict&&r.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(r.strict&&r.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=r.carryoverIntervalCount??r.carryoverConcurrencyCount??!1,this.#A=r.intervalCap===Number.POSITIVE_INFINITY||r.interval===0,this.#r=r.intervalCap,this.#E=r.interval,this.#i=r.strict,this.#l=new r.queueClass,this.#p=r.queueClass,this.concurrency=r.concurrency,r.timeout!==void 0&&!(Number.isFinite(r.timeout)&&r.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${r.timeout}\` (${typeof r.timeout})`);this.timeout=r.timeout,this.#d=r.autoStart===!1,this.#K()}#y(r){for(;this.#c=this.#E)this.#c++;else break}(this.#c>100&&this.#c>this.#o.length/2||this.#c===this.#o.length)&&(this.#o=this.#o.slice(this.#c),this.#c=0)}#f(r){this.#i?this.#o.push(r):this.#t++}#D(){this.#i?this.#o.length>this.#c&&this.#o.pop():this.#t>0&&this.#t--}#m(){return this.#o.length-this.#c}get#w(){return this.#A?!0:this.#i?this.#m()=this.#r){let i=this.#o[this.#c],e=this.#E-(r-i);return this.#F(e),!0}return!1}if(this.#I===void 0){let o=this.#s-r;if(o<0)this.#t=this.#e?this.#h:0;else return this.#F(o),!0}return!1}#F(r){this.#a===void 0&&(this.#a=setTimeout(()=>{this.#O()},r))}#T(){this.#I&&(clearInterval(this.#I),this.#I=void 0)}#L(){this.#a&&(clearTimeout(this.#a),this.#a=void 0)}#k(){if(this.#l.size===0){if(this.#T(),this.emit("empty"),this.#h===0){if(this.#L(),this.#i&&this.#c>0){let o=Date.now();this.#y(o)}this.emit("idle")}return!1}let r=!1;if(!this.#d){let o=Date.now(),i=!this.#M(o);if(this.#w&&this.#N){let e=this.#l.dequeue();this.#A||(this.#f(o),this.#G()),i&&this.#v(),this.emit("active"),e(),r=!0}}return r}#v(){this.#A||this.#I!==void 0||this.#i||(this.#I=setInterval(()=>{this.#b()},this.#E),this.#s=Date.now()+this.#E)}#b(){this.#i||(this.#I!==void 0&&(this.#t===0&&this.#h===0?this.#T():this.#s=Date.now()+this.#E),this.#t=this.#e?this.#h:0),this.#P(),this.#G()}#P(){for(;this.#k(););}get concurrency(){return this.#C}set concurrency(r){if(!(typeof r=="number"&&r>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${r}\` (${typeof r})`);this.#C=r,this.#P()}setPriority(r,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#l.setPriority(r,o)}async add(r,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#Q++).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=()=>{},t=async()=>{A(),this.#h++,this.#u.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(p){throw this.#H(),this.#u.delete(a),p}let c=r({signal:o.signal});if(o.timeout!==void 0&&(c=Av(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#h} running, ${this.#l.size} waiting)`})),o.signal){let{signal:p}=o;c=Promise.race([c,new Promise((B,Q)=>{g=()=>{Q(p.reason)},p.addEventListener("abort",g,{once:!0})})])}let l=await c;i(l),this.emit("completed",l)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#u.delete(a),queueMicrotask(()=>{this.#S()})}};this.#l.enqueue(t,o);let s=()=>{if(this.#l instanceof gE){this.#l.remove(t);return}this.#l.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#k(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#B.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#B.add(A)}this.emit("add"),this.#k()})}async addAll(r,o){return Promise.all(r.map(async i=>this.add(i,o)))}start(){return this.#d?(this.#d=!1,this.#P(),this):this}pause(){this.#d=!0}clear(){for(let r of this.#B)r();this.#l=new this.#p,this.#T(),this.#Y(),this.emit("empty"),this.#h===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#l.size!==0&&await this.#R("empty")}async onSizeLessThan(r){this.#l.sizethis.#l.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#R(r,o){let i=Array.isArray(r)?r:[r];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.#l.size}sizeBy(r){return this.#l.filter(r).length}get pending(){return this.#h}get isPaused(){return this.#d}#K(){this.#A||(this.on("add",()=>{this.#l.size>0&&this.#G()}),this.on("next",()=>{this.#G()}))}#G(){this.#A||this.#n||(this.#n=!0,queueMicrotask(()=>{this.#n=!1,this.#Y()}))}#H(){this.#A||(this.#D(),this.#G())}#Y(){let r=this.#g;if(this.#A||this.#l.size===0){r&&(this.#g=!1,this.emit("rateLimitCleared"));return}let o;if(this.#i){let e=Date.now();this.#y(e),o=this.#m()}else o=this.#t;let i=o>=this.#r;i!==r&&(this.#g=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#g}get isSaturated(){return this.#h===this.#C&&this.#l.size>0||this.isRateLimited&&this.#l.size>0}get runningTasks(){return[...this.#u.values()].map(r=>({...r,timeoutRemaining:r.timeout?Math.max(0,r.startTime+r.timeout-Date.now()):void 0}))}};var Zm=class{constructor(r,o){this.store=r,this.logger=o,this.queues=new Map}getQueue(r){return this.queues.has(r)||this.queues.set(r,new kc({concurrency:1})),this.queues.get(r)}async processOperations(r,o,i,e,a){let A=r[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let t=[],s={};for(let g in A)A[g]===null?t.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),t.length>0&&await this.processDeletions(o,t,i,e,a)})}async processDeletions(r,o,i,e,a){if(a)for(let A of o)i[r]?.[A]?(i[r][A]=null,e[r][A]=null):this.logger.warn(`Skipping deletion of non-existent ${r} in transaction: ${A}`);else{let A=await this.store.get(r,o);for(let t of o)A[t]?(i[r][t]=null,e[r][t]=null):this.logger.warn(`Skipping deletion of non-existent ${r}: ${t}`)}}async validateDeletions(r,o){let i=r[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 r[o][A])})}};var P9=(n,r,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new xRe,a=new Map,A=new Map,t=new Map,s=new Zm(n,r);function g(f){return a.has(f)||a.set(f,new kc({concurrency:1})),a.get(f)}function c(f){return A.has(f)||(A.set(f,new jn),t.set(f,0)),A.get(f)}function l(f){let y=t.get(f)??0;t.set(f,y+1)}function p(f){let y=(t.get(f)??1)-1;if(t.set(f,y),y<=0){let m=A.get(f);m&&!m.isLocked()&&(A.delete(f),t.delete(f))}}function B(){return!!e.getStore()}async function Q(f){if(Object.keys(f).length===0){r.trace("no mutations in transaction");return}r.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(f,y);let R=m.cache[f]||{},k=y.filter(K=>!(K in R));if(k.length>0){m.dbQueries++,r.trace({type:f,count:k.length},"fetching missing keys in transaction");let K=await c(f).runExclusive(()=>n.get(f,k));m.cache[f]=m.cache[f]||{},Object.assign(m.cache[f],K)}let G={};for(let K of y){let x=m.cache[f]?.[K];x!=null&&(G[K]=x)}return G},set:async f=>{let y=e.getStore();if(!y){let m=Object.keys(f);for(let R of m){let k=R;k==="pre-key"&&await s.validateDeletions(f,k)}await Promise.all(m.map(R=>g(R).add(async()=>{let k={[R]:f[R]};await n.set(k)})));return}r.trace({types:Object.keys(f)},"caching in transaction");for(let m in f){let R=m;y.cache[R]=y.cache[R]||{},y.mutations[R]=y.mutations[R]||{},R==="pre-key"?await s.processOperations(f,R,y.cache,y.mutations,!0):(Object.assign(y.cache[R],f[R]),Object.assign(y.mutations[R],f[R]))}},isInTransaction:B,transaction:async(f,y)=>{if(e.getStore())return r.trace("reusing existing transaction context"),f();let R=c(y);l(y);try{return await R.runExclusive(async()=>{let k={cache:{},mutations:{},dbQueries:0};r.trace("entering transaction");try{let G=await e.run(k,f);return await Q(k.mutations),r.trace({dbQueries:k.dbQueries},"transaction completed"),G}catch(G){throw r.error({error:G},"transaction failed, rolling back"),G}})}finally{p(y)}}}},G9=n=>{let r=n.me?.id;if(!r)throw new v9.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return r},F9=()=>{let n=Ut.generateKeyPair();return{noiseKey:Ut.generateKeyPair(),pairingEphemeralKeyPair:Ut.generateKeyPair(),signedIdentityKey:n,signedPreKey:Ff(n,1),registrationId:vq(),advSecretKey:jRe(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 JRe,readFile as qRe,stat as VRe,unlink as zRe,writeFile as WRe}from"fs/promises";import{join as rv}from"path";var L9=new Map,av=n=>{let r=L9.get(n);return r||(r=new jn,L9.set(n,r)),r},U9=async n=>{let r=async(t,s)=>{let g=rv(n,a(s));return av(g).acquire().then(async l=>{try{await WRe(g,JSON.stringify(t,WC.replacer))}finally{l()}})},o=async t=>{try{let s=rv(n,a(t));return await av(s).acquire().then(async c=>{try{let l=await qRe(s,{encoding:"utf-8"});return JSON.parse(l,WC.reviver)}finally{c()}})}catch{return null}},i=async t=>{try{let s=rv(n,a(t));return av(s).acquire().then(async c=>{try{await zRe(s)}catch{}finally{c()}})}catch{}},e=await VRe(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 JRe(n,{recursive:!0});let a=t=>t?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||F9();return{state:{creds:A,keys:{get:async(t,s)=>{let g={};return await Promise.all(s.map(async c=>{let l=await o(`${t}-${c}.json`);t==="app-state-sync-key"&&l&&(l=Ae.Message.AppStateSyncKeyData.fromObject(l)),g[c]=l})),g},set:async t=>{let s=[];for(let g in t)for(let c in t[g]){let l=t[g][c],p=`${g}-${c}.json`;s.push(l?r(l,p):i(p))}await Promise.all(s)}}},saveCreds:async()=>r(A,"creds.json")}};var ZRe=192,XRe=async(n,{thumbnailWidth:r,fetchOpts:o})=>{let i=await Km(n,o);return await Sk(i,r)},H9=async(n,r={thumbnailWidth:ZRe,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,{...r.fetchOpts,followRedirects:"follow",handleRedirects:(t,s)=>{let g=new URL(t),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:r.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[t]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:t};if(r.uploadImage){let{imageMessage:g}=await Jh({image:{url:t}},{upload:r.uploadImage,mediaTypeOverride:"thumbnail-link",options:r.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=t?(await XRe(t,r)).buffer:void 0}catch(g){r.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 ske from"events";var ov=Le(ar(),1);var $Re=/^1313555\d{4}$|^131655500\d{2}$/;function eke(n){if(!n)return!1;let r=n.split("@")[0]??"";return r==="0"||$Re.test(r)||gl(n)?!1:!!(nt(n)||vA(n)||Lt(n)||yr(n)||n.endsWith("@c.us"))}var Xm=604800,Ake=4,sg="__index";async function $m(n){let o=(await n.get("tctoken",[sg]))[sg];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!==sg):[]}catch{return[]}}async function cE(n,r){let o=await $m(n),i=new Set(o);for(let e of r)e&&e!==sg&&i.add(e);return{[sg]:{token:Buffer.from(JSON.stringify([...i]))}}}function vc(n){if(n==null)return!0;let r=typeof n=="string"?parseInt(n):n;if(isNaN(r))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/Xm)-(Ake-1))*Xm;return ri}async function Zo(n,r){return vA(n)?n:await r(n)??n}async function Ad(n,r,o,i){return r?vA(n)?n:await o(n)??n:vA(n)&&i?await i(n)??n:n}async function iv({authState:n,jid:r,baseContent:o=[],getLIDForPN:i}){try{let e=await Zo(r,i),A=(await n.keys.get("tctoken",[e]))?.[e],t=A?.token,s=A?.timestamp;if(!t?.length||s===void 0||vc(s)){if(t){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:t}),o}catch{return o.length>0?o:void 0}}async function IE({result:n,fallbackJid:r,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=ie(n,"tokens");if(!a)return;let A=mA(a,"token");for(let t of A){if(t.attrs.type!=="trusted_contact"||!(t.content instanceof Uint8Array))continue;let s=oA(r||t.attrs.jid);if(!eke(s))continue;let g=await Zo(s,i),l=(await o.get("tctoken",[g]))[g],p=l?.timestamp?Number(l.timestamp):0,B=t.attrs.t?Number(t.attrs.t):0;B&&(p>0&&p>B||(await o.set({tctoken:{[g]:{...l,token:Buffer.from(t.content),timestamp:t.attrs.t}}}),e?.(g)))}}var tke=new Set([QA.CALL_MISSED_GROUP_VIDEO,QA.CALL_MISSED_GROUP_VOICE,QA.CALL_MISSED_VIDEO,QA.CALL_MISSED_VOICE]),rke=new Set([QA.GROUP_PARTICIPANT_ADD]);async function ake(n,r,o,i){let e=r.lidMapping.getLIDForPN.bind(r.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?or(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let l=oA(g.id),p=await Zo(l,e);a.push({storageJid:p,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?or(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),t=await o.get("tctoken",A),s={};for(let g of a){let c=t[g.storageJid],l=c?.timestamp?Number(c.timestamp):0;l>0&&l>=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 cE(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Y9=(n,r,o)=>{Lt(n.key.remoteJid)||yr(n.key.remoteJid)?n.key.remoteJid=Ft(lA(n.key?.remoteJid)?.user,Lt(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=oA(n.key.remoteJid),Lt(n.key.participant)||yr(n.key.participant)?n.key.participant=Ft(lA(n.key.participant)?.user,Lt(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=oA(n.key.participant);let i=Hr(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:lt(a.participant||a.remoteJid,r)||lt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},nv=n=>{let r=Hr(n.message),o=!!qh(r);return(!!r||tke.has(n.messageStubType)||rke.has(n.messageStubType))&&o&&!r?.protocolMessage&&!r?.reactionMessage&&!r?.pollUpdateMessage},sv=n=>!n.key.fromMe&&!n.messageStubType,ike=({remoteJid:n,participant:r,fromMe:o})=>{if(!n)throw new ov.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:r,fromMe:o}});if(HC(n)&&!_n(n)&&!o){if(!r)throw new ov.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return r}return n};function oke({encPayload:n,encIv:r},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([l(i),l(o),l(a),l("Event Response"),new Uint8Array([1])]),t=Ao(e,new Uint8Array(32),"sha256"),s=Ao(A,t,"sha256"),g=l(`${i}\0${a}`),c=gc(n,s,r,g);return Ae.Message.EventResponseMessage.decode(c);function l(p){return Buffer.from(p)}}var nke=async(n,{shouldProcessHistoryMsg:r,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:t,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:l}=e,p={id:oA(ike(n.key))},B=nv(n);B&&(p.messages=[{message:n}],p.conversationTimestamp=or(n.messageTimestamp),sv(n)&&(p.unreadCount=(p.unreadCount||0)+1));let Q=Hr(n.message);(B||Q?.reactionMessage?.key?.fromMe)&&l?.unarchiveChats&&(p.archived=!1,p.readOnly=!1);let f=Q?.protocolMessage;if(f){let y=new Set([Ae.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,Ae.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,Ae.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,Ae.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(f.type!==null&&f.type!==void 0&&y.has(f.type)&&!n.key.fromMe){t?.warn({msgId:n.key.id,type:f.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(f.type){case Ae.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=f.historySyncNotification,R=r,k=!e.processedHistoryMessages?.length;if(t?.info({histNotification:m,process:R,id:n.key.id,isLatest:k},"got history notification"),R){m.syncType!==Ae.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let T=await l9(m,s,t);T.lidPnMappings?.length&&(t?.debug({count:T.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(T.lidPnMappings).catch(V=>t?.warn({err:V},"failed to store LID-PN mappings from history sync"))),await ake(T.chats,a,A,t),i.emit("messaging-history.set",{...T,isLatest:m.syncType!==Ae.HistorySync.HistorySyncType.ON_DEMAND?k:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case Ae.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let G=f.appStateSyncKeyShare.keys;if(G?.length){let T="";await A.transaction(async()=>{let V=[];for(let{keyData:U,keyId:b}of G){let L=Buffer.from(b.keyId).toString("base64");V.push(L),await A.set({"app-state-sync-key":{[L]:U}}),T=L}t?.info({newAppStateSyncKeyId:T,newKeys:V},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:T})}else t?.info({protocolMsg:f},"recv app state sync with 0 keys");break;case Ae.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:f.key.id},update:{message:null,messageStubType:QA.REVOKE,key:n.key}}]);break;case Ae.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(p,{ephemeralSettingTimestamp:or(n.messageTimestamp),ephemeralExpiration:f.ephemeralExpiration||null});break;case Ae.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let K=f.peerDataOperationRequestResponseMessage;if(K){let T=K.peerDataOperationResult||[];for(let V of T){let U=V?.placeholderMessageResendResponse;if(U?.webMessageInfoBytes)try{let b=Ae.WebMessageInfo.decode(U.webMessageInfoBytes),L=b.key?.id,X=L?await o?.get(L):void 0;L&&await o?.del(L);let pe;X&&typeof X=="object"?(X.message=b.message,b.messageTimestamp&&(X.messageTimestamp=b.messageTimestamp),pe=X):pe=b,t?.debug({msgId:L,requestId:K.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[pe],type:"notify",requestId:K.stanzaId})}catch(b){t?.warn({err:b,stanzaId:K.stanzaId},"failed to decode placeholder resend response")}}}break;case Ae.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:f.key?.id},update:{message:{editedMessage:{message:f.editedMessage}},messageTimestamp:f.timestampMs?Math.floor(or(f.timestampMs)/1e3):n.messageTimestamp}}]);break;case Ae.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let x=f.memberLabel;x?.label&&i.emit("group.member-tag.update",{groupId:p.id,label:x.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case Ae.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let H=f.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:j}=Ae.LIDMigrationMappingSyncPayload.decode(H);t?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:j},"got lid mappings and chat db migration timestamp");let F=[];for(let{pn:T,latestLid:V,assignedLid:U}of q){let b=V||U;F.push({lid:`${b}@lid`,pn:`${T}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(F),F.length)for(let{pn:T,lid:V}of F)await a.migrateSession(T,V)}}else if(Q?.reactionMessage){let y={...Q.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:Q.reactionMessage?.key}])}else if(Q?.encEventResponseMessage){let y=Q.encEventResponseMessage,m=y.eventCreationMessageKey,R=await g(m);if(R)try{let k=oA(c),G=m.participant||m.remoteJid,K=vA(G)?await a.lidMapping.getPNForLID(G):G,x=Cl({remoteJid:oA(K),fromMe:k===K},k),H=Cl(n.key,k),q=R?.messageContextInfo?.messageSecret;if(!q)t?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let j=oke(y,{eventEncKey:q,eventCreatorJid:x,eventMsgId:m.id,responderJid:H}),F={eventResponseMessageKey:n.key,senderTimestampMs:j.timestampMs,response:j};i.emit("messages.update",[{key:m,update:{eventResponses:[F]}}])}}catch(k){t?.warn({err:k,creationMsgKey:m},"failed to decrypt event response")}else t?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,R=x=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:x}),k=x=>{i.emit("groups.update",[{id:y,...x,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},G=(x,H,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:x.lid,participantPn:x.pn,action:H,method:q})},K=()=>m.find(x=>lt(c,x.phoneNumber));switch(n.messageStubType){case QA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("modify");break;case QA.GROUP_PARTICIPANT_LEAVE:case QA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("remove"),K()&&(p.readOnly=!0);break;case QA.GROUP_PARTICIPANT_ADD:case QA.GROUP_PARTICIPANT_INVITE:case QA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],K()&&(p.readOnly=!1),R("add");break;case QA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("demote");break;case QA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(X=>JSON.parse(X))||[],R("promote");break;case QA.GROUP_CHANGE_ANNOUNCE:let x=n.messageStubParameters?.[0];k({announce:x==="true"||x==="on"});break;case QA.GROUP_CHANGE_RESTRICT:let H=n.messageStubParameters?.[0];k({restrict:H==="true"||H==="on"});break;case QA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];p.name=q,k({subject:q});break;case QA.GROUP_CHANGE_DESCRIPTION:let j=n.messageStubParameters?.[0];p.description=j,k({desc:j});break;case QA.GROUP_CHANGE_INVITE_LINK:let F=n.messageStubParameters?.[0];k({inviteCode:F});break;case QA.GROUP_MEMBER_ADD_MODE:let T=n.messageStubParameters?.[0];k({memberAddMode:T==="all_member_add"});break;case QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let V=n.messageStubParameters?.[0];k({joinApprovalMode:V==="on"});break;case QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let U=JSON.parse(n.messageStubParameters?.[0]),b=n.messageStubParameters?.[1],L=n.messageStubParameters?.[2];G(U,b,L);break}}Object.keys(p).length>1&&i.emit("chats.update",[p])},x9=nke;var gke=["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"],cke=new Set(gke),j9=n=>{let r=new ske,o=new Set,i=gv(),e=!1,a=null,A=null,t=0,s=1e4,g=3e4;r.on("event",p=>{for(let B in p)r.emit(B,p[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,t=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),l())},g)),t++}function l(){if(!e)return!1;n.debug({bufferCount:t},"Flushing event buffer"),e=!1,t=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 p=gv(),B=Object.values(i.chatUpdates),Q=0;for(let y of B)y.conditional&&(Q+=1,p.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let f=lke(i);return Object.keys(f).length&&r.emit("event",f),i=p,n.trace({conditionalChatUpdatesLeft:Q},"released buffered events"),!0}return{process(p){let B=async Q=>{await p(Q)};return r.on("event",B),()=>{r.off("event",B)}},emit(p,B){if(p==="messages.upsert"){let{type:Q}=B,f=Object.values(i.messageUpserts);if(f.length>0){let y=f[0].type;y!==Q&&(n.debug({bufferedType:y,newType:Q},"messages.upsert type mismatch, emitting buffered messages"),r.emit("event",{"messages.upsert":{messages:f.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&cke.has(p)?(Ike(i,o,p,B,n),!0):r.emit("event",{[p]:B})},isBuffering(){return e},buffer:c,flush:l,createBufferedFunction(p){return async(...B)=>{c();try{let Q=await p(...B);return t===1&&setTimeout(()=>{e&&t===1&&l()},100),Q}catch(Q){throw Q}finally{t=Math.max(0,t-1),t===0&&(A||(A=setTimeout(l,100)))}}},on:(...p)=>r.on(...p),off:(...p)=>r.off(...p),removeAllListeners:(...p)=>r.removeAllListeners(...p),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=gv(),e=!1,t=0,r.removeAllListeners(),n.debug("Event buffer destroyed")}}},gv=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function Ike(n,r,o,i,e){switch(o){case"messaging-history.set":for(let f of i.chats){let y=f.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=f.endOfHistoryTransferType),!m&&!r.has(y)&&(n.historySets.chats[y]=f,r.add(y),a(f))}for(let f of i.contacts){let y=n.historySets.contacts[f.id];if(y)Object.assign(y,Hf(f));else{let m=`c:${f.id}`,R=f.notify||f.name||f.verifiedName;(!r.has(m)||R)&&(n.historySets.contacts[f.id]=f,r.add(m))}}for(let f of i.messages){let y=lE(f.key);!n.historySets.messages[y]&&!r.has(y)&&(n.historySets.messages[y]=f,r.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let f=new Map,y=R=>`${R.userJid||""}:${R.leaveTs||""}:${R.leaveReason||""}`,m=R=>{let k=R.groupJid??JSON.stringify(R),G=f.get(k);if(!G){f.set(k,{...R,pastParticipants:[...R.pastParticipants||[]]});return}let K=new Set((G.pastParticipants||[]).map(y));for(let x of R.pastParticipants||[]){let H=y(x);K.has(H)||(G.pastParticipants.push(x),K.add(H))}};for(let R of n.historySets.pastParticipants||[])m(R);for(let R of i.pastParticipants)m(R);n.historySets.pastParticipants=[...f.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 f of i){let y=f.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=eS(m,f):(m=f,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let f of i){let y=f.id,m=f.conditional?f.conditional(n):!0;if(m){delete f.conditional;let R=n.historySets.chats[y]||n.chatUpserts[y];if(R)eS(R,f);else{let k=n.chatUpdates[y]||{};n.chatUpdates[y]=eS(k,f)}}else m===void 0&&(n.chatUpdates[y]=f);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let f of i)n.chatDeletes.has(f)||n.chatDeletes.add(f),n.chatUpdates[f]&&delete n.chatUpdates[f],n.chatUpserts[f]&&delete n.chatUpserts[f],n.historySets.chats[f]&&delete n.historySets.chats[f];break;case"contacts.upsert":for(let f of i){let y=n.contactUpserts[f.id];y||(y=n.historySets.contacts[f.id],y&&e.debug({contactId:f.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,Hf(f)):(y=f,n.contactUpserts[f.id]=y),n.contactUpdates[f.id]&&(y=Object.assign(n.contactUpdates[f.id],Hf(f)),delete n.contactUpdates[f.id])}break;case"contacts.update":let t=i;for(let f of t){let y=f.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,f);else{let R=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(R,f)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let f of s){let y=lE(f.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(f.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(f,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=f:n.messageUpserts[y]={message:f,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:f,update:y}of c){let m=lE(f),R=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(R)Object.assign(R,y),y.status===sl.READ&&!f.fromMe&&A(R);else{let k=n.messageUpdates[m]||{key:f,update:{}};Object.assign(k.update,y),n.messageUpdates[m]=k}}break;case"messages.delete":let l=i;if("keys"in l){let{keys:f}=l;for(let y of f){let m=lE(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 p=i;for(let{key:f,reaction:y}of p){let m=lE(f),R=n.messageUpserts[m];R?Tk(R.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:f,reactions:[]},Tk(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:f,receipt:y}of B){let m=lE(f),R=n.messageUpserts[m];R?Nk(R.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:f,userReceipt:[]},Nk(n.messageReceipts[m],y))}break;case"groups.update":let Q=i;for(let f of Q){let y=f.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,f))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(t){let s=t.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(t,eS(g,t)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(t){let s=t.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];nv(t)&&sv(t)&&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 lke(n){let r={};n.historySets.empty||(r["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&&(r["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(r["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(r["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;r["messages.upsert"]={messages:a.map(Q=>Q.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(r["messages.update"]=A);let t=Object.values(n.messageDeletes);t.length&&(r["messages.delete"]={keys:t});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:Q})=>Q.flatMap(f=>({key:B,reaction:f})));s.length&&(r["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:Q})=>Q.flatMap(f=>({key:B,receipt:f})));g.length&&(r["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(r["contacts.upsert"]=c);let l=Object.values(n.contactUpdates);l.length&&(r["contacts.update"]=l);let p=Object.values(n.groupUpdates);return p.length&&(r["groups.update"]=p),r}function eS(n,r){return r.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,r.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof r.unreadCount=="number"&&(r={...r},r.unreadCount>=0&&(r.unreadCount=Math.max(r.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,r)}var lE=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var Eke=512,cv="\0",J9=3600*1e3,pke=3e3,Jn;(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"})(Jn||(Jn={}));var q9=new Set([Jn.SignalErrorInvalidMessage,Jn.SignalErrorBadMac]),AS=class{constructor(r,o){this.logger=r,this.recentMessagesMap=new Mn({max:Eke,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(cv);if(a>-1){let A=e.slice(a+cv.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Mn({ttl:J9*2,ttlAutopurge:!0}),this.retryCounters=new Mn({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Mn({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(r,o,i){let e={to:r,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: ${r}/${o}`)}getRecentMessage(r,o){let i={to:r,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(r,o,i){if(!o)return this.sessionRecreateHistory.set(r,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&q9.has(i))return this.sessionRecreateHistory.set(r,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:r,errorCode:Jn[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${Jn[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(r);return!a||e-a>J9?(this.sessionRecreateHistory.set(r,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(r){if(r===void 0||r==="")return;let o=parseInt(r,10);if(!Number.isNaN(o))return o>=Jn.UnknownError&&o<=Jn.StatusRevokeDelay?o:Jn.UnknownError}isMacError(r){return r!==void 0&&q9.has(r)}incrementRetryCount(r){return this.retryCounters.set(r,(this.retryCounters.get(r)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(r)}getRetryCount(r){return this.retryCounters.get(r)||0}hasExceededMaxRetries(r){return this.getRetryCount(r)>=this.maxMsgRetryCount}markRetrySuccess(r){this.statistics.successfulRetries++,this.retryCounters.delete(r),this.cancelPendingPhoneRequest(r),this.removeRecentMessage(r)}markRetryFailed(r){this.statistics.failedRetries++,this.retryCounters.delete(r),this.cancelPendingPhoneRequest(r),this.removeRecentMessage(r)}schedulePhoneRequest(r,o,i=pke){this.cancelPendingPhoneRequest(r),this.pendingPhoneRequests[r]=setTimeout(()=>{delete this.pendingPhoneRequests[r],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${r} with ${i}ms delay`)}cancelPendingPhoneRequest(r){let o=this.pendingPhoneRequests[r];o&&(clearTimeout(o),delete this.pendingPhoneRequests[r],this.logger.debug(`Cancelled pending phone request for message ${r}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let r of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(r);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(r,o,i){this.baseKeys.set(`${r}:${o}`,i)}hasSameBaseKey(r,o,i){let e=this.baseKeys.get(`${r}:${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=>[dke[Cke()]||"Ubuntu",n,hke()]};var ao;(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"})(ao||(ao={}));var uke={Chrome:ao.CHROME,Edge:ao.EDGE,Firefox:ao.FIREFOX,IE:ao.IE,Opera:ao.OPERA,Safari:ao.SAFARI},Bke=([n,r])=>r==="Desktop"?n==="Windows"?ao.UWP:ao.ELECTRON:uke[r]||ao.OTHER_WEB_CLIENT,Iv=n=>Bke(n).toString(),V9=(n,r,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,r,o,i,Iv(e)].join(",");async function z9(n,r){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!ie(n,"identity"))return{action:"no_identity_node"};r.logger.info({jid:o},"identity changed");let e=lA(o);if(e?.device&&e.device!==0)return r.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(r.meId&&(lt(o,r.meId)||r.meLid&<(o,r.meLid)))return r.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(r.debounceCache.get(o))return r.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};r.debounceCache.set(o,!0);let A=!Tq(n.attrs.offline);if(!(await r.validateSession(o)).exists)return r.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(r.logger.debug({jid:o},"old session exists, will refresh session"),A)return r.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};r.onBeforeSessionRefresh?.(o);try{return await r.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return r.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function W9(n,r,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return r&&(a.attrs.error=r.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 Qke(n){return n===null||n===""}function fke(n){return n>2147483647||n<-2147483648?n&4294967295:n}function Z9(n){let r=0;if(!Qke(n))for(let o=0;oo.iteration===r)}addSenderMessageKey(r){this.senderKeyStateStructure.senderMessageKeys.push({iteration:r.getIteration(),seed:r.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(r){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===r);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new Pc(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var qn=class n{constructor(r){if(this.MAX_STATES=5,this.senderKeyStates=[],r)for(let o of r)this.senderKeyStates.push(new Gc(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(r){return r===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===r)}addSenderKeyState(r,o,i,e){this.senderKeyStates.push(new Gc(r,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(r,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new Gc(r,o,i,e))}serialize(){return this.senderKeyStates.map(r=>r.getStructure())}static deserialize(r){let o=Buffer.from(r).toString("utf-8"),i=JSON.parse(o,WC.reviver);return new n(i)}};var eX=Le(Os(),1);import*as rS from"crypto";function AX(){return rS.randomBytes(32)}function tX(){return rS.randomInt(2147483647)}function rX(n){return n||(n=(0,eX.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var Fc=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 Lc=class extends Fc{constructor(r,o,i,e,a){if(super(),a)try{let A=a.slice(1),t=Ae.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=t.id,this.iteration=t.iteration,this.chainKey=typeof t.chainKey=="string"?Buffer.from(t.chainKey,"base64"):t.chainKey,this.signatureKey=typeof t.signingKey=="string"?Buffer.from(t.signingKey,"base64"):t.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=r,this.iteration=o,this.chainKey=i,this.signatureKey=e;let t=Ae.SenderKeyDistributionMessage.encode(Ae.SenderKeyDistributionMessage.create({id:r,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),t])}}intsToByteHighAndLow(r,o){return((r<<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 EE=class{constructor(r){this.senderKeyStore=r}async process(r,o){let i=await this.senderKeyStore.loadSenderKey(r);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(r,i)}async create(r){let o=await this.senderKeyStore.loadSenderKey(r);if(o.isEmpty()){let e=tX(),a=AX(),A=rX();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(r,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new Lc(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var iS=Le(ac(),1);var aS=Le(Os(),1);var pE=class extends Fc{constructor(r,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],t=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=Ae.SenderKeyMessage.decode(t).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,t=Buffer.from(i),s=Ae.SenderKeyMessage.encode(Ae.SenderKeyMessage.create({id:r,iteration:o,ciphertext:t})).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=r,this.iteration=o,this.ciphertext=t,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(r){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,aS.verifySignature)(r,o,i))throw new Error("Invalid signature!")}getSignature(r,o){return Buffer.from((0,aS.calculateSignature)(r,o))}serialize(){return this.serialized}getType(){return 4}};var CE=class{constructor(r,o){this.senderKeyStore=r,this.senderKeyName=o}async encrypt(r){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(),r),t=new pE(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),t.serialize()}async decrypt(r){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new pE(null,null,null,null,r),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(r,o){let i=r.getSenderChainKey();if(i.getIteration()>o){if(r.hasSenderMessageKey(o)){let e=r.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 t=[...i];this.logger.trace(`Batch fetching ${t.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",t);for(let g of t){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:t,lidUser:s}of o){if(e.get(t)===s){this.logger.debug({pnUser:t,lidUser:s},"LID mapping already exists, skipping");continue}a[t]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[t,s]of Object.entries(a))A[t]=s,A[`${s}_reverse`]=t;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[t,s]of Object.entries(a))this.mappingCache.set(`pn:${t}`,s),this.mappingCache.set(`lid:${s}`,t)}async getLIDForPN(r){return(await this.getLIDsForPNs([r]))?.[0]?.lid||null}async getLIDsForPNs(r){if(r.length===0)return null;let o=[...new Set(r)].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(r);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(r){let o={},i={},e=[],a=(A,t,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=t.device!==void 0?t.device:0,l=`${g}${c?`:${c}`:""}@${t.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${l} (user mapping with device ${c})`),i[A]={lid:l,pn:A},!0};for(let A of r){if(!nt(A)&&!Lt(A))continue;let t=lA(A);if(!t)continue;let s=t.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,t,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:t})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],t=await this.keys.get("lid-mapping",A);for(let s of A){let g=t[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 l=this.mappingCache.get(`pn:${g}`);if(l&&typeof l=="string"){if(!a(s,c,l)){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 p=c.device||0,B=oA(s);Lt(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(p):o[B]=[p]}}}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 t of A){let g=lA(t.pn)?.user;if(!g)continue;let c=lA(t.lid)?.user;if(c)for(let l of o[t.pn]){let p=`${c}${l?`:${l}`:""}@${l===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${t.pn} \u2192 ${p} (user mapping with device ${l})`);let B=`${g}${l?`:${l}`:""}@${l===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:p,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(r){return(await this.getPNsForLIDs([r]))?.[0]?.pn||null}async getPNsForLIDs(r){if(r.length===0)return null;let o=[...new Set(r)].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(r);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(r){let o={},i=[],e=(a,A,t)=>{if(!t||typeof t!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${t}:${s}@${A.domainType===ut.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 r){if(!vA(a))continue;let A=lA(a);if(!A)continue;let t=A.user,s=this.mappingCache.get(`lid:${t}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:t,decoded:A})}if(i.length){let a=[...new Set(i.map(t=>`${t.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:t,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(t,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 yke(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=iX.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function oX(n,r,o){let i=new oS(n.keys,r,o),e=mke(n,i),a=n.keys,A=new Mn({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),t=async(g,c)=>{let l=nS(g,c),p=l.toString(),{[p]:B}=await n.keys.get("sender-key",[p]);B||await e.storeSenderKey(l,new qn);let Q=await new EE(e).create(l);return{senderName:l,skdm:Q}};return{decryptGroupMessage({group:g,authorJid:c,msg:l}){let p=nS(g,c),B=new CE(e,p);return a.transaction(async()=>B.decrypt(l),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let l=new EE(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let p=nS(g.groupId,c),B=new Lc(null,null,null,null,g.axolotlSenderKeyDistributionMessage),Q=p.toString(),{[Q]:f}=await n.keys.get("sender-key",[Q]);return f||await e.storeSenderKey(p,new qn),a.transaction(async()=>{let{[Q]:y}=await n.keys.get("sender-key",[Q]);y||await e.storeSenderKey(p,new qn),await l.process(p,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:l}){let p=io(g),B=new Xo.SessionCipher(e,p);if(c==="pkmsg"){let f=yke(l);if(f){let y=p.toString();await e.saveIdentity(y,f)&&r.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function Q(){let f;switch(c){case"pkmsg":f=await B.decryptPreKeyWhisperMessage(l);break;case"msg":f=await B.decryptWhisperMessage(l);break}return f}return a.transaction(async()=>await Q(),g)},async encryptMessage({jid:g,data:c}){let l=io(g),p=new Xo.SessionCipher(e,l);return a.transaction(async()=>{let{type:B,body:Q}=await p.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(Q,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:l}){return a.transaction(async()=>{let{senderName:p,skdm:B}=await t(g,c);return{ciphertext:await new CE(e,p).encrypt(l),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:l}=await t(g,c);return l.serialize()},g)},async hasSenderKey({group:g,meId:c}){let l=nS(g,c).toString(),{[l]:p}=await n.keys.get("sender-key",[l]);return!!p},async getSessionInfo(g){let c=io(g).toString(),l=await e.loadSession(c);if(!l)return null;let p=l.getOpenSession?.(),B=p?.indexInfo?.baseKey,Q=p?.registrationId;return!B||typeof Q!="number"?null:{baseKey:new Uint8Array(B),registrationId:Q}},async injectE2ESession({jid:g,session:c}){r.trace({jid:g},"injecting E2EE session");let l=new Xo.SessionBuilder(e,io(g));return a.transaction(async()=>{await l.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return io(g).toString()},lidMapping:i,async validateSession(g){try{let c=io(g),l=await e.loadSession(c.toString());return l?l.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(l=>{let p=io(l);c[p.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||!vA(c)&&!yr(c))return{migrated:0,skipped:0,total:0};if(!nt(g)&&!Lt(g))return{migrated:0,skipped:0,total:1};let{user:l}=lA(g);r.debug({fromJid:g},"bulk device migration - loading all user devices");let{[l]:p}=await a.get("device-list",[l]);if(!p)return{migrated:0,skipped:0,total:0};let{device:B}=lA(g),Q=B?.toString()||"0";p.includes(Q)||p.push(Q);let y=p.filter(k=>{let G=`${l}.${k}`;return!A.has(G)}).map(k=>`${l}.${k}`),m=await a.get("session",y),R=[];for(let[k,G]of Object.entries(m))if(G){let K=k.split(".")[1];if(!K)continue;let x=parseInt(K),H=x===0?`${l}@s.whatsapp.net`:`${l}:${x}@s.whatsapp.net`;x===99&&(H=`${l}:99@hosted`),R.push(H)}return r.debug({fromJid:g,totalDevices:p.length,devicesWithSessions:R.length,devices:R},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let k=R.map(F=>{let T=Aq(F,c),V=lA(F),U=lA(T);return{fromJid:F,toJid:T,pnUser:V.user,lidUser:U.user,deviceId:V.device||0,fromAddr:io(F),toAddr:io(T)}}),G=k.length,K=0,x=Array.from(new Set(k.map(F=>F.fromAddr.toString()))),H=await a.get("session",x),q={};for(let F of k){let T=F.fromAddr.toString(),V=F.toAddr.toString(),U=H[T];if(U){let b=Xo.SessionRecord.deserialize(U);b.haveOpenSession()&&(q[V]=b.serialize(),q[T]=null,K++)}}if(Object.keys(q).length>0){await a.set({session:q}),r.debug({migratedSessions:K},"bulk session migration complete");for(let F of k)if(q[F.toAddr.toString()]){let T=`${F.pnUser}.${F.deviceId}`;A.set(T,!0)}}let j=G-K;return{migrated:K,skipped:j,total:G}},`migrate-${R.length}-sessions-${lA(c)?.user}`)}}}var io=n=>{let r=lA(n),{user:o,device:i,server:e,domainType:a}=r;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==ut.WHATSAPP?`${o}_${a}`:o,t=i||0;if(i===99&&r.server!=="hosted"&&r.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new Xo.ProtocolAddress(A,t)},nS=(n,r)=>new td(n,io(r));function mke({creds:n,keys:r},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[t,s]=a.split("_"),g=parseInt(s||"0");if(g===ut.LID||g===ut.HOSTED_LID)return e;let c=`${t}${A!=="0"?`:${A}`:""}@${g===ut.HOSTED?"hosted":"s.whatsapp.net"}`,l=await o.getLIDForPN(c);if(l)return io(l).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await r.get("session",[a]);if(A)return Xo.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await r.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await r.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:t}=await r.get("identity-key",[A]),s=t?.length===a.length&&t.every((g,c)=>g===a[c]);return t&&!s?(await r.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):t?!1:(await r.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await r.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>r.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 r.get("sender-key",[a]);return A?qn.deserialize(A):new qn},storeSenderKey:async(e,a)=>{let A=e.toString(),t=JSON.stringify(a.serialize());await r.set({"sender-key":{[A]:Buffer.from(t,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from(di(e.public))}}}}var s$=Le(n$(),1),sd=(0,s$.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var XFe=[2,3e3,1043857760];var jh="https://web.whatsapp.com",jZ="https://call.whatsapp.com/video/",JZ="https://call.whatsapp.com/voice/",QE="CB:",g$="TAG:";var i9=Buffer.from([6,0]),o9=Buffer.from([6,1]),Pk=Buffer.from([6,5]),agA=Buffer.from([6,6]),Vh=10080*60,c$=1440*60,I$=336*60*60,I9="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",$Fe=3,Tn=Buffer.from([5]),l$=Buffer.from([87,65,6,$Fe]),qZ=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,Fk={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},gd=[Ae.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,Ae.HistorySync.HistorySyncType.PUSH_NAME,Ae.HistorySync.HistorySyncType.RECENT,Ae.HistorySync.HistorySyncType.FULL,Ae.HistorySync.HistorySyncType.ON_DEMAND,Ae.HistorySync.HistorySyncType.NON_BLOCKING_DATA,Ae.HistorySync.HistorySyncType.INITIAL_STATUS_V3],ng={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},E$={version:XFe,browser:tS.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:sd.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!==Ae.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:oX},Ok={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"},RZ={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"},VZ=Object.keys(Ok),p$=12e4,cd=5,C$=812,h$=3e4,aP={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var d$=Le(ar(),1);import{createHash as eLe}from"crypto";import{createWriteStream as ALe,promises as tLe}from"fs";import{tmpdir as rLe}from"os";import{join as aLe}from"path";var u$=n=>{let r=ie(n,"product_catalog"),o=mA(r,"product").map(Id),i=ie(r,"paging");return{products:o,nextPageCursor:i?RA(i,"after"):void 0}},B$=n=>{let r=ie(n,"collections");return{collections:mA(r,"collection").map(i=>{let e=RA(i,"id"),a=RA(i,"name"),A=mA(i,"product").map(Id);return{id:e,name:a,products:A,status:nLe(i)}})}},Q$=n=>{let r=ie(n,"order"),o=mA(r,"product").map(a=>{let A=ie(a,"image");return{id:RA(a,"id"),name:RA(a,"name"),imageUrl:RA(A,"url"),price:+RA(a,"price"),currency:RA(a,"currency"),quantity:+RA(a,"quantity")}}),i=ie(r,"price");return{price:{total:+RA(i,"total"),currency:RA(i,"currency")},products:o}},iP=(n,r)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof r.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(r.name)}),typeof r.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(r.description)}),typeof r.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(r.retailerId)}),r.images.length&&i.push({tag:"media",attrs:{},content:r.images.map(a=>{if(!("url"in a))throw new d$.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 r.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(r.price.toString())}),typeof r.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(r.currency)}),"originCountryCode"in r&&(typeof r.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(r.originCountryCode)}]})),typeof r.isHidden<"u"&&(o.is_hidden=r.isHidden.toString()),{tag:"product",attrs:o,content:i}},Id=n=>{let r=n.attrs.is_hidden==="true",o=RA(n,"id"),i=ie(n,"media"),e=ie(n,"status_info");return{id:o,imageUrls:oLe(i),reviewStatus:{whatsapp:RA(e,"status")},availability:"in stock",name:RA(n,"name"),retailerId:RA(n,"retailer_id"),url:RA(n,"url"),description:RA(n,"description"),price:+RA(n,"price"),currency:RA(n,"currency"),isHidden:r}};async function oP(n,r,o=3e4){return n={...n,images:n.images?await iLe(n.images,r,o):n.images},n}var iLe=async(n,r,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let l=e.url.toString();if(l.includes(".whatsapp.net"))return{url:l}}let{stream:a}=await Yh(e),A=eLe("sha256"),t=aLe(rLe(),"img"+nr()),s=ALe(t);for await(let l of a)A.update(l),s.write(l);let g=A.digest("base64"),{directPath:c}=await r(t,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await tLe.unlink(t).catch(l=>console.log("Error deleting temp file ",l)),{url:xh(c)}})),oLe=n=>{let r=ie(n,"image");return{requested:RA(r,"request_image_url"),original:RA(r,"original_image_url")}},nLe=n=>{let r=ie(n,"status_info");return{status:RA(r,"status"),canAppeal:RA(r,"can_appeal")==="true"}};var Ed=Le(ar(),1);import{randomBytes as lP}from"crypto";var Ni=null;try{Ni=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 ct(n,r,o){this.low=n|0,this.high=r|0,this.unsigned=!!o}ct.prototype.__isLong__;Object.defineProperty(ct.prototype,"__isLong__",{value:!0});function ra(n){return(n&&n.__isLong__)===!0}function f$(n){var r=Math.clz32(n&-n);return n?31-r:r}ct.isLong=ra;var y$={},m$={};function xc(n,r){var o,i,e;return r?(n>>>=0,(e=0<=n&&n<256)&&(i=m$[n],i)?i:(o=tt(n,0,!0),e&&(m$[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=y$[n],i)?i:(o=tt(n,n<0?-1:0,!1),e&&(y$[n]=o),o))}ct.fromInt=xc;function Ti(n,r){if(isNaN(n))return r?Vn:so;if(r){if(n<0)return Vn;if(n>=O$)return _$}else{if(n<=-D$)return Ra;if(n+1>=D$)return b$}return n<0?Ti(-n,r).neg():tt(n%yE|0,n/yE|0,r)}ct.fromNumber=Ti;function tt(n,r,o){return new ct(n,r,o)}ct.fromBits=tt;var bS=Math.pow;function sP(n,r,o){if(n.length===0)throw Error("empty string");if(typeof r=="number"?(o=r,r=!1):r=!!r,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return r?Vn:so;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return sP(n.substring(1),r,o).neg();for(var e=Ti(bS(o,8)),a=so,A=0;A>>0:this.low};be.toNumber=function(){return this.unsigned?(this.high>>>0)*yE+(this.low>>>0):this.high*yE+(this.low>>>0)};be.toString=function(r){if(r=r||10,r<2||36>>0,c=g.toString(r);if(A=s,A.isZero())return c+t;for(;c.length<6;)c="0"+c;t=""+c+t}};be.getHighBits=function(){return this.high};be.getHighBitsUnsigned=function(){return this.high>>>0};be.getLowBits=function(){return this.low};be.getLowBitsUnsigned=function(){return this.low>>>0};be.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ra)?64:this.neg().getNumBitsAbs();for(var r=this.high!=0?this.high:this.low,o=31;o>0&&(r&1<>21;return r?this.unsigned?!1:r===-1&&!(this.low===0&&this.high===-2097152):!0};be.isZero=function(){return this.high===0&&this.low===0};be.eqz=be.isZero;be.isNegative=function(){return!this.unsigned&&this.high<0};be.isPositive=function(){return this.unsigned||this.high>=0};be.isOdd=function(){return(this.low&1)===1};be.isEven=function(){return(this.low&1)===0};be.equals=function(r){return ra(r)||(r=Ri(r)),this.unsigned!==r.unsigned&&this.high>>>31===1&&r.high>>>31===1?!1:this.high===r.high&&this.low===r.low};be.eq=be.equals;be.notEquals=function(r){return!this.eq(r)};be.neq=be.notEquals;be.ne=be.notEquals;be.lessThan=function(r){return this.comp(r)<0};be.lt=be.lessThan;be.lessThanOrEqual=function(r){return this.comp(r)<=0};be.lte=be.lessThanOrEqual;be.le=be.lessThanOrEqual;be.greaterThan=function(r){return this.comp(r)>0};be.gt=be.greaterThan;be.greaterThanOrEqual=function(r){return this.comp(r)>=0};be.gte=be.greaterThanOrEqual;be.ge=be.greaterThanOrEqual;be.compare=function(r){if(ra(r)||(r=Ri(r)),this.eq(r))return 0;var o=this.isNegative(),i=r.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?r.high>>>0>this.high>>>0||r.high===this.high&&r.low>>>0>this.low>>>0?-1:1:this.sub(r).isNegative()?-1:1};be.comp=be.compare;be.negate=function(){return!this.unsigned&&this.eq(Ra)?Ra:this.not().add(fE)};be.neg=be.negate;be.add=function(r){ra(r)||(r=Ri(r));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=r.high>>>16,t=r.high&65535,s=r.low>>>16,g=r.low&65535,c=0,l=0,p=0,B=0;return B+=a+g,p+=B>>>16,B&=65535,p+=e+s,l+=p>>>16,p&=65535,l+=i+t,c+=l>>>16,l&=65535,c+=o+A,c&=65535,tt(p<<16|B,c<<16|l,this.unsigned)};be.subtract=function(r){return ra(r)||(r=Ri(r)),this.add(r.neg())};be.sub=be.subtract;be.multiply=function(r){if(this.isZero())return this;if(ra(r)||(r=Ri(r)),Ni){var o=Ni.mul(this.low,this.high,r.low,r.high);return tt(o,Ni.get_high(),this.unsigned)}if(r.isZero())return this.unsigned?Vn:so;if(this.eq(Ra))return r.isOdd()?Ra:so;if(r.eq(Ra))return this.isOdd()?Ra:so;if(this.isNegative())return r.isNegative()?this.neg().mul(r.neg()):this.neg().mul(r).neg();if(r.isNegative())return this.mul(r.neg()).neg();if(this.lt(w$)&&r.lt(w$))return Ti(this.toNumber()*r.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,t=r.high>>>16,s=r.high&65535,g=r.low>>>16,c=r.low&65535,l=0,p=0,B=0,Q=0;return Q+=A*c,B+=Q>>>16,Q&=65535,B+=a*c,p+=B>>>16,B&=65535,B+=A*g,p+=B>>>16,B&=65535,p+=e*c,l+=p>>>16,p&=65535,p+=a*g,l+=p>>>16,p&=65535,p+=A*s,l+=p>>>16,p&=65535,l+=i*c+e*g+a*s+A*t,l&=65535,tt(B<<16|Q,l<<16|p,this.unsigned)};be.mul=be.multiply;be.divide=function(r){if(ra(r)||(r=Ri(r)),r.isZero())throw Error("division by zero");if(Ni){if(!this.unsigned&&this.high===-2147483648&&r.low===-1&&r.high===-1)return this;var o=(this.unsigned?Ni.div_u:Ni.div_s)(this.low,this.high,r.low,r.high);return tt(o,Ni.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Vn:so;var i,e,a;if(this.unsigned){if(r.unsigned||(r=r.toUnsigned()),r.gt(this))return Vn;if(r.gt(this.shru(1)))return M$;a=Vn}else{if(this.eq(Ra)){if(r.eq(fE)||r.eq(nP))return Ra;if(r.eq(Ra))return fE;var A=this.shr(1);return i=A.div(r).shl(1),i.eq(so)?r.isNegative()?fE:nP:(e=this.sub(r.mul(i)),a=i.add(e.div(r)),a)}else if(r.eq(Ra))return this.unsigned?Vn:so;if(this.isNegative())return r.isNegative()?this.neg().div(r.neg()):this.neg().div(r).neg();if(r.isNegative())return this.div(r.neg()).neg();a=so}for(e=this;e.gte(r);){i=Math.max(1,Math.floor(e.toNumber()/r.toNumber()));for(var t=Math.ceil(Math.log(i)/Math.LN2),s=t<=48?1:bS(2,t-48),g=Ti(i),c=g.mul(r);c.isNegative()||c.gt(e);)i-=s,g=Ti(i,this.unsigned),c=g.mul(r);g.isZero()&&(g=fE),a=a.add(g),e=e.sub(c)}return a};be.div=be.divide;be.modulo=function(r){if(ra(r)||(r=Ri(r)),Ni){var o=(this.unsigned?Ni.rem_u:Ni.rem_s)(this.low,this.high,r.low,r.high);return tt(o,Ni.get_high(),this.unsigned)}return this.sub(this.div(r).mul(r))};be.mod=be.modulo;be.rem=be.modulo;be.not=function(){return tt(~this.low,~this.high,this.unsigned)};be.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};be.clz=be.countLeadingZeros;be.countTrailingZeros=function(){return this.low?f$(this.low):f$(this.high)+32};be.ctz=be.countTrailingZeros;be.and=function(r){return ra(r)||(r=Ri(r)),tt(this.low&r.low,this.high&r.high,this.unsigned)};be.or=function(r){return ra(r)||(r=Ri(r)),tt(this.low|r.low,this.high|r.high,this.unsigned)};be.xor=function(r){return ra(r)||(r=Ri(r)),tt(this.low^r.low,this.high^r.high,this.unsigned)};be.shiftLeft=function(r){return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r<32?tt(this.low<>>32-r,this.unsigned):tt(0,this.low<>>r|this.high<<32-r,this.high>>r,this.unsigned):tt(this.high>>r-32,this.high>=0?0:-1,this.unsigned)};be.shr=be.shiftRight;be.shiftRightUnsigned=function(r){return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r<32?tt(this.low>>>r|this.high<<32-r,this.high>>>r,this.unsigned):r===32?tt(this.high,0,this.unsigned):tt(this.high>>>r-32,0,this.unsigned)};be.shru=be.shiftRightUnsigned;be.shr_u=be.shiftRightUnsigned;be.rotateLeft=function(r){var o;return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r===32?tt(this.high,this.low,this.unsigned):r<32?(o=32-r,tt(this.low<>>o,this.high<>>o,this.unsigned)):(r-=32,o=32-r,tt(this.high<>>o,this.low<>>o,this.unsigned))};be.rotl=be.rotateLeft;be.rotateRight=function(r){var o;return ra(r)&&(r=r.toInt()),(r&=63)===0?this:r===32?tt(this.high,this.low,this.unsigned):r<32?(o=32-r,tt(this.high<>>r,this.low<>>r,this.unsigned)):(r-=32,o=32-r,tt(this.low<>>r,this.high<>>r,this.unsigned))};be.rotr=be.rotateRight;be.toSigned=function(){return this.unsigned?tt(this.low,this.high,!1):this};be.toUnsigned=function(){return this.unsigned?this:tt(this.low,this.high,!0)};be.toBytes=function(r){return r?this.toBytesLE():this.toBytesBE()};be.toBytesLE=function(){var r=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,r&255,r>>>8&255,r>>>16&255,r>>>24]};be.toBytesBE=function(){var r=this.high,o=this.low;return[r>>>24,r>>>16&255,r>>>8&255,r&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};ct.fromBytes=function(r,o,i){return i?ct.fromBytesLE(r,o):ct.fromBytesBE(r,o)};ct.fromBytesLE=function(r,o){return new ct(r[0]|r[1]<<8|r[2]<<16|r[3]<<24,r[4]|r[5]<<8|r[6]<<16|r[7]<<24,o)};ct.fromBytesBE=function(r,o){return new ct(r[4]<<24|r[5]<<16|r[6]<<8|r[7],r[0]<<24|r[1]<<16|r[2]<<8|r[3],o)};typeof BigInt=="function"&&(ct.fromBigInt=function(r,o){var i=Number(BigInt.asIntN(32,r)),e=Number(BigInt.asIntN(32,r>>BigInt(32)));return tt(i,e,o)},ct.fromValue=function(r,o){return typeof r=="bigint"?ct.fromBigInt(r,o):Ri(r,o)},be.toBigInt=function(){var r=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new jn;return{mutex(r){return n.runExclusive(r)}}},N$=()=>{let n=new Map;return{async mutex(r,o){let i=n.get(r);i||(i={mutex:new jn,refCount:0},n.set(r,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(r)===i&&n.delete(r)}}}};function T$(n,r,o=10){let i=[],e=!1;return{enqueue:(A,t)=>{if(i.push({type:A,node:t}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&r.isWsOpen();){let{type:c,node:l}=i.shift(),p=n.get(c);if(!p){r.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await p(l).catch(B=>r.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await r.yieldToEventLoop())}e=!1})().catch(g=>r.onUnexpectedError(g,"processing offline nodes"))}}}var US=Le(ar(),1);var cg=Le(ar(),1);var _S=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(r){let o=[],i;if(r.tag==="devices"){Oa(r);let e=ie(r,"device-list"),a=ie(r,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:t}of e.content){let s=+t.id,g=+t["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(t.is_hosted&&t.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 An=class{withId(r){return this.id=r,this}withLid(r){return this.lid=r,this}withPhone(r){return this.phone=r,this}withUsername(r){return this.username=r,this}withUsernameKey(r){return this.usernameKey=r,this}withType(r){return this.type=r,this}withPersonaId(r){return this.personaId=r,this}};var NS=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(r){return r.phone?{tag:"contact",attrs:{},content:r.phone}:r.username?{tag:"contact",attrs:{username:r.username,...r.usernameKey?{pin:r.usernameKey}:{},...r.lid?{lid:r.lid}:{}}}:r.type?{tag:"contact",attrs:{type:r.type}}:{tag:"contact",attrs:{}}}parser(r){return r.tag==="contact"?(Oa(r),r?.attrs?.type==="in"):!1}};var TS=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(r){if(r.tag==="status"){Oa(r);let o=r?.content?.toString()??null,i=new Date(+(r?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):r.attrs?.code&&+r.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var RS=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(r){if(r.tag==="disappearing_mode"){Oa(r);let o=+r?.attrs.duration,i=new Date(+(r?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var kS=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(r){return null}parser(r){return r.tag==="username"?(Oa(r),typeof r.content=="string"?r.content:null):null}};var vS=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(r){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:r.personaId}}]}}parser(r){let o=ie(r,"bot"),i=ie(o,"profile"),e=ie(i,"commands"),a=ie(i,"prompts"),A=[],t=[];for(let s of mA(e,"command"))A.push({name:RA(s,"name"),description:RA(s,"description")});for(let s of mA(a,"prompt"))t.push(`${RA(s,"emoji")} ${RA(s,"text")}`);return{isDefault:!!ie(i,"default"),jid:r.attrs.jid,name:RA(i,"name"),attributes:RA(i,"attributes"),description:RA(i,"description"),category:RA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:RA(e,"description"),commands:A,prompts:t}}};var PS=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(r){return r.lid?{tag:"lid",attrs:{jid:r.lid}}:null}parser(r){return r.tag==="lid"?r.attrs.val:null}};var tn=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(r){return this.mode=r,this}withContext(r){return this.context=r,this}withUser(r){return this.users.push(r),this}parseUSyncQueryResult(r){if(r?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=ie(r,"usync"),a=e?ie(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,t)=>{let s=t?.attrs.jid;if(s){let g=Array.isArray(t?.content)?Object.fromEntries(t.content.map(c=>{let l=c.tag,p=o[l];return p?[l,p(c)]:[l,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new _S),this}withContactProtocol(){return this.protocols.push(new NS),this}withStatusProtocol(){return this.protocols.push(new TS),this}withDisappearingModeProtocol(){return this.protocols.push(new RS),this}withBotProfileProtocol(){return this.protocols.push(new vS),this}withLIDProtocol(){return this.protocols.push(new PS),this}withUsernameProtocol(){return this.protocols.push(new kS),this}};var lr=Le(ar(),1);import{randomBytes as cP}from"crypto";import{URL as ILe}from"url";import{promisify as lLe}from"util";var GS=class{constructor(r={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,r)}};import{EventEmitter as gLe}from"events";var FS=class extends gLe{constructor(r,o){super(),this.url=r,this.config=o,this.setMaxListeners(0)}};var LS=class extends FS{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===Hi.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===Hi.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===Hi.CLOSING}get isConnecting(){return this.socket?.readyState===Hi.CONNECTING}connect(){if(this.socket)return;this.socket=new Hi(this.url,{origin:jh,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let r=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of r)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let r=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await r,this.socket=null}send(r,o){return this.socket?.send(r,o),!!this.socket}};var gP=Le(ar(),1);var cLe=(n,r,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:uA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:r},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),ld=async(n,r,o,i,e)=>{let a=await cLe(n,r,i,e),A=ie(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(", "),l=s.errors[0],p=l.extensions?.error_code||400;throw new gP.Boom(`GraphQL server error: ${c}`,{statusCode:p,data:l})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let t=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new gP.Boom(`Failed to ${t}, unexpected response structure.`,{statusCode:400,data:a})};var R$=n=>{let{waWebSocketUrl:r,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:t,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:l}=n,p=new GS,B=0,Q=Fq(),f=()=>`${Q}${Se++}`;t&&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."),gd.map(oe=>n.shouldSyncHistoryMessage({syncType:oe})).filter(oe=>oe===!1).length===gd.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 r=="string"?new ILe(r):r;if(n.mobile||m.protocol==="tcp:")throw new lr.Boom("Mobile API is not supported anymore",{statusCode:yt.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let R=Ut.generateKeyPair(),k=c9({keyPair:R,NOISE_HEADER:l$,logger:i,routingInfo:A?.creds?.routingInfo}),G=new LS(m,n);G.connect();let K=lLe(G.send),x=async oe=>{if(!G.isOpen)throw new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed});let le=k.encodeFrame(oe);await dl(o,async(Be,eA)=>{try{await K.call(G,le),Be()}catch(IA){eA(IA)}})},H=oe=>{i.level==="trace"&&i.trace({xml:Zi(oe),msg:"xml send"});let le=tq(oe);return x(le)},q=async(oe,le=s)=>{let Be,eA;try{return await dl(le,(TA,wt)=>(Be=WA=>{TA(WA)},eA=WA=>{wt(WA||new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed}))},G.on(`TAG:${oe}`,Be),G.on("close",eA),G.on("error",eA),()=>wt(new lr.Boom("Query Cancelled"))))}catch(IA){if(IA instanceof lr.Boom&&IA.output?.statusCode===yt.timedOut){i?.warn?.({msgId:oe},"timed out waiting for message");return}throw IA}finally{Be&&G.off(`TAG:${oe}`,Be),eA&&(G.off("close",eA),G.off("error",eA))}},j=async(oe,le)=>{oe.attrs.id||(oe.attrs.id=f());let Be=oe.attrs.id,eA=await dl(le,async(IA,TA)=>{let wt=q(Be,le).catch(TA);H(oe).then(async()=>IA(await wt)).catch(TA)});return eA&&"tag"in eA&&Oa(eA),eA},F=async()=>{let oe=await j({tag:"iq",attrs:{to:uA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!ie(oe,"digest"))throw await Ye(),new Error("encrypt/get digest returned no digest node")},T=async()=>{let oe=(X.signedPreKey.keyId||0)+1,le=await Ff(X.signedIdentityKey,oe);await j({tag:"iq",attrs:{to:uA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[zh(le)]}]}),L.emit("creds.update",{signedPreKey:le})},V=async oe=>{if(oe.protocols.length===0)throw new lr.Boom("USyncQuery must have at least one protocol");let Be=oe.users.map(WA=>({tag:"user",attrs:{jid:WA.phone?void 0:WA.id},content:oe.protocols.map(Er=>Er.getUserElement(WA)).filter(Er=>Er!==null)})),eA={tag:"list",attrs:{},content:Be},IA={tag:"query",attrs:{},content:oe.protocols.map(WA=>WA.getQueryElement())},TA={tag:"iq",attrs:{to:uA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:oe.context,mode:oe.mode,sid:f(),last:"true",index:"0"},content:[IA,eA]}]},wt=await j(TA);return oe.parseUSyncQueryResult(wt)},U=async(...oe)=>{let le=new tn,Be=!1;for(let IA of oe)if(vA(IA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{Be||(Be=!0,le=le.withContactProtocol());let TA=`+${IA.replace("+","").split("@")[0]?.split(":")[0]}`;le.withUser(new An().withPhone(TA))}if(le.users.length===0)return[];let eA=await V(le);if(eA)return eA.list.filter(IA=>!!IA.contact).map(({contact:IA,id:TA})=>({jid:TA,exists:IA}))},b=async oe=>{let le=new tn().withLIDProtocol().withContext("background");for(let eA of oe)if(vA(eA)){i?.warn("LID user found in LID fetch call");continue}else le.withUser(new An().withId(eA));if(le.users.length===0)return[];let Be=await V(le);return Be?Be.list.filter(eA=>!!eA.lid).map(({lid:eA,id:IA})=>({pn:IA,lid:eA})):[]},L=j9(i),{creds:X}=A,pe=P9(A.keys,i,g),me=l({creds:X,keys:pe},i,b),qe,Se=1,Ge,je,Xe=!1,rA=[],nA=(oe,le)=>{i.error({err:oe},`unexpected error in '${le}'`)},Fe=async oe=>{if(!G.isOpen)throw new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed});let le,Be,eA=dl(o,(IA,TA)=>{le=IA,Be=IP(TA),G.on("frame",le),G.on("close",Be),G.on("error",Be)}).finally(()=>{G.off("frame",le),G.off("close",Be),G.off("error",Be)});return oe&&x(oe).catch(Be),eA},hA=async()=>{let oe={clientHello:{ephemeral:R.public}};oe=Ae.HandshakeMessage.fromObject(oe),i.info({browser:a,helloMsg:oe},"connected to WA");let le=Ae.HandshakeMessage.encode(oe).finish(),Be=await Fe(le),eA=Ae.HandshakeMessage.decode(Be);i.trace({handshake:eA},"handshake recv from WA");let IA=k.processHandshake(eA,X.noiseKey),TA;X.me?(TA=t9(X.me.id,n),i.info({node:TA},"logging in...")):(TA=r9(X,n),i.info({node:TA},"not logged in, attempting registration..."));let wt=k.encrypt(Ae.ClientPayload.encode(TA).finish());await x(Ae.HandshakeMessage.encode({clientFinish:{static:IA,payload:wt}}).finish()),await k.finishInit(),Ue()},Ce=async()=>{let oe=await j({tag:"iq",attrs:{id:f(),xmlns:"encrypt",type:"get",to:uA},content:[{tag:"count",attrs:{}}]});return+ie(oe,"count").attrs.value},ce=null,Ye=async(oe=cd)=>{if(ce){i.debug("Pre-key upload already in progress, waiting for completion"),await ce;return}let le=async Be=>{i.info({count:oe,retryCount:Be},"uploading pre-keys");let eA=await pe.transaction(async()=>{i.debug({requestedCount:oe},"generating pre-keys with requested count");let{update:IA,node:TA}=await $Z({creds:X,keys:pe},oe);return L.emit("creds.update",IA),TA},X?.me?.id||"upload-pre-keys");try{await j(eA),i.info({count:oe},"uploaded pre-keys successfully")}catch(IA){if(i.error({uploadError:IA.toString(),count:oe},"Failed to upload pre-keys to server"),Be<3){let TA=Math.min(1e3*Math.pow(2,Be),1e4);return i.info(`Retrying pre-key upload in ${TA}ms`),await new Promise(wt=>setTimeout(wt,TA)),le(Be+1)}throw IA}};ce=Promise.race([le(0),new Promise((Be,eA)=>setTimeout(()=>eA(new lr.Boom("Pre-key upload timeout",{statusCode:408})),h$))]);try{await ce}finally{ce=null}},ve=async()=>{let oe=X.nextPreKeyId-1;return oe<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await pe.get("pre-key",[oe.toString()]))[oe.toString()],currentPreKeyId:oe}},ue=async()=>{try{let oe=0,le=await Ce();le===0?oe=C$:oe=cd;let{exists:Be,currentPreKeyId:eA}=await ve();i.info(`${le} pre-keys found on server`),i.info(`Current prekey ID: ${eA}, exists in storage: ${Be}`);let IA=le<=oe,TA=!Be&&eA>0;if(IA||TA){let WA=[];IA&&WA.push(`server count low (${le})`),TA&&WA.push(`current prekey ${eA} missing from storage`),i.info(`Uploading PreKeys due to: ${WA.join(", ")}`),await Ye(oe)}else i.info(`PreKey validation passed - Server: ${le}, Current prekey ${eA} exists`)}catch(oe){i.error({error:oe},"Failed to check/upload pre-keys during initialization")}},aA=async oe=>{await k.decodeFrame(oe,le=>{qe=new Date;let Be=!1;if(Be=G.emit("frame",le),!(le instanceof Uint8Array)){let eA=le.attrs.id;i.level==="trace"&&i.trace({xml:Zi(le),msg:"recv xml"}),Be=G.emit(`${g$}${eA}`,le)||Be;let IA=le.tag,TA=le.attrs||{},wt=Array.isArray(le.content)?le.content[0]?.tag:"";for(let WA of Object.keys(TA))Be=G.emit(`${QE}${IA},${WA}:${TA[WA]},${wt}`,le)||Be,Be=G.emit(`${QE}${IA},${WA}:${TA[WA]}`,le)||Be,Be=G.emit(`${QE}${IA},${WA}`,le)||Be;Be=G.emit(`${QE}${IA},,${wt}`,le)||Be,Be=G.emit(`${QE}${IA}`,le)||Be,!Be&&i.level==="debug"&&i.debug({unhandled:!0,msgId:eA,fromMe:!1,frame:le},"communication recv")}})},iA=async oe=>{if(Xe){i.trace({trace:oe?.stack},"connection already closed");return}if(Xe=!0,i.info({trace:oe?.stack},oe?"connection errored":"connection closed"),clearInterval(Ge),clearTimeout(je),G.removeAllListeners("close"),G.removeAllListeners("open"),G.removeAllListeners("message"),me.close?.(),!G.isClosed&&!G.isClosing)try{await G.close()}catch{}for(let le of rA)try{await le(oe)}catch(Be){i.error({err:Be},"error in socket end handler")}L.emit("connection.update",{connection:"close",lastDisconnect:{error:oe,date:new Date}}),L.removeAllListeners("connection.update"),L.destroy()},$e=async()=>{if(G.isOpen)return;if(G.isClosed||G.isClosing)throw new lr.Boom("Connection Closed",{statusCode:yt.connectionClosed});let oe,le;await new Promise((Be,eA)=>{oe=()=>Be(void 0),le=IP(eA),G.on("open",oe),G.on("close",le),G.on("error",le)}).finally(()=>{G.off("open",oe),G.off("close",le),G.off("error",le)})},Ue=()=>Ge=setInterval(()=>{qe||(qe=new Date),Date.now()-qe.getTime()>e+5e3?iA(new lr.Boom("Connection was lost",{statusCode:yt.connectionLost})):G.isOpen?j({tag:"iq",attrs:{id:f(),to:uA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(le=>{i.error({trace:le.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),yA=oe=>j({tag:"iq",attrs:{to:uA,xmlns:"passive",type:"set"},content:[{tag:oe,attrs:{}}]}),Ie=async oe=>{let le=A.creds.me?.id;le&&await H({tag:"iq",attrs:{to:uA,type:"set",id:f(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:le,reason:"user_initiated"}}]}),iA(new lr.Boom(oe||"Intentional Logout",{statusCode:yt.loggedOut}))},ye=async(oe,le)=>{let Be=le??Yq(cP(5));if(le&&le?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=Be,A.creds.me={id:Ft(oe,"s.whatsapp.net"),name:"~"},L.emit("creds.update",A.creds),await H({tag:"iq",attrs:{to:uA,type:"set",id:f(),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 _e()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:Iv(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function _e(){let oe=cP(32),le=cP(16),Be=await Lf(A.creds.pairingCode,oe),eA=wq(A.creds.pairingEphemeralKeyPair.public,Be,le);return Buffer.concat([oe,le,eA])}let DA=oe=>j({tag:"iq",attrs:{to:uA,id:f(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:oe}]});G.on("message",aA),G.on("open",async()=>{try{await hA()}catch(oe){i.error({err:oe},"error in validating connection"),iA(oe)}}),G.on("error",IP(iA)),G.on("close",()=>void iA(new lr.Boom("Connection Terminated",{statusCode:yt.connectionClosed}))),G.on("CB:xmlstreamend",()=>void iA(new lr.Boom("Connection Terminated by Server",{statusCode:yt.connectionClosed}))),G.on("CB:iq,type:set,pair-device",async oe=>{let le={tag:"iq",attrs:{to:uA,type:"result",id:oe.attrs.id}};await H(le);let Be=ie(oe,"pair-device"),eA=mA(Be,"ref"),IA=Buffer.from(X.noiseKey.public).toString("base64"),TA=Buffer.from(X.signedIdentityKey.public).toString("base64"),wt=X.advSecretKey,WA=c||6e4,Er=()=>{if(!G.isOpen)return;let Kt=eA.shift();if(!Kt){iA(new lr.Boom("QR refs attempts ended",{statusCode:yt.timedOut}));return}let rn=Kt.content.toString("utf-8"),an=V9(rn,IA,TA,wt,a);L.emit("connection.update",{qr:an}),je=setTimeout(Er,WA),WA=c||2e4};Er()}),G.on("CB:iq,,pair-success",async oe=>{i.debug("pair success recv");try{OA(oe);let{reply:le,creds:Be}=a9(oe,X);i.info({me:Be.me,platform:Be.platform},"pairing configured successfully, expect to restart the connection..."),L.emit("creds.update",Be),L.emit("connection.update",{isNewLogin:!0,qr:void 0}),await H(le),BA()}catch(le){i.info({trace:le.stack},"error in pairing"),iA(le)}}),G.on("CB:success",async oe=>{try{OA(oe),await ue(),await yA("active");try{await F()}catch(le){i.warn({e:le},"failed to run digest after login")}}catch(le){i.warn({err:le},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(je),L.emit("creds.update",{me:{...A.creds.me,lid:oe.attrs.lid}}),L.emit("connection.update",{connection:"open"}),BA(),oe.attrs.lid&&A.creds.me?.id){let le=oe.attrs.lid;process.nextTick(async()=>{try{let Be=A.creds.me.id;await me.lidMapping.storeLIDPNMappings([{lid:le,pn:Be}]);let{user:eA,device:IA}=lA(Be);await A.keys.set({"device-list":{[eA]:[IA?.toString()||"0"]}}),await me.migrateSession(Be,le),i.info({myPN:Be,myLID:le},"Own LID session created successfully")}catch(Be){i.error({error:Be,lid:le},"Failed to create own LID session")}})}}),G.on("CB:stream:error",oe=>{let[le]=bo(oe);i.error({reasonNode:le,fullErrorNode:oe},"stream errored out");let{reason:Be,statusCode:eA}=Uq(oe);iA(new lr.Boom(`Stream Errored (${Be})`,{statusCode:eA,data:le||oe}))}),G.on("CB:failure",oe=>{let le=+(oe.attrs.reason||500);iA(new lr.Boom("Connection Failure",{statusCode:le,data:oe.attrs}))}),G.on("CB:ib,,downgrade_webclient",()=>{iA(new lr.Boom("Multi-device beta not joined",{statusCode:yt.multideviceMismatch}))}),G.on("CB:ib,,offline_preview",async oe=>{i.info("offline preview received",JSON.stringify(oe)),await H({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),G.on("CB:ib,,edge_routing",oe=>{let le=ie(oe,"edge_routing"),Be=ie(le,"routing_info");Be?.content&&(A.creds.routingInfo=Buffer.from(Be?.content),L.emit("creds.update",A.creds))});let Te=!1;process.nextTick(()=>{X.me?.id&&(L.buffer(),Te=!0),L.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),G.on("CB:ib,,offline",oe=>{let Be=+(ie(oe,"offline")?.attrs.count||0);i.info(`handled ${Be} offline messages/notifications`),Te&&(L.flush(),i.trace("flushed events for initial buffer")),L.emit("connection.update",{receivedPendingNotifications:!0})}),L.on("creds.update",oe=>{let le=oe.me?.name;X.me?.name!==le&&(i.debug({name:le},"updated pushName"),H({tag:"presence",attrs:{name:le}}).catch(Be=>{i.warn({trace:Be.stack},"error in sending presence update on name change")})),Object.assign(X,oe)});let OA=({attrs:oe})=>{let le=oe?.t;if(!le)return;let Be=Number(le);if(Number.isNaN(Be)||Be<=0)return;let eA=Date.now();B=Be*1e3-eA,i.debug({offset:B},"calculated server time offset")},zA=()=>{let oe=3*aP.Day;return((Date.now()+B+oe)%aP.Week).toString()},BA=async()=>{if(!G.isOpen)return;let oe={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:zA()}}]};try{await H(oe)}catch(le){i.debug({error:le},"failed to send unified_session telemetry")}},rt=oe=>{rA.push(oe)},Jt=async()=>{let oe=await ld({},fr.REACHOUT_TIMELOCK,kr.xwa2_fetch_account_reachout_timelock,j,f),le={isActive:!!oe?.is_active,timeEnforcementEnds:oe?.time_enforcement_ends&&oe?.time_enforcement_ends!=="0"?new Date(parseInt(oe.time_enforcement_ends,10)*1e3):void 0,enforcementType:oe?.enforcement_type??Rs.DEFAULT};return L.emit("connection.update",{reachoutTimeLock:le}),le},NA=async()=>ld({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},fr.MESSAGE_CAPPING_INFO,kr.xwa2_message_capping_info,j,f);return{type:"md",ws:G,ev:L,authState:{creds:X,keys:pe},signalRepository:me,get user(){return A.creds.me},generateMessageTag:f,query:j,waitForMessage:q,waitForSocketOpen:$e,sendRawMessage:x,sendNode:H,logout:Ie,end:iA,registerSocketEndHandler:rt,onUnexpectedError:nA,uploadPreKeys:Ye,uploadPreKeysToServerIfRequired:ue,digestKeyBundle:F,rotateSignedPreKey:T,requestPairingCode:ye,updateServerTimeOffset:OA,sendUnifiedSession:BA,wamBuffer:p,waitForConnectionUpdate:Gq(L),sendWAMBuffer:DA,executeUSyncQuery:V,onWhatsApp:U,fetchAccountReachoutTimelock:Jt,fetchNewChatMessageCap:NA}};function IP(n){return r=>{n(new lr.Boom(`WebSocket Error (${r?.message})`,{statusCode:Kq(r),data:r}))}}var ELe=(n,r)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return r?.length&&(o.content=r),[o]},k$=n=>{let{logger:r,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:t}=n,s=R$(n),{ev:g,ws:c,authState:l,generateMessageTag:p,sendNode:B,query:Q,signalRepository:f,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:R}=s,k=f.lidMapping.getLIDForPN.bind(f.lidMapping),G,K={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},x=Qr.Connecting,H=zn(),q=zn(),j=zn(),F=zn(),T,V={initialBootstrapComplete:!1,recentSyncComplete:!1},U,b=new Set,L=n.placeholderResendCache||new xn({stdTTL:ng.MSG_RETRY,useClones:!1}),X=async Y=>{let{[Y]:z}=await l.keys.get("app-state-sync-key",[Y]);return z},pe=async(Y=!1)=>{if(!G||Y){let{content:z}=await Q({tag:"iq",attrs:{xmlns:"privacy",to:uA,type:"get"},content:[{tag:"privacy",attrs:{}}]});G=aT(z?.[0],"category")}return G},me=async(Y,z)=>{await Q({tag:"iq",attrs:{xmlns:"privacy",to:uA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:Y,value:z}}]}]})},qe=async Y=>{await me("messages",Y)},Se=async Y=>{await me("calladd",Y)},Ge=async Y=>{await me("last",Y)},je=async Y=>{await me("online",Y)},Xe=async Y=>{await me("profile",Y)},rA=async Y=>{await me("status",Y)},nA=async Y=>{await me("readreceipts",Y)},Fe=async Y=>{await me("groupadd",Y)},hA=async Y=>{await Q({tag:"iq",attrs:{xmlns:"disappearing_mode",to:uA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:Y.toString()}}]})},Ce=async()=>{let Y=await Q({tag:"iq",attrs:{xmlns:"bot",to:uA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),z=ie(Y,"bot"),ee=[];for(let te of mA(z,"section"))if(te.attrs.type==="all")for(let he of mA(te,"bot"))ee.push({jid:he.attrs.jid,personaId:he.attrs.persona_id});return ee},ce=async(...Y)=>{let z=new tn().withStatusProtocol();for(let te of Y)z.withUser(new An().withId(te));let ee=await s.executeUSyncQuery(z);if(ee)return ee.list},Ye=async(...Y)=>{let z=new tn().withDisappearingModeProtocol();for(let te of Y)z.withUser(new An().withId(te));let ee=await s.executeUSyncQuery(z);if(ee)return ee.list},ve=async(Y,z,ee)=>{let te;if(!Y)throw new cg.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");oA(Y)!==oA(l.creds.me.id)?te=oA(Y):te=void 0;let{img:he}=await Hm(z,ee);await Q({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:profile:picture",...te?{target:te}:{}},content:[{tag:"picture",attrs:{type:"image"},content:he}]})},ue=async Y=>{let z;if(!Y)throw new cg.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");oA(Y)!==oA(l.creds.me.id)?z=oA(Y):z=void 0,await Q({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:profile:picture",...z?{target:z}:{}}})},aA=async Y=>{await Q({tag:"iq",attrs:{to:uA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(Y,"utf-8")}]})},iA=async Y=>{await NA({pushNameSetting:Y},"")},$e=async()=>{let Y=await Q({tag:"iq",attrs:{xmlns:"blocklist",to:uA,type:"get"}}),z=ie(Y,"list");return mA(z,"item").map(ee=>ee.attrs.jid)},Ue=async(Y,z)=>{let ee=oA(Y),te,he;if(vA(ee)||yr(ee)){if(te=ee,z==="block"){let ge=await f.lidMapping.getPNForLID(ee);if(!ge)throw new cg.Boom(`Unable to resolve PN JID for LID: ${Y}`,{statusCode:400});he=oA(ge)}}else if(nt(ee)||Lt(ee)){let ge=await f.lidMapping.getLIDForPN(ee);if(!ge)throw new cg.Boom(`Unable to resolve LID for PN JID: ${Y}`,{statusCode:400});te=ge,z==="block"&&(he=oA(ee))}else throw new cg.Boom(`Invalid jid: ${Y}`,{statusCode:400});let se={action:z,jid:te};if(z==="block"){if(!he)throw new cg.Boom(`pn_jid required for block: ${Y}`,{statusCode:400});se.pn_jid=he}await Q({tag:"iq",attrs:{xmlns:"blocklist",to:uA,type:"set"},content:[{tag:"item",attrs:se}]})},yA=async Y=>{let z=await Q({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:Y}}]}]}),ee=ie(z,"business_profile"),te=ie(ee,"profile");if(te){let he=ie(te,"address"),se=ie(te,"description"),ge=ie(te,"website"),Ee=ie(te,"email"),Pe=ie(ie(te,"categories"),"category"),tA=ie(te,"business_hours"),CA=tA?mA(tA,"business_hours_config"):void 0,UA=ge?.content?.toString();return{wid:te.attrs?.jid,address:he?.content?.toString(),description:se?.content?.toString()||"",website:UA?[UA]:[],email:Ee?.content?.toString(),category:Pe?.content?.toString(),business_hours:{timezone:tA?.attrs?.timezone,business_config:CA?.map(({attrs:MA})=>MA)}}}},Ie=async(Y,z)=>{r.info({fromTimestamp:z},"clean dirty bits "+Y),await B({tag:"iq",attrs:{to:uA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:p()},content:[{tag:"clean",attrs:{type:Y,...z?{timestamp:z.toString()}:null}}]})},ye=Y=>({onMutation(z){O9(z,g,l.creds.me,Y?{accountSettings:l.creds.accountSettings}:void 0,r)}}),_e=g.createBufferedFunction(async(Y,z)=>{let ee=new Map,te=async Ee=>{if(ee.has(Ee))return ee.get(Ee)??void 0;let Pe=await X(Ee);return ee.set(Ee,Pe??null),Pe},he={},se={};await l.keys.transaction(async()=>{let Ee=new Set(Y),Pe={},tA=new Set;for(;Ee.size;){let CA={},UA=[];for(let jA of Ee){let gA=(await l.keys.get("app-state-sync-version",[jA]))[jA];gA?(gA=Uk(gA),typeof he[jA]>"u"&&(he[jA]=gA.version)):gA=qm(),CA[jA]=gA;let xA=tA.has(jA);xA&&tA.delete(jA),r.info(`resyncing ${jA} from v${gA.version}${xA?" (forcing snapshot)":""}`),UA.push({tag:"collection",attrs:{name:jA,version:gA.version.toString(),return_snapshot:(xA||!gA.version).toString()}})}let MA=await Q({tag:"iq",attrs:{to:uA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:UA}]}),LA=await m9(MA,n?.options);for(let jA in LA){let Oe=jA,{patches:gA,hasMorePatches:xA,snapshot:Kr}=LA[Oe];try{if(Kr){let{state:Yt,mutationMap:go}=await D9(Oe,Kr,te,he[Oe],e.snapshot,r);CA[Oe]=Yt,Object.assign(se,go),r.info(`restored state of ${Oe} from snapshot to v${Yt.version} with mutations`),await l.keys.set({"app-state-sync-version":{[Oe]:Yt}})}if(gA.length){let{state:Yt,mutationMap:go}=await Kk(Oe,gA,CA[Oe],te,n.options,he[Oe],r,e.patch);await l.keys.set({"app-state-sync-version":{[Oe]:Yt}}),r.info(`synced ${Oe} to v${Yt.version}`),he[Oe]=Yt.version,Object.assign(se,go)}xA?r.info(`${Oe} has more patches...`):Ee.delete(Oe)}catch(Yt){Pe[Oe]=(Pe[Oe]||0)+1;let go={name:Oe,attempt:Pe[Oe],version:CA[Oe].version,statusCode:Yt.output?.statusCode,errorType:Yt.name,error:Yt.stack};Xh(Yt)&&Pe[Oe]>=Hk?(r.warn(go,`${Oe} blocked on missing key from v${CA[Oe].version}, parking after ${Pe[Oe]} attempts`),b.add(Oe),Ee.delete(Oe)):Xh(Yt)?(r.info(go,`${Oe} blocked on missing key from v${CA[Oe].version}, retrying with snapshot`),tA.add(Oe)):Q9(Yt,Pe[Oe])?(r.warn(go,`failed to sync ${Oe} from v${CA[Oe].version}, giving up`),Ee.delete(Oe)):(r.info(go,`failed to sync ${Oe} from v${CA[Oe].version}, forcing snapshot retry`),tA.add(Oe))}}}},l?.creds?.me?.id||"resync-app-state");let{onMutation:ge}=ye(z);for(let Ee in se)ge(se[Ee])}),DA=async(Y,z="preview",ee)=>{let te=oA(Y),he=nt(te)||vA(te),se=l.creds.me,ge=se&&(te===oA(se.id)||se.lid&&te===oA(se.lid)),Ee;K.profilePicPrivacyToken&&he&&!ge&&(Ee=await iv({authState:l,jid:te,getLIDForPN:k})),Y=oA(Y);let Pe=await Q({tag:"iq",attrs:{target:Y,to:uA,type:"get",xmlns:"w:profile:picture"},content:ELe(z,Ee)},ee);return ie(Pe,"picture")?.attrs?.url},Te=async(Y,z,ee)=>{let te=await Q({tag:"call",attrs:{id:p(),to:"@call"},content:[{tag:"link_create",attrs:{media:Y},content:z?[{tag:"event",attrs:{start_time:String(z.startTime)}}]:void 0}]},ee);return ie(te,"link_create")?.attrs?.token},OA=async(Y,z)=>{let ee=l.creds.me,te=Y==="available";if(te||Y==="unavailable"){if(!ee.name){r.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:te}),te&&m(),await B({tag:"presence",attrs:{name:ee.name.replace(/@/g,""),type:Y}})}else{let{server:he}=lA(z);await B({tag:"chatstate",attrs:{from:he==="lid"?ee.lid:ee.id,to:z},content:[{tag:Y==="recording"?"composing":Y,attrs:Y==="recording"?{media:"audio"}:{}}]})}},zA=async Y=>{let z=oA(Y),te=nt(z)||vA(z)?await iv({authState:l,jid:z,getLIDForPN:k}):void 0;return B({tag:"presence",attrs:{to:Y,id:p(),type:"subscribe"},content:te})},BA=({tag:Y,attrs:z,content:ee})=>{let te,he=z.from,se=z.participant||z.from;if(!(a(he)&&he!==uA)){if(Y==="presence")te={lastKnownPresence:z.type==="unavailable"?"unavailable":"available",lastSeen:z.last&&z.last!=="deny"?+z.last:void 0,groupOnlineCount:z.count?+z.count:void 0};else if(Array.isArray(ee)){let[ge]=ee,Ee=ge.tag;Ee==="paused"&&(Ee="available"),ge.attrs?.media==="audio"&&(Ee="recording"),te={lastKnownPresence:Ee}}else r.error({tag:Y,attrs:z,content:ee},"recv invalid presence node");te&&g.emit("presence.update",{id:he,presences:{[se]:te}})}},rt=async Y=>{let z=Y.type,ee=l.creds.myAppStateKeyId;if(!ee)throw new cg.Boom("App state key not present!",{statusCode:400});let te,he;if(await j.mutex(async()=>{await l.keys.transaction(async()=>{r.debug({patch:Y},"applying app patch"),await _e([z],!1);let{[z]:se}=await l.keys.get("app-state-sync-version",[z]);te=se?Uk(se):qm(),he=await f9(Y,ee,te,X);let{patch:ge,state:Ee}=he,Pe={tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:z,version:(Ee.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:Ae.SyncdPatch.encode(ge).finish()}]}]}]};await Q(Pe),await l.keys.set({"app-state-sync-version":{[z]:Ee}})},l?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:se}=ye(!1),{mutationMap:ge}=await Kk(z,[{...he.patch,version:{version:he.state.version}}],te,X,n.options,void 0,r);for(let Ee in ge)se(ge[Ee])}},Jt=async()=>{let Y=await Q({tag:"iq",attrs:{to:uA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...l?.creds?.lastPropHash?{hash:l.creds.lastPropHash}:{}}}]}),z=ie(Y,"props"),ee={};z&&(z.attrs?.hash&&(l.creds.lastPropHash=z?.attrs?.hash,g.emit("creds.update",l.creds)),ee=aT(z,"prop"));let te=ee[10518]??ee.privacy_token_sending_on_all_1_on_1_messages;te!==void 0&&(K.privacyTokenOn1to1=te==="true"||te==="1");let he=ee[9666]??ee.profile_scraping_privacy_token_in_photo_iq;he!==void 0&&(K.profilePicPrivacyToken=he==="true"||he==="1");let se=ee[14303]??ee.lid_trusted_token_issue_to_lid;return se!==void 0&&(K.lidTrustedTokenIssueToLid=se==="true"||se==="1"),r.debug({serverProps:K},"fetched props"),ee},NA=(Y,z)=>{let ee=w9(Y,z);return rt(ee)},oe=Y=>NA({disableLinkPreviews:{isPreviewsDisabled:Y}},""),le=(Y,z,ee)=>NA({star:{messages:z,star:ee}},Y),Be=(Y,z)=>NA({contact:z},Y),eA=Y=>NA({contact:null},Y),IA=(Y,z)=>NA({addLabel:{...z}},Y),TA=(Y,z)=>NA({addChatLabel:{labelId:z}},Y),wt=(Y,z)=>NA({removeChatLabel:{labelId:z}},Y),WA=(Y,z,ee)=>NA({addMessageLabel:{messageId:z,labelId:ee}},Y),Er=(Y,z,ee)=>NA({removeMessageLabel:{messageId:z,labelId:ee}},Y),Kt=Y=>NA({quickReply:Y},""),rn=Y=>NA({quickReply:{timestamp:Y,deleted:!0}},""),an=async()=>{await Promise.all([Jt(),$e(),pe()])},Z=g.createBufferedFunction(async(Y,z)=>{if(g.emit("messages.upsert",{messages:[Y],type:z}),Y.pushName){let se=Y.key.fromMe?l.creds.me.id:Y.key.participant||Y.key.remoteJid;se=oA(se),Y.key.fromMe||g.emit("contacts.update",[{id:se,notify:Y.pushName,verifiedName:Y.verifiedBizName}]),Y.key.fromMe&&Y.pushName&&l.creds.me?.name!==Y.pushName&&g.emit("creds.update",{me:{...l.creds.me,name:Y.pushName}})}let ee=Jm(Y.message),te=ee?A(ee)&&gd.includes(ee.syncType):!1;if(ee&&te){let se=ee.syncType;se===Ae.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!V.initialBootstrapComplete&&(V.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:se,status:"complete",explicit:!0})),se===Ae.HistorySync.HistorySyncType.RECENT&&ee.progress===100&&!V.recentSyncComplete&&(V.recentSyncComplete=!0,clearTimeout(U),U=void 0,g.emit("messaging-history.status",{syncType:se,status:"complete",explicit:!0})),se===Ae.HistorySync.HistorySyncType.RECENT&&!V.recentSyncComplete&&(clearTimeout(U),U=setTimeout(()=>{V.recentSyncComplete||(V.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:Ae.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),U=void 0},p$))}ee&&x===Qr.AwaitingInitialSync&&(T&&(clearTimeout(T),T=void 0),te?(x=Qr.Syncing,r.info("Transitioned to Syncing state")):(x=Qr.Online,r.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let he=async()=>{if(x===Qr.Syncing){b.clear(),r.info("Doing app state sync"),await _e(JJ,!0),x=Qr.Online,r.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let se=(l.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:se})}};await Promise.all([(async()=>{te&&await he()})(),x9(Y,{signalRepository:f,shouldProcessHistoryMsg:te,placeholderResendCache:L,ev:g,creds:l.creds,keyStore:l.keys,logger:r,options:n.options,getMessage:t})]),Y.message?.protocolMessage?.appStateSyncKeyShare&&x===Qr.Syncing&&(r.info("App state sync key arrived, triggering app state sync"),await he())});return c.on("CB:presence",BA),c.on("CB:chatstate",BA),c.on("CB:ib,,dirty",async Y=>{let{attrs:z}=ie(Y,"dirty");switch(z.type){case"account_sync":if(z.timestamp){let{lastAccountSyncTimestamp:te}=l.creds;te&&await Ie("account_sync",te),te=+z.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:te})}break;case"groups":break;default:r.info({node:Y},"received unknown sync");break}}),g.on("connection.update",({connection:Y,receivedPendingNotifications:z})=>{if(Y==="close"&&(b.clear(),clearTimeout(U),U=void 0),Y==="open"&&(i&&an().catch(te=>y(te,"init queries")),OA(o?"available":"unavailable").catch(te=>y(te,"presence update requests"))),!z||x!==Qr.Connecting)return;if(V.initialBootstrapComplete=!1,V.recentSyncComplete=!1,clearTimeout(U),U=void 0,x=Qr.AwaitingInitialSync,r.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(Ae.Message.HistorySyncNotification.create({syncType:Ae.HistorySync.HistorySyncType.RECENT}))){r.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),x=Qr.Online,setTimeout(()=>g.flush(),0);return}if(l.creds.accountSyncCounter>0){r.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),x=Qr.Online,setTimeout(()=>g.flush(),0);return}r.info("First connection, awaiting history sync notification with a 20s timeout."),T&&clearTimeout(T),T=setTimeout(()=>{if(x===Qr.AwaitingInitialSync){r.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),x=Qr.Online,g.flush();let te=(l.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:te})}},2e4)}),g.on("creds.update",({myAppStateKeyId:Y})=>{if(!Y||b.size===0)return;if(x===Qr.Syncing){b.clear();return}let z=[...b];b.clear(),r.info({collections:z},"app state sync key arrived, re-syncing blocked collections"),_e(z,!1).catch(ee=>y(ee,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:Y,pn:z})=>{try{await f.lidMapping.storeLIDPNMappings([{lid:Y,pn:z}])}catch(ee){r.warn({lid:Y,pn:z,error:ee},"Failed to store LID-PN mapping")}}),R(()=>{T&&(clearTimeout(T),T=void 0),!n.placeholderResendCache&&L.close&&L.close(),x=Qr.Connecting,G=void 0}),{...s,serverProps:K,createCallLink:Te,getBotListV2:Ce,messageMutex:H,receiptMutex:q,appStatePatchMutex:j,notificationMutex:F,fetchPrivacySettings:pe,upsertMessage:Z,appPatch:rt,sendPresenceUpdate:OA,presenceSubscribe:zA,profilePictureUrl:DA,fetchBlocklist:$e,fetchStatus:ce,fetchDisappearingDuration:Ye,updateProfilePicture:ve,removeProfilePicture:ue,updateProfileStatus:aA,updateProfileName:iA,updateBlockStatus:Ue,updateDisableLinkPreviewsPrivacy:oe,updateCallPrivacy:Se,updateMessagesPrivacy:qe,updateLastSeenPrivacy:Ge,updateOnlinePrivacy:je,updateProfilePicturePrivacy:Xe,updateStatusPrivacy:rA,updateReadReceiptsPrivacy:nA,updateGroupsAddPrivacy:Fe,updateDefaultDisappearingMode:hA,getBusinessProfile:yA,resyncAppState:_e,chatModify:NA,cleanDirtyBits:Ie,addOrEditContact:Be,removeContact:eA,placeholderResendCache:L,addLabel:IA,addChatLabel:TA,removeChatLabel:wt,addMessageLabel:WA,removeMessageLabel:Er,star:le,addOrEditQuickReply:Kt,removeQuickReply:rn}};var v$=n=>{let r=k$(n),{authState:o,ev:i,query:e,upsertMessage:a}=r,A=async(g,c,l)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:l}),t=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return mE(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={},l=ie(g,"groups");if(l){let p=mA(l,"group");for(let B of p){let Q=mE({tag:"result",attrs:{},content:[B]});c[Q.id]=Q}}return r.ev.emit("groups.update",Object.values(c)),c};return r.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=ie(g,"dirty");c.type==="groups"&&(await s(),await r.cleanDirtyBits("groups"))}),{...r,groupMetadata:t,groupCreate:async(g,c)=>{let l=nr(),p=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:l},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return mE(p)},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:{}}]),l=ie(c,"membership_approval_requests");return mA(l,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,l)=>{let p=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:l,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=ie(p,"membership_requests_action"),Q=ie(B,l);return mA(Q,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,l)=>{let p=await A(g,"set",[{tag:l,attrs:{},content:c.map(f=>({tag:"participant",attrs:{jid:f}}))}]),B=ie(p,l);return mA(B,"participant").map(f=>({status:f.attrs.error||"200",jid:f.attrs.jid,content:f}))},groupUpdateDescription:async(g,c)=>{let p=(await t(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:nr()}:{delete:"true"},...p?{prev:p}:{}},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 ie(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return ie(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return ie(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 l=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=Ae.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:nr(r.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:QA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:Pr()},"notify"),l.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return mE(c)},groupToggleEphemeral:async(g,c)=>{let l=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[l])},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}},mE=n=>{let r=ie(n,"group");if(!r){let B=ie(n,"error");if(B){let Q=B.attrs.code?+B.attrs.code:500,f=B.attrs.text||"group metadata query failed";throw new US.Boom(f,{statusCode:Q,data:B})}throw new US.Boom("Invalid group metadata response: missing node",{data:n})}if(!r.attrs.id)throw new US.Boom("Invalid group metadata response: missing group id",{data:r});let o=ie(r,"description"),i,e,a,A,t,s;o&&(i=RA(o,"body"),a=o.attrs.participant?oA(o.attrs.participant):void 0,A=o.attrs.participant_pn?oA(o.attrs.participant_pn):void 0,t=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=r.attrs.id.includes("@")?r.attrs.id:Ft(r.attrs.id,"g.us"),c=ie(r,"ephemeral")?.attrs.expiration,l=RA(r,"member_add_mode")==="all_member_add";return{id:g,notify:r.attrs.notify,addressingMode:r.attrs.addressing_mode==="lid"?LC.LID:LC.PN,subject:r.attrs.subject,subjectOwner:r.attrs.s_o,subjectOwnerPn:r.attrs.s_o_pn,subjectOwnerUsername:r.attrs.s_o_username,subjectTime:+r.attrs.s_t,size:r.attrs.size?+r.attrs.size:mA(r,"participant").length,creation:+r.attrs.creation,owner:r.attrs.creator?oA(r.attrs.creator):void 0,ownerPn:r.attrs.creator_pn?oA(r.attrs.creator_pn):void 0,ownerUsername:r.attrs.creator_username||void 0,owner_country_code:r.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:t,descTime:s,linkedParent:ie(r,"linked_parent")?.attrs.jid||void 0,restrict:!!ie(r,"locked"),announce:!!ie(r,"announcement"),isCommunity:!!ie(r,"parent"),isCommunityAnnounce:!!ie(r,"default_sub_group"),joinApprovalMode:!!ie(r,"membership_approval_mode"),memberAddMode:l,participants:mA(r,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:vA(B.jid)&&nt(B.phone_number)?B.phone_number:void 0,lid:nt(B.jid)&&vA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var SE=Le(ar(),1);var pLe=n=>{let{id:r,thread_metadata:o,viewer_metadata:i}=n;return{id:r,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}},CLe=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,P$=n=>{let r=v$(n),{query:o,generateMessageTag:i}=r,e=(A,t,s)=>ld(A,t,s,o,i),a=async(A,t)=>{let s={newsletter_id:A,updates:{...t,settings:null}};return e(s,fr.UPDATE_METADATA,"xwa2_newsletter_update")};return{...r,newsletterCreate:async(A,t)=>{let g=await e({input:{name:A,description:t??null}},fr.CREATE,kr.xwa2_newsletter_create);return pLe(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},fr.SUBSCRIBERS,kr.xwa2_newsletter_subscribers),newsletterMetadata:async(A,t)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:t,type:A.toUpperCase()}},g=await e(s,fr.METADATA,kr.xwa2_newsletter_metadata);return CLe(g)},newsletterFollow:A=>e({newsletter_id:A},fr.FOLLOW,kr.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},fr.UNFOLLOW,kr.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},fr.MUTE,kr.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},fr.UNMUTE,kr.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,t)=>await a(A,{name:t}),newsletterUpdateDescription:async(A,t)=>await a(A,{description:t}),newsletterUpdatePicture:async(A,t)=>{let{img:s}=await Hm(t);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,t,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:t,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,t,s,g)=>{let c={count:t.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 t=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=ie(t,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},fr.ADMIN_COUNT,kr.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,t)=>{await e({newsletter_id:A,user_id:t},fr.CHANGE_OWNER,kr.xwa2_newsletter_change_owner)},newsletterDemote:async(A,t)=>{await e({newsletter_id:A,user_id:t},fr.DEMOTE,kr.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},fr.DELETE,kr.xwa2_newsletter_delete_v2)}}};var G$=n=>{let{logger:r,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:t,maxMsgRetryCount:s}=n,g=P$(n),{ev:c,authState:l,messageMutex:p,signalRepository:B,upsertMessage:Q,query:f,fetchPrivacySettings:y,sendNode:m,groupMetadata:R,groupToggleEphemeral:k,registerSocketEndHandler:G}=g,K=B.lidMapping.getLIDForPN.bind(B.lidMapping),x=new Set,H=n.userDevicesCache||new xn({stdTTL:ng.USER_DEVICES,useClones:!1}),q=zn(),j=t?new AS(r,s):null,F=N$(),T,V=Dk,U=async(Ce=!1)=>{let ce=await T;return(!ce||Ce||new Date().getTime()-ce.fetchDate.getTime()>ce.ttl*1e3)&&(T=(async()=>{let Ye=await f({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:uA},content:[{tag:"media_conn",attrs:{}}]}),ve=ie(Ye,"media_conn"),ue={hosts:mA(ve,"host").map(({attrs:aA})=>({hostname:aA.hostname,maxContentLengthBytes:+aA.maxContentLengthBytes})),auth:ve.attrs.auth,ttl:+ve.attrs.ttl,fetchDate:new Date};return r.debug("fetched media conn"),ue.hosts[0]&&(V=ue.hosts[0].hostname),ue})()),T},b=async(Ce,ce,Ye,ve)=>{if(!Ye||Ye.length===0)throw new SE.Boom("missing ids in receipt");let ue={tag:"receipt",attrs:{id:Ye[0]}};(ve==="read"||ve==="read-self")&&(ue.attrs.t=Pr().toString()),ve==="sender"&&(nt(Ce)||vA(Ce))?(ue.attrs.recipient=Ce,ue.attrs.to=ce):(ue.attrs.to=Ce,ce&&(ue.attrs.participant=ce)),ve&&(ue.attrs.type=ve);let iA=Ye.slice(1);iA.length&&(ue.content=[{tag:"list",attrs:{},content:iA.map($e=>({tag:"item",attrs:{id:$e}}))}]),r.debug({attrs:ue.attrs,messageIds:Ye},"sending receipt for messages"),await m(ue)},L=async(Ce,ce)=>{let Ye=KZ(Ce);for(let{jid:ve,participant:ue,messageIds:aA}of Ye)await b(ve,ue,aA,ce)},X=async Ce=>{let Ye=(await y()).readreceipts==="all"?"read":"read-self";await L(Ce,Ye)},pe=async(Ce,ce,Ye)=>{let ve=[];ce||r.debug("not using cache for devices");let ue=[],aA=Ce.map(Ie=>{let ye=lA(Ie),_e=ye?.user,DA=ye?.device;return typeof DA=="number"&&DA>=0&&_e?(ve.push({user:_e,device:DA,jid:Ie}),null):(Ie=oA(Ie),{jid:Ie,user:_e})}).filter(Ie=>Ie!==null),iA;if(ce&&H.mget){let Ie=aA.map(ye=>ye?.user).filter(Boolean);iA=await H.mget(Ie)}for(let{jid:Ie,user:ye}of aA)if(ce){let _e=iA?.[ye]||(H.mget?void 0:await H.get(ye));if(_e){let DA=_e.map(Te=>({...Te,jid:Ft(Te.user,Te.server,Te.device)}));ve.push(...DA),r.trace({user:ye},"using cache for devices")}else ue.push(Ie)}else ue.push(Ie);if(!ue.length)return ve;let $e=new Set;for(let Ie of ue)if(vA(Ie)||yr(Ie)){let ye=lA(Ie)?.user;ye&&$e.add(ye)}let Ue=new tn().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Ie of ue)Ue.withUser(new An().withId(Ie));let yA=await g.executeUSyncQuery(Ue);if(yA){let Ie=yA.list.filter(Te=>!!Te.lid);if(Ie.length>0){r.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Ie.map(Te=>({lid:Te.lid,pn:Te.id})));try{let Te=Ie.map(OA=>OA.lid);Te.length&&await qe(Te,!0)}catch(Te){r.warn({e:Te,count:Ie.length},"failed to assert sessions for newly mapped LIDs")}}let ye=XZ(yA?.list,l.creds.me.id,l.creds.me.lid,Ye),_e={};for(let Te of ye)_e[Te.user]=_e[Te.user]||[],_e[Te.user]?.push(Te);for(let[Te,OA]of Object.entries(_e)){let zA=$e.has(Te);for(let BA of OA){let rt=zA?Ft(Te,BA.server,BA.device):Ft(BA.user,BA.server,BA.device);ve.push({...BA,jid:rt}),r.debug({user:BA.user,device:BA.device,finalJid:rt,usedLid:zA},"Processed device with LID priority")}}await q.mutex(async()=>{if(H.mset)await H.mset(Object.entries(_e).map(([Te,OA])=>({key:Te,value:OA})));else for(let Te in _e)_e[Te]&&await H.set(Te,_e[Te])});let DA={};for(let[Te,OA]of Object.entries(_e))OA&&OA.length>0&&(DA[Te]=OA.map(zA=>zA.device?.toString()||"0"));if(Object.keys(DA).length>0)try{await l.keys.set({"device-list":DA}),r.debug({userCount:Object.keys(DA).length},"stored user device lists for bulk migration")}catch(Te){r.warn({error:Te},"failed to store user device lists")}}return ve},me=(Ce,ce)=>je(Ce,{protocolMessage:{type:Ae.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:ce?.slice(0,30),labelTimestamp:Pr()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),qe=async(Ce,ce)=>{let Ye=!1,ve=[...new Set(Ce)],ue=[];r.debug({jids:Ce},"assertSessions call with jids");for(let aA of ve)!ce&&(await B.validateSession(aA)).exists||ue.push(aA);if(ue.length){let aA=[...ue.filter($e=>!!vA($e)||!!yr($e)),...(await B.lidMapping.getLIDsForPNs(ue.filter($e=>!!nt($e)||!!Lt($e)))||[]).map($e=>$e.lid)];r.debug({jidsRequiringFetch:ue,wireJids:aA},"fetching sessions");let iA=await f({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:uA},content:[{tag:"key",attrs:{},content:aA.map($e=>{let Ue={jid:$e};return ce&&(Ue.reason="identity"),{tag:"user",attrs:Ue}})}]});await ZZ(iA,B),Ye=!0}return Ye},Se=async Ce=>{if(!l.creds.me?.id)throw new SE.Boom("Not authenticated");let ce={protocolMessage:{peerDataOperationRequestMessage:Ce,type:Ae.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},Ye=oA(l.creds.me.id);return await je(Ye,ce,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},Ge=async(Ce,ce,Ye,ve)=>{if(!Ce.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let ue=await a(ce,Ce),aA=Array.isArray(ue)?ue:Ce.map(_e=>({recipientJid:_e,message:ue})),iA=!1,$e=l.creds.me.id,Ue=l.creds.me?.lid,yA=Ue?lA(Ue)?.user:null,Ie=aA.map(async({recipientJid:_e,message:DA})=>{try{if(!_e)return null;let Te=DA;if(ve){let{user:rt}=lA(_e),{user:Jt}=lA($e),NA=yA;(rt===Jt||NA&&rt===NA)&&!(_e===$e||Ue&&_e===Ue)&&(Te=ve,r.debug({jid:_e,targetUser:rt},"Using DSM for own device"))}let OA=hl(Te),zA=_e;return await F.mutex(zA,async()=>{let{type:rt,ciphertext:Jt}=await B.encryptMessage({jid:_e,data:OA});return rt==="pkmsg"&&(iA=!0),{tag:"to",attrs:{jid:_e},content:[{tag:"enc",attrs:{v:"2",type:rt,...Ye||{}},content:Jt}]}})}catch(Te){return r.error({jid:_e,err:Te},"Failed to encrypt for recipient"),null}}),ye=(await Promise.all(Ie)).filter(_e=>_e!==null);if(Ce.length>0&&ye.length===0)throw new SE.Boom("All encryptions failed",{statusCode:500});return{nodes:ye,shouldIncludeDeviceIdentity:iA}},je=async(Ce,ce,{messageId:Ye,participant:ve,additionalAttributes:ue,additionalNodes:aA,useUserDevicesCache:iA,useCachedGroupMetadata:$e,statusJidList:Ue})=>{let yA=G9(l.creds),Ie=l.creds.me?.lid,ye=!!ve?.jid,_e=ye,DA="status@broadcast",{user:Te,server:OA}=lA(Ce),zA=OA==="g.us",BA=Ce===DA,rt=OA==="lid",Jt=OA==="newsletter",NA=zA||BA,oe=Ce;Ye=Ye||nr(yA),iA=iA!==!1,$e=$e!==!1&&!BA;let le=[],Be=BA?DA:oe,eA=[],IA=[],TA,wt={deviceSentMessage:{destinationJid:Be,message:ce},messageContextInfo:ce.messageContextInfo},WA={};if(ve){!zA&&!BA&&(ue={...ue,device_fanout:"false"});let{user:Er,device:Kt}=lA(ve.jid);IA.push({user:Er,device:Kt,jid:ve.jid})}return await l.keys.transaction(async()=>{let Er=rA(ce);if(Er&&(WA.mediatype=Er),Jt){let se=a?await a(ce,[]):ce,ge=xq(se);eA.push({tag:"plaintext",attrs:{},content:ge});let Ee={tag:"message",attrs:{to:Ce,id:Ye,type:Xe(ce),...ue||{}},content:eA};r.debug({msgId:Ye},`sending newsletter message to ${Ce}`),await m(Ee);return}if((Hr(ce)?.pinInChatMessage||Hr(ce)?.reactionMessage)&&(WA["decrypt-fail"]="hide"),NA&&!ye){let[se,ge]=await Promise.all([(async()=>{let gA=$e&&A?await A(Ce):void 0;return gA&&Array.isArray(gA?.participants)?r.trace({jid:Ce,participants:gA.participants.length},"using cached group metadata"):BA||(gA=await R(Ce)),gA})(),(async()=>!ve&&!BA?(await l.keys.get("sender-key-memory",[Ce]))[Ce]||{}:{})()]),Ee=se?se.participants.map(gA=>gA.id):[];se?.ephemeralDuration&&se.ephemeralDuration>0&&(ue={...ue,expiration:se.ephemeralDuration.toString()}),BA&&Ue&&Ee.push(...Ue);let Pe=await pe(Ee,!!iA,!1);IA.push(...Pe),zA&&(ue={...ue,addressing_mode:se?.addressingMode||"lid"});let tA=await a(ce);if(Array.isArray(tA))throw new SE.Boom("Per-jid patching is not supported in groups");let CA=hl(tA);TA=tA;let MA=(ue?.addressing_mode||se?.addressingMode||"lid")==="lid"&&Ie?Ie:yA,{ciphertext:LA,senderKeyDistributionMessage:jA}=await B.encryptGroupMessage({group:Be,data:CA,meId:MA}),Oe=[];for(let gA of IA){let xA=gA.jid;(!!!ge[xA]||ve)&&!yr(xA)&&!Lt(xA)&&gA.device!==99&&(Oe.push(xA),ge[xA]=!0)}if(Oe.length){r.debug({senderKeyJids:Oe},"sending new sender key");let gA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:jA,groupId:Be}};await qe(Oe);let Kr=await Ge(Oe,gA,WA);_e=_e||Kr.shouldIncludeDeviceIdentity,le.push(...Kr.nodes)}eA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...WA},content:LA}),await l.keys.set({"sender-key-memory":{[Ce]:ge}})}else{let se=yA;rt&&Ie?(se=Ie,r.debug({to:Ce,ownId:se},"Using LID identity for @lid conversation")):r.debug({to:Ce,ownId:se},"Using PN identity for @s.whatsapp.net conversation");let{user:ge}=lA(se);if(!ve){let gA=await a(ce,[Ce]);TA=Array.isArray(gA)?gA.find(xA=>xA.recipientJid===Ce)||gA[0]:gA}if(!ye){let gA=rt?"lid":"s.whatsapp.net";if(IA.push({user:Te,device:0,jid:Ft(Te,gA,0)}),Te!==ge){let xA=rt?"lid":"s.whatsapp.net",Kr=rt&&Ie?lA(Ie).user:lA(yA).user;IA.push({user:Kr,device:0,jid:Ft(Kr,xA,0)})}if(ue?.category!=="peer"){IA.length=0;let xA=rt&&Ie?Ft(lA(Ie)?.user,"lid",void 0):Ft(lA(yA)?.user,"s.whatsapp.net",void 0),Kr=await pe([xA,Ce],!0,!1);IA.push(...Kr),r.debug({deviceCount:IA.length,devices:IA.map(Yt=>`${Yt.user}:${Yt.device}@${lA(Yt.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let Ee=[],Pe=[],tA=[],{user:CA}=lA(yA),{user:UA}=Ie?lA(Ie):{user:null};for(let{user:gA,jid:xA}of IA){if(xA===yA||Ie&&xA===Ie){r.debug({jid:xA,meId:yA,meLid:Ie},"Skipping exact sender device (whatsmeow pattern)");continue}gA===CA||gA===UA?Pe.push(xA):tA.push(xA),Ee.push(xA)}await qe(Ee);let[{nodes:MA,shouldIncludeDeviceIdentity:LA},{nodes:jA,shouldIncludeDeviceIdentity:Oe}]=await Promise.all([Ge(Pe,wt||ce,WA),Ge(tA,ce,WA,wt)]);le.push(...MA),le.push(...jA),(Pe.length>0||tA.length>0)&&(WA.phash=kq([...Pe,...tA])),_e=_e||LA||Oe}if(ye){let se=vA(ve.jid),ge=lt(ve.jid,se?Ie:yA),Ee=ce;if(NA){let UA;if(Ie&&await B.hasSenderKey({group:Be,meId:Ie})?UA=Ie:await B.hasSenderKey({group:Be,meId:yA})&&(UA=yA),UA)try{let MA=await B.getSenderKeyDistributionMessage({group:Be,meId:UA});Ee={...ce,senderKeyDistributionMessage:{groupId:Be,axolotlSenderKeyDistributionMessage:MA}}}catch(MA){r.warn({err:MA,jid:Be},"failed to build SKDM for retry, sending without it")}}let Pe=ge?hl({deviceSentMessage:{destinationJid:Be,message:Ee}}):hl(Ee),{type:tA,ciphertext:CA}=await B.encryptMessage({data:Pe,jid:ve.jid});eA.push({tag:"enc",attrs:{v:"2",type:tA,count:ve.count.toString()},content:CA})}if(le.length)if(ue?.category==="peer"){let se=le[0]?.content?.[0];se&&eA.push(se)}else eA.push({tag:"participants",attrs:{},content:le});let Kt={tag:"message",attrs:{id:Ye,to:Be,type:Xe(ce),...ue||{}},content:eA};if(ve?ir(Be)?(Kt.attrs.to=Be,Kt.attrs.participant=ve.jid):lt(ve.jid,yA)?(Kt.attrs.to=ve.jid,Kt.attrs.recipient=Be):Kt.attrs.to=ve.jid:Kt.attrs.to=Be,_e&&(Kt.content.push({tag:"device-identity",attrs:{},content:Wh(l.creds.account,!0)}),r.debug({jid:Ce},"adding device identity")),!Jt&&!ye&&TA?.messageContextInfo?.messageSecret&&xm(TA))try{let se=hl(TA),ge={id:Ye,fromMe:!0,remoteJid:Be,participant:ve?.jid},Ee=await GZ(se,TA,ge);Ee&&(Kt.content.push(Ee),r.trace({jid:Ce},"added reporting token to message"))}catch(se){r.warn({jid:Ce,trace:se?.stack},"failed to attach reporting token")}let rn=ue?.category==="peer",an=!zA&&!ye&&!BA&&!Jt&&!rn,Z=an?await Zo(Be,K):Be,z=(an?await l.keys.get("tctoken",[Z]):{})[Z],ee=z?.token;if(ee?.length&&vc(z?.timestamp)){r.debug({jid:Be,timestamp:z?.timestamp},"tctoken expired, clearing"),ee=void 0;let se=z?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:z.senderTimestamp}:null;try{await l.keys.set({tctoken:{[Z]:se}})}catch(ge){r.debug({jid:Be,err:ge?.message},"failed to persist tctoken expiry cleanup")}}ee?.length&&g.serverProps.privacyTokenOn1to1&&Kt.content.push({tag:"tctoken",attrs:{},content:ee}),aA&&aA.length>0&&Kt.content.push(...aA),r.debug({msgId:Ye},`sending message to ${le.length} devices`),await m(Kt);let te=!!Hr(ce)?.protocolMessage,he=Be===XJ||eq(Be)||gl(Be);if(an&&!te&&!he&&K9(z?.senderTimestamp)&&!x.has(Z)){x.add(Z);let se=Pr(),ge=B.lidMapping.getPNForLID.bind(B.lidMapping);Ad(Be,g.serverProps.lidTrustedTokenIssueToLid,K,ge).then(Ee=>nA([Ee],se)).then(async Ee=>{await IE({result:Ee,fallbackJid:Z,keys:l.keys,getLIDForPN:K});let tA=(await l.keys.get("tctoken",[Z]))[Z],CA=await cE(l.keys,[Z]);await l.keys.set({tctoken:{[Z]:{token:Buffer.alloc(0),...tA,senderTimestamp:se},...CA}})}).catch(Ee=>{r.debug({jid:Be,err:Ee?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{x.delete(Z)})}j&&!ve&&j.addRecentMessage(Be,Ye,ce)},yA),Ye},Xe=Ce=>{let ce=Hr(Ce);return ce?ce.reactionMessage||ce.encReactionMessage?"reaction":ce.pollCreationMessage||ce.pollCreationMessageV2||ce.pollCreationMessageV3||ce.pollUpdateMessage?"poll":ce.eventMessage?"event":rA(ce)!==""?"media":"text":"text"},rA=Ce=>Ce.imageMessage?"image":Ce.videoMessage?Ce.videoMessage.gifPlayback?"gif":"video":Ce.audioMessage?Ce.audioMessage.ptt?"ptt":"audio":Ce.contactMessage?"vcard":Ce.documentMessage?"document":Ce.contactsArrayMessage?"contact_array":Ce.liveLocationMessage?"livelocation":Ce.stickerMessage?"sticker":Ce.listMessage?"list":Ce.listResponseMessage?"list_response":Ce.buttonsResponseMessage?"buttons_response":Ce.orderMessage?"order":Ce.productMessage?"product":Ce.interactiveResponseMessage?"native_flow_response":Ce.groupInviteMessage?"url":"",nA=async(Ce,ce)=>{let Ye=(ce??Pr()).toString();return await f({tag:"iq",attrs:{to:uA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:Ce.map(ue=>({tag:"token",attrs:{jid:oA(ue),t:Ye,type:"trusted_contact"}}))}]})},Fe=MZ(n,U),hA=ET(c,"messages.media-update");return G(()=>{!n.userDevicesCache&&H.close&&H.close(),T=void 0,j&&j.clear()}),{...g,userDevicesCache:H,devicesMutex:q,issuePrivacyTokens:nA,assertSessions:qe,relayMessage:je,sendReceipt:b,sendReceipts:L,readMessages:X,refreshMediaConn:U,getMediaHost:()=>V,waUploadToServer:Fe,fetchPrivacySettings:y,sendPeerDataOperationMessage:Se,createParticipantNodes:Ge,getUSyncDevices:pe,messageRetryManager:j,updateMemberLabel:me,updateMediaMessage:async Ce=>{let ce=xZ(Ce.message),Ye=ce.mediaKey,ve=l.creds.me.id,ue=_Z(Ce.key,Ye,ve),aA;if(await Promise.all([m(ue),hA(async iA=>{let $e=iA.find(Ue=>Ue.key.id===Ce.key.id);if($e){if($e.error)aA=$e.error;else try{let Ue=TZ($e.media,Ye,$e.key.id);if(Ue.result!==Ae.MediaRetryNotification.ResultType.SUCCESS){let yA=Ae.MediaRetryNotification.ResultType[Ue.result];throw new SE.Boom(`Media re-upload failed by device (${yA})`,{data:Ue,statusCode:wk(Ue.result)||404})}ce.directPath=Ue.directPath,ce.url=xh(ce.directPath,V),r.debug({directPath:Ue.directPath,key:$e.key},"media update successful")}catch(Ue){aA=Ue}return!0}})]),aA)throw aA;return c.emit("messages.update",[{key:Ce.key,update:{message:Ce.message}}]),Ce},sendMessage:async(Ce,ce,Ye={})=>{let ve=l.creds.me.id;if(typeof ce=="object"&&"disappearingMessagesInChat"in ce&&typeof ce.disappearingMessagesInChat<"u"&&ir(Ce)){let{disappearingMessagesInChat:ue}=ce;await k(Ce,typeof ue=="boolean"?ue?Vh:0:ue)}else{let ue=await UZ(Ce,ce,{logger:r,userJid:ve,getUrlInfo:_e=>H9(_e,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:r,uploadImage:i?Fe:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:Fe,mediaCache:n.mediaCache,options:n.options,messageId:nr(g.user?.id),...Ye}),aA="event"in ce&&!!ce.event,iA="delete"in ce&&!!ce.delete,$e="edit"in ce&&!!ce.edit,Ue="pin"in ce&&!!ce.pin,yA="poll"in ce&&!!ce.poll,Ie={},ye=[];return iA?ir(ce.delete?.remoteJid)&&!ce.delete?.fromMe?Ie.edit="8":Ie.edit="7":$e?Ie.edit="1":Ue?Ie.edit="2":yA?ye.push({tag:"meta",attrs:{polltype:"creation"}}):aA&&ye.push({tag:"meta",attrs:{event_type:"creation"}}),await je(Ce,ue.message,{messageId:ue.key.id,useCachedGroupMetadata:Ye.useCachedGroupMetadata,additionalAttributes:Ie,statusJidList:Ye.statusJidList,additionalNodes:ye}),n.emitOwnEvents&&process.nextTick(async()=>{await p.mutex(()=>Q(ue,"append"))}),ue}}}};var hLe=new Set(Object.values(Rs));function dLe(n){return typeof n=="string"&&hLe.has(n)}var F$=n=>{let{logger:r,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,t=G$(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:l,ws:p,messageMutex:B,notificationMutex:Q,receiptMutex:f,signalRepository:y,query:m,upsertMessage:R,resyncAppState:k,onUnexpectedError:G,assertSessions:K,sendNode:x,relayMessage:H,sendReceipt:q,uploadPreKeys:j,sendPeerDataOperationMessage:F,messageRetryManager:T,registerSocketEndHandler:V,issuePrivacyTokens:U,fetchAccountReachoutTimelock:b,placeholderResendCache:L}=t,X=y.lidMapping.getLIDForPN.bind(y.lidMapping),pe=zn(),me=n.msgRetryCounterCache||new xn({stdTTL:ng.MSG_RETRY,useClones:!1}),qe=n.callOfferCache||new xn({stdTTL:ng.CALL_OFFER,useClones:!1}),Se=new xn({stdTTL:5,useClones:!1}),Ge=!1,je=async(Z,Y,z)=>{if(!l.creds.me?.id)throw new Ed.Boom("Not authenticated");let ee={historySyncOnDemandRequest:{chatJid:Y.remoteJid,oldestMsgFromMe:Y.fromMe,oldestMsgId:Y.id,oldestMsgTimestampMs:z,onDemandMsgCount:Z},peerDataOperationRequestType:Ae.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return F(ee)},Xe=async(Z,Y)=>{if(!l.creds.me?.id)throw new Ed.Boom("Not authenticated");if(await L.get(Z?.id)){r.debug({messageKey:Z},"already requested resend");return}else await L.set(Z?.id,Y||!0);if(await ZC(2e3),!await L.get(Z?.id))return r.debug({messageKey:Z},"message received while resend requested"),"RESOLVED";let z={placeholderMessageResendRequest:[{messageKey:Z}],peerDataOperationRequestType:Ae.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await L.get(Z?.id)&&(r.debug({messageKey:Z},"PDO message without response after 8 seconds. Phone possibly offline"),await L.del(Z?.id))},8e3),F(z)},rA=async Z=>{let Y=ie(Z,"update");if(Y){let z=Y.attrs?.op_name;if(!z){r.warn({node:Zi(Z)},"mex notification missing op_name, fallback to legacy"),await hA(Z);return}let ee;try{ee=JSON.parse(Y.content.toString())}catch(he){r.error({err:he,opName:z},"failed to parse mex notification JSON");return}if(ee.errors?.length){r.warn({errors:ee.errors,opName:z},"mex notification has GQL errors");return}let te=ee.data;if(!te){r.warn({opName:z},"mex notification has null data");return}switch(r.debug({opName:z},"processing mex notification"),z){case"NotificationUserReachoutTimelockUpdate":nA(te);break;case"MessageCappingInfoNotification":Fe(te);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 hA(Z);break;default:r.debug({opName:z},"unhandled mex notification");break}return}await hA(Z)},nA=Z=>{let Y=Z.xwa2_notify_account_reachout_timelock;if(!Y){r.warn("reachout timelock notification missing payload");return}if(!Y.is_active){r.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:Rs.DEFAULT}});return}let z=Y.time_enforcement_ends?new Date(parseInt(Y.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),ee=dLe(Y.enforcement_type)?Y.enforcement_type:Rs.DEFAULT;r.info({enforcementType:ee,timeEnforcementEnds:z},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:z,enforcementType:ee}})},Fe=Z=>{let Y=Z.xwa2_notify_new_chat_messages_capping_info_update;if(!Y){r.warn("message capping notification missing payload");return}r.info({payload:Y},"received message capping update"),c.emit("message-capping.update",Y)},hA=async Z=>{let Y=ie(Z,"mex"),z=Y?.content?null:ie(Z,"update")||bo(Z)[0],ee=Y?.content?Y:z;if(!ee?.content){r.warn({node:Zi(Z)},"invalid mex newsletter notification");return}let te;try{let ge=ee.content;if(Array.isArray(ge)){r.warn({payloadNode:ee},"invalid mex newsletter notification payload format");return}let Ee=typeof ge=="string"?Buffer.from(ge,"binary"):Buffer.from(ge);te=JSON.parse(Ee.toString())}catch(ge){r.error({err:ge,node:Zi(Z)},"failed to parse mex newsletter notification");return}let he=te?.operation??ee?.attrs?.op_name,se=te?.updates;if(!se){let ge=te?.data?.xwa2_notify_linked_profiles;ge&&(se=[ge])}if(!se||!he){r.warn({data:te},"invalid mex newsletter notification content");return}switch(r.info({operation:he,updates:se},"got mex newsletter notification"),he){case"NotificationNewsletterUpdate":for(let ge of se)ge.jid&&ge.settings&&Object.keys(ge.settings).length>0&&c.emit("newsletter-settings.update",{id:ge.jid,update:ge.settings});break;case"NotificationNewsletterAdminPromote":for(let ge of se)ge.jid&&ge.user&&c.emit("newsletter-participants.update",{id:ge.jid,author:Z.attrs.from,user:ge.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let ge of se){let Ee=ge?.jid,Pe=Array.isArray(ge?.added_profiles)?ge.added_profiles:[],tA=[];for(let CA of Pe){let UA=typeof CA=="string"?CA:CA?.pn??CA?.jid??null;if(Ee&&UA){let MA={lid:Ee,pn:UA};c.emit("lid-mapping.update",MA),tA.push(MA)}}await y.lidMapping.storeLIDPNMappings(tA)}break;default:r.info({operation:he,data:te},"unhandled mex newsletter notification");break}},Ce=async Z=>{let Y=Z.attrs.from,z=bo(Z),ee=Z.attrs.participant;for(let te of z)switch(r.debug({from:Y,child:te},"got newsletter notification"),te.tag){case"reaction":{let he={id:Y,server_id:te.attrs.message_id,reaction:{code:RA(te,"reaction"),count:1}};c.emit("newsletter.reaction",he);break}case"view":{let he={id:Y,server_id:te.attrs.message_id,count:parseInt(te.content?.toString()||"0",10)};c.emit("newsletter.view",he);break}case"participant":{let he={id:Y,author:ee,user:te.attrs.jid,action:te.attrs.action,new_role:te.attrs.role};c.emit("newsletter-participants.update",he);break}case"update":{let he=ie(te,"settings");if(he){let se={},ge=ie(he,"name");ge?.content&&(se.name=ge.content.toString());let Ee=ie(he,"description");Ee?.content&&(se.description=Ee.content.toString()),c.emit("newsletter-settings.update",{id:Y,update:se})}break}case"message":{let he=ie(te,"plaintext");if(he?.content)try{let se=typeof he.content=="string"?Buffer.from(he.content,"binary"):Buffer.from(he.content),ge=Ae.Message.decode(se).toJSON(),Ee=Ae.WebMessageInfo.fromObject({key:{remoteJid:Y,id:te.attrs.message_id||te.attrs.server_id,fromMe:!1},message:ge,messageTimestamp:+te.attrs.t}).toJSON();await R(Ee,"append"),r.debug("Processed plaintext newsletter message")}catch(se){r.error({error:se},"Failed to decode plaintext newsletter message")}break}default:r.warn({node:Z,child:te},"Unknown newsletter notification child");break}},ce=async(Z,Y)=>{let z=W9(Z,Y,l.creds.me.id);r.debug({recv:{tag:Z.tag,attrs:Z.attrs},sent:z.attrs},"sent ack"),await x(z)},Ye=async(Z,Y)=>{let z={tag:"call",attrs:{from:l.creds.me.id,to:Y},content:[{tag:"reject",attrs:{"call-id":Z,"call-creator":Y,count:"0"},content:void 0}]};await m(z)},ve=async(Z,Y=!1)=>{let{fullMessage:z}=CT(Z,l.creds.me.id,l.creds.me.lid||""),{key:ee}=z,te=ee.id;if(T){if(T.hasExceededMaxRetries(te)){r.debug({msgId:te},"reached retry limit with new retry manager, clearing"),T.markRetryFailed(te);return}let LA=T.incrementRetryCount(te),jA=`${te}:${ee?.participant}`;await me.set(jA,LA)}else{let LA=`${te}:${ee?.participant}`,jA=await me.get(LA)||0;if(jA>=i){r.debug({retryCount:jA,msgId:te},"reached retry limit, clearing"),await me.del(LA);return}jA+=1,await me.set(LA,jA)}let he=`${te}:${ee?.participant}`,se=await me.get(he)||1,{account:ge,signedPreKey:Ee,signedIdentityKey:Pe}=l.creds,tA=Z.attrs.from,CA=!1,UA="";if(A&&T&&se>1)try{let LA=y.jidToSignalProtocolAddress(tA),jA=await y.validateSession(tA),Oe=T.shouldRecreateSession(tA,jA.exists);CA=Oe.recreate,UA=Oe.reason,CA&&(r.debug({fromJid:tA,retryCount:se,reason:UA},"recreating session for retry"),await l.keys.set({session:{[LA]:null}}),Y=!0)}catch(LA){r.warn({error:LA,fromJid:tA},"failed to check session recreation")}if(se<=2)if(T)T.schedulePhoneRequest(te,async()=>{try{let LA=await Xe(ee);r.debug(`sendRetryRequest: requested placeholder resend (${LA}) for message ${te} (scheduled)`)}catch(LA){r.warn({error:LA,msgId:te},"failed to send scheduled phone request")}});else{let LA=await Xe(ee);r.debug(`sendRetryRequest: requested placeholder resend for message ${LA}`)}let MA=Wh(ge,!0);await l.keys.transaction(async()=>{let LA={tag:"receipt",attrs:{id:te,type:"retry",to:Z.attrs.from},content:[{tag:"retry",attrs:{count:se.toString(),id:Z.attrs.id,t:Z.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:Rn(l.creds.registrationId)}]};if(Z.attrs.recipient&&(LA.attrs.recipient=Z.attrs.recipient),Z.attrs.participant&&(LA.attrs.participant=Z.attrs.participant),se>1||Y||CA){let{update:jA,preKeys:Oe}=await vk(l,1),[gA]=Object.keys(Oe),xA=Oe[+gA];LA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Tn)},{tag:"identity",attrs:{},content:Pe.public},kk(xA,+gA),zh(Ee),{tag:"device-identity",attrs:{},content:MA}]}),c.emit("creds.update",jA)}await x(LA),r.info({msgAttrs:Z.attrs,retryCount:se},"sent retry receipt")},l?.creds?.me?.id||"sendRetryRequest")},ue=new Set,aA=Z=>{(async()=>{let Y=oA(Z),z=await Zo(Y,X),te=(await l.keys.get("tctoken",[z]))?.[z]?.senderTimestamp;if(te==null||vc(te))return;r.debug({jid:Y,senderTimestamp:te},"identity changed, re-issuing tctoken");let he=y.lidMapping.getPNForLID.bind(y.lidMapping),se=await Ad(Y,t.serverProps.lidTrustedTokenIssueToLid,X,he),ge=await U([se],te);await IE({result:ge,fallbackJid:z,keys:l.keys,getLIDForPN:X,onNewJidStored:OA})})().catch(Y=>{r.debug({jid:Z,err:Y?.message},"failed to re-issue tctoken after identity change")})},iA=async Z=>{if(Z.attrs.from===uA){let z=Z.attrs.id;if(z&&ue.has(z))return;let te=+ie(Z,"count").attrs.value,he=te{let ee=Z.attrs.participant,te=Z.attrs.participant_pn,he=Z.attrs.participant_username,se=ie(Y,"participant")?.attrs?.jid||ee,ge=ie(Y,"participant")?.attrs?.phone_number||te;switch(Y?.tag){case"create":let Ee=mE(Y);z.messageStubType=QA.GROUP_CREATE,z.messageStubParameters=[Ee.subject],z.key={participant:Ee.owner,participantAlt:Ee.ownerPn},c.emit("chats.upsert",[{id:Ee.id,name:Ee.subject,conversationTimestamp:Ee.creation}]),c.emit("groups.upsert",[{...Ee,author:ee,authorPn:te,authorUsername:he}]);break;case"ephemeral":case"not_ephemeral":z.message={protocolMessage:{type:Ae.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(Y.attrs.expiration||0)}};break;case"modify":let Pe=mA(Y,"participant").map(Oe=>Oe.attrs.jid);z.messageStubParameters=Pe||[],z.messageStubType=QA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let tA=`GROUP_PARTICIPANT_${Y.tag.toUpperCase()}`;z.messageStubType=QA[tA];let CA=mA(Y,"participant").map(({attrs:Oe})=>({id:Oe.jid,phoneNumber:vA(Oe.jid)&&nt(Oe.phone_number)?Oe.phone_number:void 0,lid:nt(Oe.jid)&&vA(Oe.lid)?Oe.lid:void 0,username:Oe.participant_username||Oe.username||void 0,admin:Oe.type||null}));CA.length===1&&(lt(CA[0].id,ee)||lt(CA[0].id,te))&&Y.tag==="remove"&&(z.messageStubType=QA.GROUP_PARTICIPANT_LEAVE),z.messageStubParameters=CA.map(Oe=>JSON.stringify(Oe));break;case"subject":z.messageStubType=QA.GROUP_CHANGE_SUBJECT,z.messageStubParameters=[Y.attrs.subject];break;case"description":let UA=ie(Y,"body")?.content?.toString();z.messageStubType=QA.GROUP_CHANGE_DESCRIPTION,z.messageStubParameters=UA?[UA]:void 0;break;case"announcement":case"not_announcement":z.messageStubType=QA.GROUP_CHANGE_ANNOUNCE,z.messageStubParameters=[Y.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":z.messageStubType=QA.GROUP_CHANGE_RESTRICT,z.messageStubParameters=[Y.tag==="locked"?"on":"off"];break;case"invite":z.messageStubType=QA.GROUP_CHANGE_INVITE_LINK,z.messageStubParameters=[Y.attrs.code];break;case"member_add_mode":let MA=Y.content;MA&&(z.messageStubType=QA.GROUP_MEMBER_ADD_MODE,z.messageStubParameters=[MA.toString()]);break;case"membership_approval_mode":let LA=ie(Y,"group_join");LA&&(z.messageStubType=QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,z.messageStubParameters=[LA.attrs.state]);break;case"created_membership_requests":z.messageStubType=QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,z.messageStubParameters=[JSON.stringify({lid:se,pn:ge}),"created",Y.attrs.request_method];break;case"revoked_membership_requests":let jA=lt(se,ee);z.messageStubType=QA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,z.messageStubParameters=[JSON.stringify({lid:se,pn:ge}),jA?"revoked":"rejected"];break}},Ue=async Z=>{let[Y]=bo(Z),z=oA(Z.attrs.from);if(!Y){r.debug({from:z},"devices notification missing child, skipping");return}let ee=Y.tag,te=Y.attrs.device_hash,he=mA(Y,"device");if(lt(z,l.creds.me.id)||lt(z,l.creds.me.lid)){let ge=he.map(Ee=>Ee.attrs.jid);r.info({deviceJids:ge},"got my own devices")}if(!he.length){r.debug({from:z,tag:ee},"no devices in notification, skipping");return}let se=[];for(let ge of he){let Ee=ge.attrs.jid;if(!Ee)continue;let Pe=lA(Ee);if(!Pe){r.debug({jid:Ee},"failed to decode device jid, skipping");continue}se.push({jid:Ee,user:Pe.user,server:Pe.server,device:Pe.device})}se.length&&await g.mutex(async()=>{let ge=new Map;for(let Ee of se){let Pe=ge.get(Ee.user)||[];Pe.push(Ee),ge.set(Ee.user,Pe)}for(let[Ee,Pe]of ge){if(ee==="update"){r.debug({user:Ee},`${Ee}'s device list updated, dropping cached devices`),await s?.del(Ee);continue}ee==="remove"&&await y.deleteSession(Pe.map(MA=>MA.jid));let tA=await s?.get(Ee)||[];if(!tA.length){r.debug({user:Ee,tag:ee},"device list not cached, deferring to USync refresh");continue}let CA=new Set(Pe.map(MA=>MA.device)),UA;switch(ee){case"add":r.info({deviceHash:te,count:Pe.length},"devices added"),UA=[...tA.filter(MA=>!CA.has(MA.device)),...Pe.map(MA=>({user:MA.user,server:MA.server,device:MA.device}))];break;case"remove":r.info({deviceHash:te,count:Pe.length},"devices removed"),UA=tA.filter(MA=>!CA.has(MA.device));break;default:r.debug({tag:ee},"Unknown device list change tag");continue}UA.length===0?await s?.del(Ee):await s?.set(Ee,UA)}})},yA=async Z=>{let Y={},[z]=bo(Z),ee=Z.attrs.type,te=oA(Z.attrs.from);switch(ee){case"newsletter":await Ce(Z);break;case"mex":await rA(Z);break;case"w:gp2":$e(Z,z,Y);break;case"mediaretry":let he=NZ(Z);c.emit("messages.media-update",[he]);break;case"encrypt":await iA(Z);break;case"devices":try{await Ue(Z)}catch(co){r.error({error:co,node:Z},"failed to handle devices notification")}break;case"server_sync":let se=ie(Z,"collection");if(se){let co=se.attrs.name;await k([co],!1)}break;case"picture":let ge=ie(Z,"set"),Ee=ie(Z,"delete");if(c.emit("contacts.update",[{id:oA(Z?.attrs?.from)||(ge||Ee)?.attrs?.hash||"",imgUrl:ge?"changed":"removed"}]),ir(te)){let co=ge||Ee;Y.messageStubType=QA.GROUP_CHANGE_ICON,ge&&(Y.messageStubParameters=[ge.attrs.id]),Y.participant=co?.attrs.author,Y.key={...Y.key||{},participant:ge?.attrs.author}}break;case"account_sync":if(z.tag==="disappearing_mode"){let co=+z.attrs.duration,Cd=+z.attrs.t;r.info({newDuration:co},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...l.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:co,ephemeralSettingTimestamp:Cd}}})}else if(z.tag==="blocklist"){let co=mA(z,"item");for(let{attrs:Cd}of co){let X$=[Cd.jid],$$=Cd.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:X$,type:$$})}}break;case"link_code_companion_reg":let Pe=ie(Z,"link_code_companion_reg"),tA=rt(vr(Pe,"link_code_pairing_ref")),CA=rt(vr(Pe,"primary_identity_pub")),UA=rt(vr(Pe,"link_code_pairing_wrapped_primary_ephemeral_pub")),MA=await BA(UA),LA=Ut.sharedKey(l.creds.pairingEphemeralKeyPair.private,MA),jA=lP(32),Oe=lP(32),gA=eo(LA,32,{salt:Oe,info:"link_code_pairing_key_bundle_encryption_key"}),xA=Buffer.concat([Buffer.from(l.creds.signedIdentityKey.public),CA,jA]),Kr=lP(12),Yt=sc(xA,gA,Kr,Buffer.alloc(0)),go=Buffer.concat([Oe,Kr,Yt]),W$=Ut.sharedKey(l.creds.signedIdentityKey.private,CA),Z$=Buffer.concat([LA,W$,jA]);l.creds.advSecretKey=Buffer.from(eo(Z$,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:uA,type:"set",id:t.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:l.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:go},{tag:"companion_identity_public",attrs:{},content:l.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:tA}]}]}),l.creds.registered=!0,c.emit("creds.update",l.creds);break;case"privacy_token":await zA(Z);break}if(Object.keys(Y).length)return Y},Ie=new Set,ye=(async()=>{try{let Z=await $m(l.keys);for(let Y of Z)Ie.add(Y);r.debug({count:Ie.size},"loaded tctoken index")}catch(Z){r.warn({err:Z?.message},"failed to load tctoken index")}})(),_e;async function DA(){_e&&(clearTimeout(_e),_e=void 0);let Z=await cE(l.keys,Ie);return l.keys.set({tctoken:Z})}function Te(){_e&&clearTimeout(_e),_e=setTimeout(()=>{_e=void 0,DA().catch(Z=>{r.warn({err:Z?.message},"failed to save tctoken index")})},5e3)}function OA(Z){Z&&Z!==sg&&!Ie.has(Z)&&(Ie.add(Z),Te())}let zA=async Z=>{if(!ie(Z,"tokens"))return;let z=oA(Z.attrs.from),te=(Z.attrs.sender_lid&&vA(oA(Z.attrs.sender_lid))?oA(Z.attrs.sender_lid):void 0)??await Zo(z,X);r.debug({from:z,storageJid:te},"processing privacy token notification"),await IE({result:Z,fallbackJid:te,keys:l.keys,getLIDForPN:X,onNewJidStored:OA})};async function BA(Z){let Y=rt(Z),z=Y.slice(0,32),ee=await Lf(l.creds.pairingCode,z),te=Y.slice(32,48),he=Y.slice(48,80);return Oq(he,ee,te)}function rt(Z){if(Z===void 0)throw new Ed.Boom("Invalid buffer",{statusCode:400});return Z instanceof Buffer?Z:Buffer.from(Z)}let Jt=async(Z,Y)=>{let z=`${Z}:${Y}`;return(await me.get(z)||0){let z=`${Z}:${Y}`,ee=(await me.get(z)||0)+1;await me.set(z,ee)},oe=async(Z,Y,z,ee)=>{let te=Z.remoteJid,he=Z.participant||te,se=+z.attrs.count||1,ge=Y[0],Ee=[];for(let Oe of Y){let gA;if(T){let xA=T.getRecentMessage(te,Oe);xA&&(gA=xA.message,r.debug({jid:te,id:Oe},"found message in retry cache"),T.markRetrySuccess(Oe))}gA||(gA=await e({...Z,id:Oe}),gA&&(r.debug({jid:te,id:Oe},"found message via getMessage"),T&&T.markRetrySuccess(Oe))),Ee.push(gA)}let Pe=!lA(he)?.device,tA=y.jidToSignalProtocolAddress(he),CA=!1,UA=WZ(ee);if(UA)try{await y.injectE2ESession({jid:he,session:UA}),CA=!0,r.debug({participant:he,retryCount:se},"injected session from retry receipt key bundle")}catch(Oe){r.warn({error:Oe,participant:he},"failed to inject session from retry receipt")}if(!CA){let Oe=vs(ee,"registration",4);if(typeof Oe=="number"&&Number.isInteger(Oe)){let gA=await y.getSessionInfo(he);gA&&gA.registrationId!==0&&gA.registrationId!==Oe&&(r.info({participant:he,stored:gA.registrationId,received:Oe},"reg id mismatch on retry without bundle, deleting session"),await l.keys.set({session:{[tA]:null}}))}}let MA=2;if(ge&&T){let Oe=await y.getSessionInfo(he);Oe&&(se===MA?T.saveBaseKey(tA,ge,Oe.baseKey):se>MA&&(T.hasSameBaseKey(tA,ge,Oe.baseKey)&&(r.warn({participant:he,retryCount:se},"base key collision on retry, forcing fresh session"),await l.keys.set({session:{[tA]:null}})),T.deleteBaseKey(tA,ge)))}let LA=!1,jA="";if(A&&T&&se>1&&!CA)try{let Oe=await y.validateSession(he),gA=T.shouldRecreateSession(he,Oe.exists);LA=gA.recreate,jA=gA.reason,LA&&(r.debug({participant:he,retryCount:se,reason:jA},"recreating session for outgoing retry"),await l.keys.set({session:{[tA]:null}}))}catch(Oe){r.warn({error:Oe,participant:he},"failed to check session recreation for outgoing retry")}CA||await K([he],!0),ir(te)&&await l.keys.set({"sender-key-memory":{[te]:null}}),r.debug({participant:he,sendToAll:Pe,shouldRecreateSession:LA,recreateReason:jA,injectedFromBundle:CA},"prepared session for retry resend");for(let[Oe,gA]of Ee.entries())if(Y[Oe])if(gA&&await Jt(Y[Oe],he)){await NA(Y[Oe],he);let xA={messageId:Y[Oe]};Pe?xA.useUserDevicesCache=!1:xA.participant={jid:he,count:+z.attrs.count},await H(Z.remoteJid,gA,xA)}else r.debug({jid:Z.remoteJid,id:Y[Oe]},"recv retry request, but message not available")},le=async Z=>{let{attrs:Y,content:z}=Z,ee=Y.from.includes("lid"),te=lt(Y.participant||Y.from,ee?l.creds.me?.lid:l.creds.me?.id),he=!te||ir(Y.from)?Y.from:Y.recipient,se=!Y.recipient||(Y.type==="retry"||Y.type==="sender")&&te,ge={remoteJid:he,id:"",fromMe:se,participant:Y.participant},Ee=[Y.id];if(Array.isArray(z)){let Pe=mA(z[0],"item");Ee.push(...Pe.map(tA=>tA.attrs.id))}try{await Promise.all([f.mutex(async()=>{let Pe=Lq(Y.type);if(typeof Pe<"u"&&(Pe>=Ae.WebMessageInfo.Status.SERVER_ACK||!te))if(ir(he)||_n(he)){if(Y.participant){let tA=Pe===Ae.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",Ee.map(CA=>({key:{...ge,id:CA},receipt:{userJid:oA(Y.participant),[tA]:+Y.t}})))}}else c.emit("messages.update",Ee.map(tA=>({key:{...ge,id:tA},update:{status:Pe,messageTimestamp:or(+(Y.t??0))}})));if(Y.type==="retry"){ge.participant=ge.participant||Y.from;let tA=ie(Z,"retry");if(Ee[0]&&ge.participant&&await Jt(Ee[0],ge.participant))if(ge.fromMe)try{await NA(Ee[0],ge.participant),r.debug({attrs:Y,key:ge},"recv retry request"),await oe(ge,Ee,tA,Z)}catch(CA){r.error({key:ge,ids:Ee,trace:CA instanceof Error?CA.stack:"Unknown error"},"error in sending message again")}else r.info({attrs:Y,key:ge},"recv retry for not fromMe message");else r.info({attrs:Y,key:ge},"will not send message again, as sent too many times")}})])}finally{await ce(Z).catch(Pe=>r.error({ackErr:Pe},"failed to ack receipt"))}},Be=async Z=>{let Y=Z.attrs.from;try{await Promise.all([Q.mutex(async()=>{let z=await yA(Z);if(z){let ee=lt(Z.attrs.participant||Y,l.creds.me.id),{senderAlt:te,addressingMode:he}=Yf(Z);z.key={remoteJid:Y,fromMe:ee,participant:Z.attrs.participant,participantAlt:te,participantUsername:Z.attrs.participant_username,addressingMode:he,id:Z.attrs.id,...z.key||{}},z.participant??(z.participant=Z.attrs.participant),z.messageTimestamp=+Z.attrs.t;let se=Ae.WebMessageInfo.fromObject(z);await R(se,"append")}})])}finally{await ce(Z).catch(z=>r.error({ackErr:z},"failed to ack notification"))}},eA=async Z=>{if(ie(Z,"enc")?.attrs.type==="msmsg"){r.debug({key:Z.attrs.key},"ignored msmsg"),await ce(Z,Ic.MissingMessageSecret);return}let z=!1;try{let{fullMessage:ee,category:te,author:he,decrypt:se}=qq(Z,l.creds.me.id,l.creds.me.lid||"",y,r),ge=ee.key.participantAlt||ee.key.remoteJidAlt;if(ge){let Ee=lA(ge)?.server,Pe=ee.key.participant||ee.key.remoteJid;Ee==="lid"?await y.lidMapping.getPNForLID(ge)||(await y.lidMapping.storeLIDPNMappings([{lid:ge,pn:Pe}]),await y.migrateSession(Pe,ge)):(await y.lidMapping.storeLIDPNMappings([{lid:Pe,pn:ge}]),await y.migrateSession(ge,Pe))}await B.mutex(async()=>{if(await se(),ee.key?.remoteJid&&ee.key?.id&&ee.message&&T&&T.addRecentMessage(ee.key.remoteJid,ee.key.id,ee.message),ee.messageStubType===Ae.WebMessageInfo.StubType.CIPHERTEXT&&ee.category!=="peer"){if(ee?.messageStubParameters?.[0]===jq)return z=!0,ce(Z,Ic.ParsingError);if(ee.messageStubParameters?.[0]===Kf){let Pe=ie(Z,"unavailable")?.attrs?.type;if(Pe==="bot_unavailable_fanout"||Pe==="hosted_unavailable_fanout"||Pe==="view_once_unavailable_fanout")return r.debug({msgId:ee.key.id,unavailableType:Pe},"skipping placeholder resend for excluded unavailable type"),z=!0,ce(Z);let tA=Pr()-or(ee.messageTimestamp);if(tA>I$)return r.debug({msgId:ee.key.id,messageAge:tA},"skipping placeholder resend for old message"),z=!0,ce(Z);let CA={remoteJid:ee.key.remoteJid,fromMe:ee.key.fromMe,id:ee.key.id,participant:ee.key.participant},UA={key:ee.key,messageTimestamp:ee.messageTimestamp,pushName:ee.pushName,participant:ee.participant,verifiedBizName:ee.verifiedBizName};Xe(CA,UA).then(MA=>{MA&&MA!=="RESOLVED"&&(r.debug({msgId:ee.key.id,requestId:MA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:ee.key,update:{messageStubParameters:[Kf,MA]}}]))}).catch(MA=>{r.warn({err:MA,msgId:ee.key.id},"failed to request placeholder resend for unavailable message")}),z=!0,await ce(Z)}else{if(_n(ee.key.remoteJid)){let Ee=Pr()-or(ee.messageTimestamp);if(Ee>c$)return r.debug({msgId:ee.key.id,messageAge:Ee,remoteJid:ee.key.remoteJid},"skipping retry for expired status message"),z=!0,ce(Z)}r.debug("[handleMessage] Attempting retry request for failed decryption"),await pe.mutex(async()=>{try{if(!p.isOpen){r.debug({node:Z},"Connection closed, skipping retry");return}let Ee=ie(Z,"enc");await ve(Z,!Ee),o&&await ZC(o)}catch(Ee){r.error({err:Ee},"Failed to send retry")}z=!0,await ce(Z,Ic.UnhandledError)})}}else if(T&&ee.key.id&&T.cancelPendingPhoneRequest(ee.key.id),ks(ee.key.remoteJid))z=!0,await ce(Z),r.debug({key:ee.key},"processed newsletter message without receipts");else{let Pe,tA=ee.key.participant;if(te==="peer"?Pe="peer_msg":ee.key.fromMe?(Pe="sender",(vA(ee.key.remoteJid)||vA(ee.key.remoteJidAlt))&&(tA=he)):Ge||(Pe="inactive"),z=!0,await q(ee.key.remoteJid,tA,[ee.key.id],Pe),Jm(ee.message)){let UA=oA(ee.key.remoteJid);await q(UA,void 0,[ee.key.id],"hist_sync")}}Y9(ee,l.creds.me.id,l.creds.me.lid),await R(ee,Z.attrs.offline?"append":"notify")})}catch(ee){r.error({error:ee,node:Zi(Z)},"error in handling message"),z||await ce(Z,Ic.UnhandledError).catch(te=>r.error({ackErr:te},"failed to ack message after error"))}},IA=async Z=>{try{let{attrs:Y}=Z,[z]=bo(Z);if(!z)throw new Ed.Boom("Missing call info in call node");let ee=Hq(z),te=z.attrs["call-id"],he=z.attrs.from||z.attrs["call-creator"],se={chatId:Y.from,from:he,callerPn:z.attrs.caller_pn,id:te,date:new Date(+Y.t*1e3),offline:!!Y.offline,status:ee};if(ee==="relaylatency"){let Ee=z.attrs.latency||z.attrs.latency_ms||z.attrs["latency-ms"],Pe=Ee?Number(Ee):void 0;Number.isFinite(Pe)&&(se.latencyMs=Pe)}ee==="offer"&&(se.isVideo=!!ie(z,"video"),se.isGroup=z.attrs.type==="group"||!!z.attrs["group-jid"],se.groupJid=z.attrs["group-jid"],await qe.set(se.id,se));let ge=await qe.get(se.id);ge&&(se.isVideo=ge.isVideo,se.isGroup=ge.isGroup,se.callerPn=se.callerPn||ge.callerPn),(ee==="reject"||ee==="accept"||ee==="timeout"||ee==="terminate")&&await qe.del(se.id),c.emit("call",[se])}catch(Y){r.error({error:Y,node:Zi(Z)},"error in handling call")}finally{await ce(Z).catch(Y=>r.error({ackErr:Y},"failed to ack call"))}},TA=async({attrs:Z})=>{let Y={remoteJid:Z.from,fromMe:!0,id:Z.id};if(Z.error){let z=Z.error===String(Ic.SenderReachoutTimelocked);if(Z.error===pT.MessageAccountRestriction){r.warn({msgId:Z.id,from:Z.from},"error 463: account restricted or missing tctoken for contact");let ee=Z.from;ee&&!rn.has(ee)&&(rn.add(ee),(async()=>{try{let te=y.lidMapping.getPNForLID.bind(y.lidMapping),he=await Zo(ee,X),se=await Ad(ee,t.serverProps.lidTrustedTokenIssueToLid,X,te),ge=await U([se],Pr());await IE({result:ge,fallbackJid:he,keys:l.keys,getLIDForPN:X,onNewJidStored:OA}),r.debug({from:ee},"completed 463 token recovery issuance")}catch(te){r.debug({from:ee,err:te?.message},"failed 463 token recovery issuance")}finally{rn.delete(ee)}})())}else Z.error===pT.SmaxInvalid?r.warn({msgId:Z.id,from:Z.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):z?(await b().catch(ee=>r.warn({err:ee},"failed to fetch reachout timelock")),r.warn({attrs:Z},"received error in ack")):r.warn({attrs:Z},"received error in ack");c.emit("messages.update",[{key:Y,update:{status:sl.ERROR,messageStubParameters:z?[Z.error,Jq]:[Z.error]}}])}},wt=async(Z,Y,z)=>{c.buffer(),await ee(),c.flush();function ee(){return z(Z,!1).catch(te=>G(te,Y))}},WA=T$(new Map([["message",eA],["call",IA],["receipt",le],["notification",Be]]),{isWsOpen:()=>p.isOpen,onUnexpectedError:G,yieldToEventLoop:()=>new Promise(Z=>setImmediate(Z))}),Er=async(Z,Y,z,ee)=>{let te=Y.attrs.from,he=te;if(Z==="receipt"&&te){let ge=Y.attrs,Ee=ge.from.includes("lid");he=!lt(ge.participant||ge.from,Ee?l.creds.me?.lid:l.creds.me?.id)||ir(ge.from)?ge.from:ge.recipient}if(he&&he!==uA&&a(he)){await ce(Y,Z==="message"?Ic.UnhandledError:void 0);return}!!Y.attrs.offline?WA.enqueue(Z,Y):await wt(Y,z,ee)};p.on("CB:message",async Z=>{await Er("message",Z,"processing message",eA)}),p.on("CB:call",async Z=>{await Er("call",Z,"handling call",IA)}),p.on("CB:receipt",async Z=>{await Er("receipt",Z,"handling receipt",le)}),p.on("CB:notification",async Z=>{await Er("notification",Z,"handling notification",Be)}),p.on("CB:ack,class:message",Z=>{TA(Z).catch(Y=>G(Y,"handling bad ack"))}),c.on("call",async([Z])=>{if(Z&&(Z.status==="timeout"||Z.status==="offer"&&Z.isGroup)){let Y={key:{remoteJid:Z.chatId,id:Z.id,fromMe:!1},messageTimestamp:Pr(Z.date)};Z.status==="timeout"?Z.isGroup?Y.messageStubType=Z.isVideo?QA.CALL_MISSED_GROUP_VIDEO:QA.CALL_MISSED_GROUP_VOICE:Y.messageStubType=Z.isVideo?QA.CALL_MISSED_VIDEO:QA.CALL_MISSED_VOICE:Y.message={call:{callKey:Buffer.from(Z.id)}};let z=Ae.WebMessageInfo.fromObject(Y);await R(z,Z.offline?"append":"notify")}});let Kt=0,rn=new Set;c.on("connection.update",({isOnline:Z,connection:Y})=>{if(typeof Z<"u"&&(Ge=Z,r.trace(`sendActiveReceipts set to "${Ge}"`)),Y==="close"&&_e){clearTimeout(_e),_e=void 0;try{Promise.resolve(DA()).catch(()=>{})}catch{}}if(Z){let z=Date.now(),ee=1440*60*1e3;z-Kt>=ee&&(Kt=z,an())}}),V(()=>{!n.msgRetryCounterCache&&me.close&&me.close(),!n.callOfferCache&&qe.close&&qe.close(),Se.close(),Ge=!1});async function an(){try{await ye;let Z=await $m(l.keys),Y=new Set(Ie);for(let ge of Z)Y.add(ge);if(!Y.size)return;let z=[...Y],ee=await l.keys.get("tctoken",z),te={},he=new Set,se=0;for(let ge of z){let Ee=ee[ge];if(!Ee){se++;continue}let Pe=!!Ee.token?.length,tA=Pe&&vc(Ee.timestamp),CA=Ee.senderTimestamp!==void 0,UA=CA&&vc(Ee.senderTimestamp),MA=Pe&&!tA,LA=CA&&!UA;!MA&&!LA?(te[ge]=null,se++):tA&&LA?(te[ge]={token:Buffer.alloc(0),senderTimestamp:Ee.senderTimestamp},he.add(ge),se++):he.add(ge)}if(se===0)return;await l.keys.set({tctoken:{...te,[sg]:{token:Buffer.from(JSON.stringify([...he]))}}}),Ie.clear();for(let ge of he)Ie.add(ge);r.debug({mutated:se,remaining:he.size},"pruned expired tctokens")}catch(Z){r.warn({err:Z?.message},"failed to prune expired tctokens")}}return{...t,sendMessageAck:ce,sendRetryRequest:ve,rejectCall:Ye,fetchMessageHistory:je,requestPlaceholderResend:Xe,messageRetryManager:T}};var L$=n=>{let r=F$(n),{authState:o,query:i,waUploadToServer:e}=r,a=async Q=>{let f=[],y=["address","email","description"];return f.push(...y.filter(R=>Q[R]!==void 0&&Q[R]!==null).map(R=>({tag:R,attrs:{},content:Q[R]}))),Q.websites!==void 0&&f.push(...Q.websites.map(R=>({tag:"website",attrs:{},content:R}))),Q.hours!==void 0&&f.push({tag:"business_hours",attrs:{timezone:Q.hours.timezone},content:Q.hours.days.map(R=>{let k={tag:"business_hours_config",attrs:{day_of_week:R.day,mode:R.mode}};return R.mode==="specific_hours"?{...k,attrs:{...k.attrs,open_time:R.openTimeInMinutes,close_time:R.closeTimeInMinutes}}:k})}),await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:f}]})},A=async Q=>{let{fileSha256:f,filePath:y}=await Um(Q,"biz-cover-photo"),m=f.toString("base64"),{meta_hmac:R,fbid:k,ts:G}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(k),op:"update",token:R,ts:String(G)}}]}]}),k},t=async Q=>await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:Q}}]}]}),s=async({jid:Q,limit:f,cursor:y})=>{Q=Q||o.creds.me?.id,Q=oA(Q);let m=[{tag:"limit",attrs:{},content:Buffer.from((f||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 R=await i({tag:"iq",attrs:{to:uA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:Q,allow_shop_source:"true"},content:m}]});return u$(R)},g=async(Q,f=51)=>{Q=Q||o.creds.me?.id,Q=oA(Q);let y=await i({tag:"iq",attrs:{to:uA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:Q},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(f.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(f.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return B$(y)},c=async(Q,f)=>{let y=await i({tag:"iq",attrs:{to:uA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:Q},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(f)}]}]});return Q$(y)},l=async(Q,f)=>{f=await oP(f,e);let y=iP(Q,f),m=await i({tag:"iq",attrs:{to:uA,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"}]}]}),R=ie(m,"product_catalog_edit"),k=ie(R,"product");return Id(k)},p=async Q=>{Q.isHidden=!!Q.isHidden,Q=await oP(Q,e);let f=iP(void 0,Q),y=await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[f,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=ie(y,"product_catalog_add"),R=ie(m,"product");return Id(R)},B=async Q=>{let f=await i({tag:"iq",attrs:{to:uA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:Q.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(ie(f,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...r,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:p,productDelete:B,productUpdate:l,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:t}};var U$=n=>{let r=L$(n),{authState:o,ev:i,query:e,upsertMessage:a}=r,A=async(l,p,B)=>e({tag:"iq",attrs:{type:p,xmlns:"w:g2",to:l},content:B}),t=async l=>{let p=await A(l,"get",[{tag:"query",attrs:{request:"interactive"}}]);return EP(p)},s=async()=>{let l=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),p={},B=ie(l,"communities");if(B){let Q=mA(B,"community");for(let f of Q){let y=EP({tag:"result",attrs:{},content:[f]});p[y.id]=y}}return r.ev.emit("groups.update",Object.values(p)),p};async function g(l){sd.info({node:l},"parseGroupResult");let p=ie(l,"group");if(p)try{sd.info({groupNode:p},"groupNode");let B=await r.groupMetadata(`${p.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:l=>l!==null?{value:l}:null};return r.ws.on("CB:ib,,dirty",async l=>{let{attrs:p}=ie(l,"dirty");p.type==="communities"&&(await s(),await r.cleanDirtyBits("groups"))}),{...r,communityMetadata:t,communityCreate:async(l,p)=>{let B=lT().substring(0,12),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:l},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(p||"","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(Q)},communityCreateGroup:async(l,p,B)=>{let Q=nr(),f=await A("@g.us","set",[{tag:"create",attrs:{subject:l,key:Q},content:[...p.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(f)},communityLeave:async l=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:l}}]}])},communityUpdateSubject:async(l,p)=>{await A(l,"set",[{tag:"subject",attrs:{},content:Buffer.from(p,"utf-8")}])},communityLinkGroup:async(l,p)=>{await A(p,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:l}}]}]}])},communityUnlinkGroup:async(l,p)=>{await A(p,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:l}}]}])},communityFetchLinkedGroups:async l=>{let p=l,B=!1,Q=await r.groupMetadata(l);Q.linkedParent?p=Q.linkedParent:B=!0;let f=await A(p,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=ie(f,"sub_groups");if(m){let R=mA(m,"group");for(let k of R)y.push({id:k.attrs.id?Ft(k.attrs.id,"g.us"):void 0,subject:k.attrs.subject||"",creation:k.attrs.creation?Number(k.attrs.creation):void 0,owner:k.attrs.creator?oA(k.attrs.creator):void 0,size:k.attrs.size?Number(k.attrs.size):void 0})}return{communityJid:p,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async l=>{let p=await A(l,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=ie(p,"membership_approval_requests");return mA(B,"membership_approval_request").map(f=>f.attrs)},communityRequestParticipantsUpdate:async(l,p,B)=>{let Q=await A(l,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:p.map(R=>({tag:"participant",attrs:{jid:R}}))}]}]),f=ie(Q,"membership_requests_action"),y=ie(f,B);return mA(y,"participant").map(R=>({status:R.attrs.error||"200",jid:R.attrs.jid}))},communityParticipantsUpdate:async(l,p,B)=>{let Q=await A(l,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:p.map(m=>({tag:"participant",attrs:{jid:m}}))}]),f=ie(Q,B);return mA(f,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(l,p)=>{let Q=(await t(l)).descId??null;await A(l,"set",[{tag:"description",attrs:{...p?{id:lT()}:{delete:"true"},...Q?{prev:Q}:{}},content:p?[{tag:"body",attrs:{},content:Buffer.from(p,"utf-8")}]:void 0}])},communityInviteCode:async l=>{let p=await A(l,"get",[{tag:"invite",attrs:{}}]);return ie(p,"invite")?.attrs.code},communityRevokeInvite:async l=>{let p=await A(l,"set",[{tag:"invite",attrs:{}}]);return ie(p,"invite")?.attrs.code},communityAcceptInvite:async l=>{let p=await A("@g.us","set",[{tag:"invite",attrs:{code:l}}]);return ie(p,"community")?.attrs.jid},communityRevokeInviteV4:async(l,p)=>!!await A(l,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:p}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(l,p)=>{l=typeof l=="string"?{remoteJid:l}:l;let B=await A(p.groupJid,"set",[{tag:"accept",attrs:{code:p.inviteCode,expiration:p.inviteExpiration.toString(),admin:l.remoteJid}}]);return l.id&&(p=Ae.Message.GroupInviteMessage.fromObject(p),p.inviteExpiration=0,p.inviteCode="",i.emit("messages.update",[{key:l,update:{message:{groupInviteMessage:p}}}])),await a({key:{remoteJid:p.groupJid,id:nr(r.user?.id),fromMe:!1,participant:l.remoteJid},messageStubType:QA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:l.remoteJid,messageTimestamp:Pr()},"notify"),B.attrs.from}),communityGetInviteInfo:async l=>{let p=await A("@g.us","get",[{tag:"invite",attrs:{code:l}}]);return EP(p)},communityToggleEphemeral:async(l,p)=>{let B=p?{tag:"ephemeral",attrs:{expiration:p.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(l,"set",[B])},communitySettingUpdate:async(l,p)=>{await A(l,"set",[{tag:p,attrs:{}}])},communityMemberAddMode:async(l,p)=>{await A(l,"set",[{tag:"member_add_mode",attrs:{},content:p}])},communityJoinApprovalMode:async(l,p)=>{await A(l,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:p}}]}])},communityFetchAllParticipating:s}},EP=n=>{let r=ie(n,"community"),o=ie(r,"description"),i,e;o&&(i=RA(o,"body"),e=o.attrs.id);let a=r.attrs.id?.includes("@")?r.attrs.id:Ft(r.attrs.id||"","g.us"),A=ie(r,"ephemeral")?.attrs.expiration,t=RA(r,"member_add_mode")==="all_member_add";return{id:a,subject:r.attrs.subject||"",subjectOwner:r.attrs.s_o,subjectTime:Number(r.attrs.s_t||0),size:mA(r,"participant").length,creation:Number(r.attrs.creation||0),owner:r.attrs.creator?oA(r.attrs.creator):void 0,desc:i,descId:e,linkedParent:ie(r,"linked_parent")?.attrs.jid||void 0,restrict:!!ie(r,"locked"),announce:!!ie(r,"announcement"),isCommunity:!!ie(r,"parent"),isCommunityAnnounce:!!ie(r,"default_sub_community"),joinApprovalMode:!!ie(r,"membership_approval_mode"),memberAddMode:t,participants:mA(r,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:RA(r,"addressing_mode")}};var uLe=n=>{let r={...E$,...n};return U$(r)},H$=uLe;var K$=H$;var BLe=Object.freeze({key:"whatsapp",label:"WhatsApp",connectionLabel:" Web \u5173\u8054\u8BBE\u5907"}),HS=class extends lo{constructor(r){super({...r,descriptor:BLe})}};import{chmod as Y$,mkdir as QLe,readdir as fLe}from"node:fs/promises";var yLe=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),mLe=6e4;function x$(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function SLe(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function DLe(n){let r=n;if(typeof r=="string"){if(!/^\d+$/.test(r))return null;r=Number(r)}else typeof r=="bigint"?r=Number(r):r&&typeof r=="object"&&(r=Number(r.valueOf()));return Number.isFinite(r)&&r>=0?r*1e3:null}async function pP(n){await QLe(n,{recursive:!0,mode:448}),await Y$(n,448);let r=await fLe(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(r.filter(o=>o.isFile()).map(o=>Y$(`${n}/${o.name}`,384).catch(()=>{})))}function wLe(n,r){let o=n.user??r.creds.me,i=oA(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):"WhatsApp\u673A\u5668\u4EBA"}}async function KS({authDir:n,onQr:r,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=K$,loadAuthState:t=U9}={}){if(!n||typeof r!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await pP(n);let s=Date.now(),{state:g,saveCreds:c}=await t(n),l=g.keys.set.bind(g.keys);g.keys.set=async j=>{await l(j),await pP(n)};let p=!1,B=!1,Q,f,y=Promise.resolve(),m=null,R=0,k=null,G=new Promise((j,F)=>{Q=j,f=F}),K=j=>{B||(B=!0,f(j))},x=async()=>{p||(p=!0,R+=1,K(x$()),await k?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},H=async()=>{p||(p=!0,R+=1,K(x$()),await k?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let j=++R,F=!1,T=A({auth:g,browser:tS.macOS("DeepSeek Harness"),logger:yLe,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=T;let V=()=>{!F||!g.creds.me||B||y.then(()=>{p||B||j!==R||!F||!g.creds.me||(B=!0,Q(wLe(T,g)))}).catch(U=>K(U))};T.ev.on("creds.update",()=>{p||j!==R||(y=y.then(async()=>{await c(),await pP(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),V())}),T.ev.on("connection.update",U=>{if(!(p||j!==R)&&(typeof U.qr=="string"&&U.qr&&r(U.qr),U.connection==="open"&&(F=!0,V()),U.connection==="close")){let b=SLe(U.lastDisconnect?.error);if(b===yt.restartRequired){k??=y.then(async()=>{p||j!==R||(await T.end(void 0).catch(()=>{}),!(p||j!==R)&&q())}).catch(pe=>K(pe)).finally(()=>{k=null});return}let L=b===yt.loggedOut,X=Object.assign(new Error(L?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:L?"logged-out":"connection-closed"});B?i?.({error:X,loggedOut:L}):K(X)}}),T.ev.on("messages.upsert",({messages:U,type:b})=>{if(!(p||j!==R||b!=="notify"&&b!=="append"||typeof o!="function"))for(let L of Array.isArray(U)?U:[]){if(b==="append"){let X=DLe(L?.messageTimestamp);if(X===null||X{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await x():e.addEventListener("abort",()=>void x(),{once:!0})),Object.freeze({get socket(){return m},ready:G,close:x,logout:H})}var j$=new Set(["image/jpeg","image/png","image/webp","image/gif"]),OLe=5*1024*1024,CP=15e3,MLe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],bLe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]);function _Le(n){let r=n;for(let o=0;o<5&&r&&typeof r=="object";o+=1){let i=MLe.find(e=>r[e]?.message);if(!i)return!1;if(bLe.has(i))return!0;r=r[i].message}return!1}function NLe(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 RLe(n){if(Number.isSafeInteger(n)&&n>=0)return n;let r;try{r=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(r)&&r>=0?r:void 0}async function kLe(n,r,{signal:o,maxBytes:i=OLe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(CP),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>r(n,"stream",{options:{signal:a}})),t=await new Promise((l,p)=>{let B=!1,Q=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",f),y(m),!0),f=()=>Q(p,a.reason);a.addEventListener("abort",f,{once:!0}),A.then(y=>{Q(l,y)||y?.destroy?.()},y=>Q(p,y)),a.aborted&&f()}).catch(l=>{throw o?.aborted?o.reason??l:e.aborted?new XA("image-download-failed",`WhatsApp image download timed out after ${CP} ms`,"\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"):l}),s=[],g=0,c=()=>t?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let l of t){a.throwIfAborted();let p=Buffer.from(l);if(g+=p.length,g>i)throw t.destroy?.(),new XA("image-too-large",`WhatsApp image exceeded ${i} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");s.push(p)}}catch(l){throw o?.aborted?o.reason??l:e.aborted?new XA("image-download-failed",`WhatsApp image stream timed out after ${CP} ms`,"\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"):l}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function vLe(n,r,o,{viewOnce:i=!1}={}){let e,a;if(!i&&r?.imageMessage&&r.imageMessage.viewOnce!==!0)e=r.imageMessage;else if(r?.documentMessage){let t=typeof r.documentMessage.mimetype=="string"?r.documentMessage.mimetype.toLowerCase():"";if(!j$.has(t))return null;e=r.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return j$.has(A)?{name:a,mediaType:A,size:RLe(e.fileLength),load:t=>kLe(n,o,t)}:null}function PLe(n,r,{download:o=YZ}={}){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"),t=n.key.fromMe===!0,s=t&&!A&&[i,e].some(y=>y&<(y,r));if(t&&!s)return null;let g=s?r:A?n.key.participant:i;if(typeof g!="string"||!g)return null;let c=_Le(n.message),l=Hr(n.message),p=NLe(l),B=Array.isArray(p?.mentionedJid)&&p.mentionedJid.some(y=>lt(y,r)),Q=typeof p?.participant=="string"&<(p.participant,r),f=vLe(n,l,o,{viewOnce:c});return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:TLe(l),images:f?[f]:[],addressed:!A||B||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s}}}var hP=class{#e=new Map;has(r){return this.#A(),this.#e.has(r)}remember(r){if(!(typeof r!="string"||!r))for(this.#A(),this.#e.set(r,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#A(){let r=Date.now();for(let[o,i]of this.#e)i>r||this.#e.delete(o)}},dP=class{#e;#A;#t=new Map;constructor(r,o){this.#e=r,this.#A=o}async sendText(r,o){await this.#r(r.jid);let i=null;for(let[e,a]of ii(o,4e3).entries())i=await this.#e.sendMessage(r.jid,{text:a},e===0&&r.quoted?{quoted:r.quoted}:void 0),this.#A.remember(i?.key?.id);return i}async sendTyping(r){!r.selfChat&&r.quoted?.key&&await this.#e.readMessages([r.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",r.jid),await this.#r(r.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",r.jid).catch(()=>{this.#r(r.jid)})},2e4);o.unref?.(),this.#t.set(r.jid,o)}async close(){let r=[...this.#t.keys()];await Promise.allSettled(r.map(o=>this.#r(o)))}async#r(r,o=!0){let i=this.#t.get(r);i&&clearInterval(i),this.#t.delete(r),o&&await this.#e.sendPresenceUpdate("paused",r).catch(()=>{})}};function GLe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var pd=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=GLe();#a=null;#i=null;#o=null;#c=null;#l=null;constructor({config:r,authDir:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=3e4,createSession:s=KS}){if(!r||!o||!i||!e||typeof s!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s}get status(){return structuredClone(this.#I)}async start(){return this.#I.ready&&this.#i?this.status:this.#l?this.#l:(this.#l=this.#p().finally(()=>{this.#l=null}),this.#l)}async#p(){await this.stop(),this.#I.startedAt=new Date().toISOString(),this.#I.connectionState="connecting",this.#I.lastError=null,await this.#t.ensureRunning(),this.#I.harnessReachable=!0;let r=new AbortController;this.#a=r;let o=new hP,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#s({authDir:this.#A,signal:r.signal,logger:this.#g,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async c=>{let l=PLe(c,this.#e.accountJid);!l||o.has(l.providerMessageId)||!this.#c||(this.#I.lastCheckedAt=Date.now(),await this.#c.accept(l))},onDisconnect:({error:c})=>{r.signal.aborted||(this.#I.ready=!1,this.#I.connectionState="failed",this.#I.lastError=c?.message??"WhatsApp Web connection closed")}});this.#i=a;let A,t=await Promise.race([a.ready,e,new Promise((c,l)=>{A=setTimeout(()=>l(new Error("WhatsApp Web did not connect in time")),this.#E)})]).finally(()=>clearTimeout(A));if(!lt(t.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new dP(a.socket,o);this.#o=s,this.#c=new HS({bot:s,harness:this.#t,state:this.#r,status:this.#I,logger:this.#g,replyTimeoutMs:this.#n,signal:r.signal});let g=Date.now();return this.#I.ready=!0,this.#I.connectionState="connected",this.#I.lastCheckedAt=g,this.#I.lastConnectedAt=g,this.status}catch(a){throw this.#I.ready=!1,this.#I.connectionState="failed",this.#I.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#i?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(r){if(!this.#I.ready||!this.#o){let o=new Error("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw o.code="test-target-unavailable",o}if(typeof r!="string"||!r.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#o.sendText({jid:this.#e.accountJid,selfChat:!0},r),{sent:!0}}async stop(){let r=this.#i,o=this.#o,i=this.#c;return this.#a?.abort(),this.#a=null,this.#i=null,this.#o=null,this.#c=null,await o?.close().catch(()=>{}),await r?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#I.ready=!1,this.#I.connectionState="idle",this.status}};var HLe=/^[a-f0-9-]{36}$/;function KLe(n,r){if(r!==void 0)return new URL(r);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-im WhatsApp requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function YLe(n){let r=Wn(n.dshHome??process.env.DSH_HOME??DE(ULe(),".dsh")),o=Wn(n.dataDir??DE(r,"integrations","dsh-whatsapp")),i=Wn(n.authDir??DE(o,"auth")),e=a=>{if(!HLe.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return Wn(i,a)};return{config:Wn(n.configPath??DE(o,"config.json")),bots:Wn(n.botsDir??DE(o,"bots")),workspaces:Wn(n.workspacesPath??DE(o,"workspaces.json")),authPath:e}}async function uP(n,r={},o={}){if(!n?.webServer)throw new TypeError("dsh-im WhatsApp requires ctx.webServer");let i=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,e=o.ConfigStore??rf,a=o.StateStore??of,A=o.HarnessClient??af,t=o.Controller??NC,s=o.Runtime??pd,g=o.createSession??KS,c=o.createConnectionSupervisor??eI,l=YLe(r),p=await new e(l.config).load(),B=Wn(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(F=>F.botId)),await Promise.all(y.map(F=>f.ensure(F.botId)));let m=typeof p.remove=="function"?Jr(p,{workspaces:f}):p,R=new Map,k=F=>Wn(l.bots,F,"state.json"),G=async F=>{let T=R.get(F);return T||(T=await new a(k(F)).load(),R.set(F,T)),T},K=zr(n,o.commandExecutor),x=new A({baseUrl:KLe(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.dshBin??"dsh",...K?{commandExecutor:K}:{}}),H=new t({configStore:m,authPath:l.authPath,createSession:g,logger:i,createRuntime:async({botId:F,config:T,authDir:V})=>{let U=await G(F);await f.ensure(F);let b=qr(x,{botId:F,workspaces:f,state:U});return new s({config:T,authDir:V,harness:b.harness,state:b.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??3e4,createSession:g,logger:{error:(...L)=>i.error?.(`[${F}]`,...L),warn:(...L)=>i.warn?.(`[${F}]`,...L),info:(...L)=>i.info?.(`[${F}]`,...L),debug:(...L)=>i.debug?.(`[${F}]`,...L)}})},deleteAuth:F=>FLe(l.authPath(F),{recursive:!0,force:!0}),deleteState:async({botId:F})=>{let T=R.get(F);if(R.delete(F),T&&typeof T.remove=="function")await T.remove();else try{await LLe(k(F))}catch(V){if(V?.code!=="ENOENT")throw V}}}),q=Vr(H,{workspaces:f,stateFor:G}),j=c({channel:"whatsapp",controller:q,harness:x,logger:i,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:q,ready:j.ready,async close(){await j.close(),await q.close(),x.stopManagedProcess()}}}import xLe from"qrcode";var J$="/whatsapp",pa=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),q$=Object.freeze(Object.values(pa)),jLe=new Set(["qrValue","accountJid","authDirectory"]);function fP(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function YS(n,r){return fP(n)&&Object.keys(n).every(o=>r.includes(o))}function BP(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function JLe(n,r){return fP(r)?[pa.status,pa.beginProvisioning].includes(n)?YS(r,[])?null:`${n} does not accept fields.`:[pa.pollProvisioning,pa.cancelProvisioning].includes(n)?YS(r,["attemptId"])&&BP(r.attemptId)?null:`${n} requires an attemptId.`:n===pa.reconnectBot?YS(r,["botId","sendTest"])&&BP(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.":n===pa.deleteBot?YS(r,["botId","confirm"])&&BP(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===pa.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown WhatsApp endpoint.":"Payload must be an object."}function wE(n){if(Array.isArray(n))return n.map(wE);if(!fP(n))return n;let r={};for(let[o,i]of Object.entries(n))jLe.has(o)||(r[o]=wE(i));return r}async function qLe(n){return xLe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function QP(n,r){return!n||typeof n.qrValue!="string"?wE(n):wE({...n,qrCodeDataUrl:await r(n.qrValue)})}async function xS(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await QP(o.provisioning,r)),wE(o)}function V$(n,{encodeQr:r=qLe}={}){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(()=>r(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(!q$.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let t=JLe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===pa.status)s=await xS(await n.status(),i);else if(e===pa.beginProvisioning)s=await QP(await n.startProvisioning(),i);else if(e===pa.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 QP(g,i)}else if(e===pa.cancelProvisioning)s=wE(await n.cancelProvisioning(a.attemptId));else if(e===pa.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 xS(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(p=>p?.botId===a.botId&&p.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let p=new Error("Connection test is unavailable");throw p.code="test-target-unavailable",p}await n.sendConnectionTest(a.botId)}catch(p){c=p}s={...s,testMessage:Ot(c)}}}else if(e===pa.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await xS(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await xS(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=Xr(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 jS(n,r,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(J$,V$(r,o),{authority:Wr(i)})}async function z$(n,r={}){if(r?.controller)return jS(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await uP(n,r,r.internals??{}),i=jS(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close WhatsApp Web connections"),i}var VLe="dsh-im-host",zLe=["connection","credentials","webServer","typertGateway"];function Zn(n,r){let o=n[r]??{};return n.rpcAuthority===void 0?o:{...o,rpcAuthority:n.rpcAuthority}}function WLe(n={}){let r=n.applyFeishu??J1,o=n.applyWeixin??oj,i=n.applyDingtalk??dG,e=n.applyWecom??K3,a=n.applyQq??r3,A=n.applySlack??d3,t=n.applyTelegram??w3,s=n.applyDiscord??bG,g=n.applyWhatsapp??z$;return Object.freeze({name:VLe,inject:zLe,async apply(c,l={}){await r(c,Zn(l,"feishu")),await o(c,Zn(l,"weixin")),await i(c,Zn(l,"dingtalk")),await e(c,Zn(l,"wecom")),await a(c,Zn(l,"qq")),await A(c,Zn(l,"slack")),await t(c,Zn(l,"telegram")),await s(c,Zn(l,"discord")),await g(c,Zn(l,"whatsapp"))}})}async function aEA(n,r={}){return WLe().apply(n,r)}export{aEA as apply,WLe as createImHostPlugin,zLe as inject,VLe as name}; /*! Bundled license information: mime-db/index.js: diff --git a/plugin-src/host/channels/dingtalk/production.mjs b/plugin-src/host/channels/dingtalk/production.mjs index ad88e79..d29778a 100644 --- a/plugin-src/host/channels/dingtalk/production.mjs +++ b/plugin-src/host/channels/dingtalk/production.mjs @@ -84,7 +84,7 @@ export async function createProductionController(ctx, config = {}, internals = { const harness = new Harness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), autostart: false, dshBin: config.dshBin ?? 'dsh', ...(commandExecutor ? { commandExecutor } : {}), diff --git a/plugin-src/host/channels/feishu/production.mjs b/plugin-src/host/channels/feishu/production.mjs index 1bddd61..e7eeb6e 100644 --- a/plugin-src/host/channels/feishu/production.mjs +++ b/plugin-src/host/channels/feishu/production.mjs @@ -110,7 +110,7 @@ export async function createProductionController(ctx, config = {}, internals = { const harness = new Harness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), // This plugin is already hosted by a running DSH process. Starting a // second DSH would create a competing server and lifecycle. autostart: false, diff --git a/plugin-src/host/channels/qq/production.mjs b/plugin-src/host/channels/qq/production.mjs index 666525f..7b60ef8 100644 --- a/plugin-src/host/channels/qq/production.mjs +++ b/plugin-src/host/channels/qq/production.mjs @@ -75,7 +75,7 @@ export async function createProductionController(ctx, config = {}, internals = { const harness = new Harness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), autostart: false, dshBin: config.dshBin ?? 'dsh', ...(commandExecutor ? { commandExecutor } : {}), diff --git a/plugin-src/host/channels/shared/production.mjs b/plugin-src/host/channels/shared/production.mjs index ea9b090..119e4d3 100644 --- a/plugin-src/host/channels/shared/production.mjs +++ b/plugin-src/host/channels/shared/production.mjs @@ -69,7 +69,7 @@ export async function createTokenProductionController(ctx, config, internals, de const harness = new ResolvedHarness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), autostart: false, dshBin: config.dshBin ?? 'dsh', ...(commandExecutor ? { commandExecutor } : {}), diff --git a/plugin-src/host/channels/slack/production.mjs b/plugin-src/host/channels/slack/production.mjs index 17c6181..0e80e38 100644 --- a/plugin-src/host/channels/slack/production.mjs +++ b/plugin-src/host/channels/slack/production.mjs @@ -54,7 +54,7 @@ export async function createProductionController(ctx, config = {}, internals = { const harness = new ResolvedHarness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), autostart: false, dshBin: config.dshBin ?? 'dsh', ...(commandExecutor ? { commandExecutor } : {}), diff --git a/plugin-src/host/channels/wecom/production.mjs b/plugin-src/host/channels/wecom/production.mjs index fe9c3f7..dab14cc 100644 --- a/plugin-src/host/channels/wecom/production.mjs +++ b/plugin-src/host/channels/wecom/production.mjs @@ -78,7 +78,7 @@ export async function createProductionController(ctx, config = {}, internals = { const harness = new Harness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), autostart: false, dshBin: config.dshBin ?? 'dsh', ...(commandExecutor ? { commandExecutor } : {}), diff --git a/plugin-src/host/channels/weixin/production.mjs b/plugin-src/host/channels/weixin/production.mjs index 7aaa340..15bf907 100644 --- a/plugin-src/host/channels/weixin/production.mjs +++ b/plugin-src/host/channels/weixin/production.mjs @@ -78,7 +78,7 @@ export async function createProductionController(ctx, config = {}, internals = { const harness = new Harness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), autostart: false, dshBin: config.dshBin ?? 'dsh', ...(commandExecutor ? { commandExecutor } : {}), diff --git a/plugin-src/host/channels/whatsapp/production.mjs b/plugin-src/host/channels/whatsapp/production.mjs index cb41157..f1b7c6e 100644 --- a/plugin-src/host/channels/whatsapp/production.mjs +++ b/plugin-src/host/channels/whatsapp/production.mjs @@ -81,7 +81,7 @@ export async function createProductionController(ctx, config = {}, internals = { const harness = new Harness({ baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl), workspace: defaultWorkspace, - agentPreset: config.agentPreset ?? 'standard', + ...(config.agentPreset == null ? {} : { agentPreset: config.agentPreset }), autostart: false, dshBin: config.dshBin ?? 'dsh', ...(commandExecutor ? { commandExecutor } : {}), diff --git a/src/channels/shared/harness-client.mjs b/src/channels/shared/harness-client.mjs index ef45b55..3d6bb7a 100644 --- a/src/channels/shared/harness-client.mjs +++ b/src/channels/shared/harness-client.mjs @@ -327,7 +327,7 @@ export class HarnessClient { constructor({ baseUrl, workspace, - agentPreset = 'standard', + agentPreset, autostart = false, dshBin = 'dsh', fetchImpl = fetch, @@ -354,7 +354,8 @@ export class HarnessClient { } this.#baseUrl = new URL(baseUrl); this.#workspace = workspace; - this.#agentPreset = agentPreset; + // Keep an omitted preset absent so session.create resolves the Host's current default. + this.#agentPreset = agentPreset ?? undefined; this.#autostart = autostart; this.#dshBin = dshBin; this.#fetch = fetchImpl; @@ -458,10 +459,9 @@ export class HarnessClient { async createSession(options = {}) { await this.ensureRunning(options); const workspaceId = await this.workspaceId(options); - const created = await this.rpc('session.create', { - workspaceId, - agentPreset: this.#agentPreset, - }, 30_000, options); + const payload = { workspaceId }; + if (this.#agentPreset !== undefined) payload.agentPreset = this.#agentPreset; + const created = await this.rpc('session.create', payload, 30_000, options); return created.sessionId; } diff --git a/test/channels/dingtalk/production.test.mjs b/test/channels/dingtalk/production.test.mjs index 70acec4..0ce6c51 100644 --- a/test/channels/dingtalk/production.test.mjs +++ b/test/channels/dingtalk/production.test.mjs @@ -58,6 +58,7 @@ test('production assembly keeps secrets in credentials and creates per-bot runti assert.equal(seen.controllerOptions.credentials, credentials); assert.equal(seen.harnessOptions.baseUrl.href, 'http://127.0.0.1:3080/'); assert.equal(seen.harnessOptions.autostart, false); + assert.equal(Object.hasOwn(seen.harnessOptions, 'agentPreset'), false); const runtime = await seen.controllerOptions.createRuntime({ botId: 'dt_abc', config: { botId: 'dt_abc', clientId: 'dingabc' }, @@ -71,4 +72,21 @@ test('production assembly keeps secrets in credentials and creates per-bot runti assert.equal(seen.supervisorClosed, true); assert.equal(seen.controllerClosed, true); assert.equal(seen.harnessStopped, true); + + const productionWithPreset = await createProductionController({ + credentials, + webServer: { port: 3080 }, + logger: () => console, + }, { dataDir: directory, agentPreset: 'router-standard' }, { + ConfigStore, + DeviceAuth, + StateStore, + HarnessClient: Harness, + Controller, + Runtime, + createConnectionSupervisor: () => supervisor, + }); + + assert.equal(seen.harnessOptions.agentPreset, 'router-standard'); + await productionWithPreset.close(); }); diff --git a/test/channels/weixin/harness-client.test.mjs b/test/channels/weixin/harness-client.test.mjs index d7f46e4..7a6ff66 100644 --- a/test/channels/weixin/harness-client.test.mjs +++ b/test/channels/weixin/harness-client.test.mjs @@ -45,6 +45,34 @@ test('all legacy channel clients now use the shared Harness RPC transport', asyn } }); +test('HarnessClient lets the Host resolve an omitted agent preset and forwards an explicit override', async () => { + const createPayload = async (options = {}) => { + const client = new HarnessClient({ + baseUrl: 'http://127.0.0.1:3080', + workspace: '/tmp/default-workspace', + ...options, + }); + let payload; + client.ensureRunning = async () => true; + client.workspaceId = async () => 'workspace-one'; + client.rpc = async (method, value) => { + assert.equal(method, 'session.create'); + payload = value; + return { sessionId: 'session-one' }; + }; + + assert.equal(await client.createSession(), 'session-one'); + return payload; + }; + + assert.deepEqual(await createPayload(), { workspaceId: 'workspace-one' }); + assert.deepEqual(await createPayload({ agentPreset: 'router-standard' }), { + workspaceId: 'workspace-one', + agentPreset: 'router-standard', + }); + assert.deepEqual(await createPayload({ agentPreset: null }), { workspaceId: 'workspace-one' }); +}); + test('HarnessClient lists only absolute workspace paths', async () => { const client = new HarnessClient({ baseUrl: 'http://127.0.0.1:3080', diff --git a/test/compact-command.test.mjs b/test/compact-command.test.mjs index b7408bb..8f65d2c 100644 --- a/test/compact-command.test.mjs +++ b/test/compact-command.test.mjs @@ -9,6 +9,17 @@ import { } from '../src/channels/shared/harness-client.mjs'; import { createHarnessCommandExecutor } from '../plugin-src/host/harness-command-executor.mjs'; +const PRODUCTION_FILES = [ + 'plugin-src/host/channels/feishu/production.mjs', + 'plugin-src/host/channels/weixin/production.mjs', + 'plugin-src/host/channels/dingtalk/production.mjs', + 'plugin-src/host/channels/wecom/production.mjs', + 'plugin-src/host/channels/qq/production.mjs', + 'plugin-src/host/channels/slack/production.mjs', + 'plugin-src/host/channels/shared/production.mjs', + 'plugin-src/host/channels/whatsapp/production.mjs', +]; + function state(sessionId = 'session-one') { return { sessionFor: () => sessionId }; } @@ -142,17 +153,7 @@ test('Host command executor invokes the commands Typert endpoint with the Sessio }); test('all nine production channels receive the Host command executor', async () => { - const productionFiles = [ - 'plugin-src/host/channels/feishu/production.mjs', - 'plugin-src/host/channels/weixin/production.mjs', - 'plugin-src/host/channels/dingtalk/production.mjs', - 'plugin-src/host/channels/wecom/production.mjs', - 'plugin-src/host/channels/qq/production.mjs', - 'plugin-src/host/channels/slack/production.mjs', - 'plugin-src/host/channels/shared/production.mjs', - 'plugin-src/host/channels/whatsapp/production.mjs', - ]; - for (const path of productionFiles) { + for (const path of PRODUCTION_FILES) { const source = await readFile(new URL(`../${path}`, import.meta.url), 'utf8'); assert.match(source, /createHarnessCommandExecutor\(ctx, internals\.commandExecutor\)/, path); assert.match(source, /commandExecutor \? \{ commandExecutor \} : \{\}/, path); @@ -169,3 +170,27 @@ test('all nine production channels receive the Host command executor', async () assert.match(source, /'typertGateway'/, channel); } }); + +test('all nine production channels defer an omitted agent preset to the Harness Host', async () => { + for (const path of PRODUCTION_FILES) { + const source = await readFile(new URL(`../${path}`, import.meta.url), 'utf8'); + assert.doesNotMatch(source, /agentPreset:\s*config\.agentPreset\s*\?\?\s*['"]standard['"]/, path); + assert.match( + source, + /\.\.\.\(config\.agentPreset == null \? \{\} : \{ agentPreset: config\.agentPreset \}\)/, + path, + ); + } + + for (const channel of ['telegram', 'discord']) { + const source = await readFile( + new URL(`../plugin-src/host/channels/${channel}/production.mjs`, import.meta.url), + 'utf8', + ); + assert.match( + source, + /createTokenProductionController\(ctx, config, internals,/, + `${channel} must delegate to the shared production assembly`, + ); + } +});