easemob-websdk 5.1.3 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-types.d.ts +2 -2
- package/chat-client.d.ts +17 -2
- package/chunks/chat-manager-BB7wYWYG.js +2 -0
- package/chunks/chat-manager-auF_3s3R.cjs +1 -0
- package/chunks/common-Cg-lTASK.cjs +1 -0
- package/chunks/common-gbNWJrBc.js +1 -0
- package/chunks/{group-user-info-resolver-B-dyr__b.cjs → group-user-info-resolver-BNwtC7dY.cjs} +1 -1
- package/chunks/{group-user-info-resolver-D6AQAHEE.js → group-user-info-resolver-rs5Fnr0l.js} +1 -1
- package/chunks/index-BUNbI8gf.cjs +1 -0
- package/chunks/index-BxMCMoWN.js +1 -0
- package/chunks/index-C7fO2X0x.cjs +1 -0
- package/chunks/index-C_EMU0-3.js +1 -0
- package/chunks/index-CsqE2tfH.js +1 -0
- package/chunks/index-DeJuR3uW.cjs +1 -0
- package/chunks/index-Dknccp9Q.js +1 -0
- package/chunks/index-P1vnLSK2.cjs +1 -0
- package/chunks/multibody-content-BHb-Au8Q.js +1 -0
- package/chunks/multibody-content-BmdQukoX.cjs +1 -0
- package/chunks/{push-manager-CSIKhoPe.js → push-manager-BO3xq-7O.js} +1 -1
- package/chunks/{push-manager-D7RDsKuv.cjs → push-manager-DMI0G9v9.cjs} +1 -1
- package/chunks/reflection-proto-codec-B1apL0ws.js +1 -0
- package/chunks/reflection-proto-codec-CYglS_mx.cjs +1 -0
- package/chunks/session-list-query-DMe2GZ4v.cjs +1 -0
- package/chunks/session-list-query-Inseic9m.js +1 -0
- package/chunks/{user-info-DH3aE1gm.cjs → user-info-B5St7axd.cjs} +1 -1
- package/chunks/{user-info-7QzMa7bR.js → user-info-BkqJHgja.js} +1 -1
- package/core/index.d.ts +1 -1
- package/core/message/attachment-downloader.d.ts +4 -1
- package/core/message/message-sender.d.ts +19 -4
- package/core/message/prepare-text-translation.d.ts +7 -0
- package/index.cjs +1 -1
- package/index.d.ts +3 -2
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-manager.d.ts +128 -7
- package/managers/chat-thread/index.cjs +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chatroom/index.cjs +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.cjs +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.cjs +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.cjs +1 -1
- package/managers/user-info/index.js +1 -1
- package/message/combine-payload-codec.d.ts +2 -2
- package/message/combine-payload-file.d.ts +11 -0
- package/message/create-message.d.ts +16 -4
- package/message/create-multibody-message.d.ts +31 -0
- package/message/message-snapshot.d.ts +2 -1
- package/message/multibody-content.d.ts +35 -0
- package/message/translations.d.ts +7 -0
- package/package.json +1 -1
- package/platform/image/miniapp-image-processor.d.ts +10 -6
- package/protocol/msync/codec.d.ts +3 -0
- package/protocol/msync/message-payload-decoder.d.ts +5 -1
- package/protocol/session-list/payload-decoder.d.ts +2 -2
- package/types/chat-manager.d.ts +2 -2
- package/types/conversation.d.ts +2 -2
- package/types/index.d.ts +33 -9
- package/types/message-create.d.ts +130 -2
- package/upload/attachment-uploader.d.ts +8 -0
- package/validators/message-create.d.ts +25 -2
- package/chunks/chat-manager-BI-6bEor.cjs +0 -1
- package/chunks/chat-manager-nXOTpJ01.js +0 -2
- package/chunks/common-DHQukb7J.js +0 -1
- package/chunks/common-tHGz9VBk.cjs +0 -1
- package/chunks/index-CneY58NJ.js +0 -1
- package/chunks/index-DJPAjXAp.cjs +0 -1
- package/chunks/index-DtWkVcfb.cjs +0 -1
- package/chunks/index-DxjmfFL7.js +0 -1
- package/chunks/reflection-proto-codec-7r8Sei3y.js +0 -1
- package/chunks/reflection-proto-codec-CwrIKT1L.cjs +0 -1
- package/chunks/session-list-query-C3iQvQxK.cjs +0 -1
- package/chunks/session-list-query-Cdpiw_IZ.js +0 -1
package/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{E as e,g as t,u as s,v as n,P as r,a as i,w as o,l as a,x as c,y as d,I as l,h as u,q as h,z as p,B as m,H as f,D as g,F as y,G as I,J as v,r as C,K as S,L as E,M as b,O as T,Q as A,T as w,W as N,V as M,k as R,o as _,A as D,s as U,S as L,X as O,U as k,p as P,Y as x,Z as F,_ as B,$ as q,a0 as K,a1 as G,a2 as V,a3 as H,a4 as z,a5 as j,a6 as W,a7 as Q,a8 as $,a9 as Y,aa as J,ab as X,ac as Z,ad as ee,ae as te,af as se,ag as ne,ah as re,R as ie,t as oe,ai as ae,aj as ce,ak as de,al as le,am as ue,an as he,ao as pe,ap as me,aq as fe,ar as ge,as as ye,at as Ie,au as ve,av as Ce,aw as Se,ax as Ee,ay as be,az as Te,aA as Ae,aB as we,aC as Ne,aD as Me,aE as Re,aF as _e,aG as De,m as Ue,C as Le,aH as Oe,aI as ke,aJ as Pe}from"./chunks/common-DHQukb7J.js";import{j as xe,aK as Fe}from"./chunks/common-DHQukb7J.js";import{a as Be,b as qe,g as Ke,I as Ge,c as Ve,v as He,d as ze,e as je,f as We,h as Qe,i as $e,M as Ye,j as Je,k as Xe,V as Ze}from"./chunks/chat-manager-nXOTpJ01.js";import{C as et}from"./chunks/chat-manager-nXOTpJ01.js";import{i as tt,a as st,L as nt,e as rt,b as it}from"./chunks/reflection-proto-codec-7r8Sei3y.js";import{l as ot}from"./chunks/light-DImBnNes.js";import{G as at,C as ct,a as dt,b as lt,L as ut}from"./chunks/event-system-DguqwFpc.js";import{P as ht}from"./chunks/event-system-DguqwFpc.js";import{n as pt,J as mt}from"./chunks/index-DxjmfFL7.js";import{G as ft,a as gt}from"./chunks/index-DxjmfFL7.js";import{n as yt}from"./chunks/profile-version-DLMz8lqW.js";import{m as It}from"./chunks/group-user-info-resolver-D6AQAHEE.js";import{p as vt,a as Ct,m as St,b as Et,t as bt}from"./chunks/session-list-query-Cdpiw_IZ.js";import{s as Tt,a as At,i as wt}from"./chunks/cache-utils-B99glc0H.js";import{z as Nt}from"zod";import{c as Mt}from"./chunks/query-params-Bu3Xq4b6.js";import{r as Rt,R as _t}from"./chunks/index-CneY58NJ.js";import{C as Dt}from"./chunks/index-CneY58NJ.js";import{ChatThread as Ut,ChatThreadManager as Lt}from"./managers/chat-thread/index.js";import{ChatRoom as Ot,ChatRoomManager as kt}from"./managers/chatroom/index.js";import{PresenceManager as Pt}from"./managers/presence/index.js";import{P as xt}from"./chunks/push-manager-CSIKhoPe.js";import{UserInfoManager as Ft}from"./managers/user-info/index.js";const Bt="onChatRoomDestroyed",qt="onMembersJoined",Kt="onMembersExited",Gt="onRemovedFromChatRoom",Vt="onMuteListAdded",Ht="onMuteListRemoved",zt="onAllowListAdded",jt="onAllowListRemoved",Wt="onAllMemberMuteStateChanged",Qt="onAdminAdded",$t="onAdminRemoved",Yt="onOwnerChanged",Jt="onAnnouncementChanged",Xt="onChatRoomInfoChanged",Zt="onAttributesUpdate",es="onAttributesRemoved",ts={ORIGINAL:"original",LARGE:"large"},ss={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function ns(e){return"object"==typeof e.stream&&null!==e.stream}const rs=0,is=1,os=2,as=3,cs=4,ds=0,ls=1,us=2,hs=3,ps=4,ms=5,fs=6,gs=7,ys=8,Is=0,vs=1,Cs=2,Ss=3,Es=4,bs=5,Ts=6,As=7,ws=8,Ns=0,Ms=1,Rs=2,_s=3,Ds=4,Us=0,Ls=1,Os=2,ks=3,Ps=5,xs=0,Fs=1,Bs=2,qs=0,Ks=0,Gs=2,Vs=0,Hs=1,zs=2,js=3,Ws=4,Qs=5,$s=6,Ys=7,Js=8,Xs=9,Zs=10,en=11,tn=12,sn=13,nn=14,rn=15,on=16,an=17,cn=18,dn=19,ln=20,un=1,hn=2,pn=3,mn=4,fn=5,gn=6,yn=7,In=8,vn="Sorry, user register limit",Cn="Sorry, user register rate limit",Sn="Sorry, token expired",En="Sorry, token or password does not match login info",bn="Sorry, user not found",Tn="Sorry, the app month live count limit",An="Sorry, the app day live count limit",wn="Sorry, the app online count limit",Nn={[Hs]:e.AUTH_UNAUTHORIZED,[zs]:e.AUTH_UNAUTHORIZED,[js]:e.VALIDATION_REQUIRED,[Ws]:e.VALIDATION_INVALID_FORMAT,[Qs]:e.CONNECTION_WEBSOCKET_ERROR,[$s]:e.AUTH_TOKEN_EXPIRED,[Ys]:e.AUTH_FORBIDDEN,[dn]:e.AUTH_FORBIDDEN,[Js]:e.CONNECTION_WEBSOCKET_ERROR,[Xs]:e.UNKNOWN,[Zs]:e.UNKNOWN,[en]:e.AUTH_BIND_ANOTHER_DEVICE,[tn]:e.AUTH_FORBIDDEN,[sn]:e.AUTH_LOGIN_TOO_MANY_DEVICES,[nn]:e.SERVICE_LIMIT_EXCEEDED,[rn]:e.AUTH_USER_MUTED,[on]:e.UNKNOWN,[an]:e.UNKNOWN,[cn]:e.MESSAGE_DECODE_FAILED,[ln]:e.USER_DEVICE_CHANGED},Mn=/* @__PURE__ */new Set([Hs,zs,js,Ws,$s,Ys,dn,Xs,Zs,en,tn,sn,nn,rn,on,an,cn,ln]),Rn={[vn]:e.SERVICE_LIMIT_EXCEEDED,[Cn]:e.SERVICE_LIMIT_EXCEEDED,[Sn]:e.AUTH_TOKEN_EXPIRED,[En]:e.AUTH_UNAUTHORIZED,[bn]:e.AUTH_UNAUTHORIZED,blocked:e.MESSAGE_BLOCKED_BY_RECIPIENT,"group not found":e.GROUP_NOT_EXIST,"illegal chatroom tag":e.VALIDATION_REQUIRED,"not in group or chatroom":e.GROUP_NOT_JOINED,"exceed recall time limit":e.MESSAGE_RECALL_TIME_LIMIT,"message recall disabled":e.SERVICE_NOT_ENABLED,"group ack not open":e.SERVICE_NOT_ENABLED,"group ack msg permission denied":e.GROUP_PERMISSION_DENIED,"the message has expired":e.MESSAGE_EXPIRED,"limit send group ack msg":e.SERVICE_LIMIT_EXCEEDED,"not in group or chatroom white list":e.MESSAGE_ILLEGAL_WHITELIST,nonroster:e.USER_NOT_ON_ROSTER,"group is disabled":e.GROUP_DISABLED,"roaming is not open":e.SERVICE_NOT_ENABLED,"Sorry, message does not exist":e.VALIDATION_REQUIRED,"Sorry, edit limit reached":e.SERVICE_LIMIT_EXCEEDED,"Sorry, You do not have permission":e.AUTH_FORBIDDEN,"Sorry, format is incorrect":e.VALIDATION_REQUIRED,"Sorry, edit is not available":e.SERVER_SERVING_DISABLED,"Sorry, edit fail":e.MESSAGE_EDIT_FAILED},_n=[["limit directed users",e.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.AUTH_FORBIDDEN]],Dn={[Tn]:e.SERVICE_LIMIT_EXCEEDED,[An]:e.SERVICE_LIMIT_EXCEEDED,[wn]:e.SERVICE_LIMIT_EXCEEDED,"sensitive words":e.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"blocked by mod_antispam":e.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"user is mute":e.USER_MUTED_BY_ADMIN,"traffic limit":e.MESSAGE_CURRENT_LIMITING,"Sorry, data is too large":e.MESSAGE_SIZE_LIMIT},Un=(t,s)=>{if("number"!=typeof t)return{code:e.UNKNOWN,retryable:!0};const n=((t,s)=>{if(s){if(t===Hs){const t=Rn[s];if(void 0!==t)return t;for(const[e,n]of _n)if(s.includes(e))return n;try{const t=JSON.parse(s);if("moderation"===t.error_type)return e.THIRD_MODERATION_FAILED;if("string"==typeof t.error_type)return e.THIRD_DEFAULT_FAILED}catch{}return}return t===Ys?Dn[s]:t===dn?e.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===rn?e.AUTH_USER_MUTED:void 0}})(t,s),r=Nn[t]??e.UNKNOWN;return{code:n??r,retryable:!Mn.has(t)}},Ln={[e.SERVICE_LIMIT_EXCEEDED]:"Message operation exceeded a service limit",[e.AUTH_TOKEN_EXPIRED]:"Message cannot be sent because the authentication token expired",[e.VALIDATION_REQUIRED]:"Message cannot be sent because the request is invalid",[e.AUTH_UNAUTHORIZED]:"Message cannot be sent because authentication failed",[e.AUTH_FORBIDDEN]:"Message operation is forbidden",[e.AUTH_BIND_ANOTHER_DEVICE]:"Message cannot be sent because the account is bound to another device",[e.AUTH_LOGIN_TOO_MANY_DEVICES]:"Message cannot be sent because the account is logged in on too many devices",[e.AUTH_USER_MUTED]:"Message cannot be sent because the user is muted in the group or chat room",[e.MESSAGE_BLOCKED_BY_RECIPIENT]:"Message cannot be sent because you are blocked by the recipient",[e.USER_MUTED_BY_ADMIN]:"Message cannot be sent because the user is globally muted",[e.USER_DEVICE_CHANGED]:"Message cannot be sent because the current device has changed",[e.USER_NOT_ON_ROSTER]:"Message cannot be sent because the recipient is not in your contact list",[e.CONNECTION_WEBSOCKET_ERROR]:"Message cannot be sent because the server is unreachable",[e.SERVER_SERVING_DISABLED]:"Message editing is not available",[e.MESSAGE_DECODE_FAILED]:"Message processing failed",[e.MESSAGE_INCLUDE_ILLEGAL_CONTENT]:"Message contains prohibited content",[e.MESSAGE_SEND_TRAFFIC_LIMIT]:"Message sending traffic limit exceeded",[e.MESSAGE_RECALL_TIME_LIMIT]:"The message recall time limit has been exceeded",[e.SERVICE_NOT_ENABLED]:"The required messaging service is not enabled",[e.MESSAGE_EXPIRED]:"The message has expired",[e.MESSAGE_ILLEGAL_WHITELIST]:"The user is not in the group or chat room allowlist",[e.MESSAGE_EXTERNAL_LOGIC_BLOCKED]:"The message was blocked by external logic",[e.MESSAGE_CURRENT_LIMITING]:"Message sending rate limit exceeded",[e.MESSAGE_SIZE_LIMIT]:"Message size exceeds the limit",[e.MESSAGE_EDIT_FAILED]:"Message editing failed",[e.GROUP_NOT_JOINED]:"The user is not in the group or chat room",[e.GROUP_PERMISSION_DENIED]:"The user does not have permission to perform this group message operation",[e.GROUP_NOT_EXIST]:"The group does not exist",[e.GROUP_DISABLED]:"The group is disabled",[e.THIRD_MODERATION_FAILED]:"The message was rejected by content moderation",[e.THIRD_DEFAULT_FAILED]:"The message was rejected by a third-party service"},On=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let s=0;s<e.length;s+=1){let n=e.charCodeAt(s);if(n>=55296&&n<=56319&&s+1<e.length){const t=e.charCodeAt(s+1);t>=56320&&t<=57343&&(n=65536+(n-55296<<10)+(t-56320),s+=1)}n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):n<=65535?t.push(224|n>>12,128|n>>6&63,128|63&n):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return new Uint8Array(t)},kn=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0;s<e.length;s+=1){const n=e[s]??0;if(n<128){t+=String.fromCharCode(n);continue}if(n>=192&&n<224){const r=e[s+1]??0;t+=String.fromCharCode((31&n)<<6|63&r),s+=1;continue}if(n>=224&&n<240){const r=e[s+1]??0,i=e[s+2]??0;t+=String.fromCharCode((15&n)<<12|(63&r)<<6|63&i),s+=2;continue}const r=((7&n)<<18|(63&(e[s+1]??0))<<12|(63&(e[s+2]??0))<<6|63&(e[s+3]??0))-65536;t+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),s+=3}return t};class Pn{constructor(){this.lastEventKey=null}normalize(e,t){const s=(e=>{switch(e){case Be.CONNECTING:case Be.RECONNECTING:return qe.CONNECTING;case Be.CONNECTED:return qe.CONNECTED;case Be.DISCONNECTED:return qe.DISCONNECTED;case Be.RECONNECT_FAILED:return qe.RECONNECT_FAILED;default:return null}})(e);if(!s)return null;const n=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(s,t);return this.lastEventKey===n?null:(this.lastEventKey=n,{eventName:s,payload:t})}reset(){this.lastEventKey=null}}const xn={web:s.WEB,"mp-weixin":s.WECHAT_MINIAPP,"mp-alipay":s.ALIPAY_MINIAPP,"mp-baidu":s.BAIDU_MINIAPP,"mp-toutiao":s.TOUTIAO_MINIAPP,"mp-lark":s.LARK_MINIAPP,"mp-qq":s.QQ_MINIAPP,"mp-kuaishou":s.KUAISHOU_MINIAPP,"mp-jd":s.JD_MINIAPP,"mp-360":s.MINIAPP_360,"mp-harmony":s.HARMONY_MINIAPP,"quickapp-webview":s.QUICKAPP,"quickapp-webview-union":s.QUICKAPP,"quickapp-webview-huawei":s.QUICKAPP},Fn=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Bn=e=>(e=>Fn(e,"canIUse")&&Fn(e,"getSystemInfo"))(e)||(e=>Fn(e,"request")&&Fn(e,"connectSocket"))(e),qn=e=>Fn(e,"request")&&Fn(e,"connectSocket")&&Fn(e,"uploadFile"),Kn=(e,t)=>t===s.WECHAT_MINIAPP?e.wx:t===s.QQ_MINIAPP?e.qq:t===s.TOUTIAO_MINIAPP?e.tt:t===s.BAIDU_MINIAPP?e.swan:t===s.ALIPAY_MINIAPP?e.my:t===s.DINGTALK_MINIAPP?e.dd:t===s.JD_MINIAPP?e.jd:t===s.KUAISHOU_MINIAPP?e.ks:t===s.UNIAPP?e.uni:void 0,Gn=e=>{const t=e?.miniGlobal;return Bn(t)?t:e},Vn=e=>{const t=Gn(e);return qn(t)?t:void 0},Hn=e=>void 0!==e.window&&void 0!==e.document,zn=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),jn=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(Bn(t))return!0;try{if(!Fn(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},Wn=e=>qn(e.wx)?s.WECHAT_MINIAPP:qn(e.my)?s.ALIPAY_MINIAPP:qn(e.dd)?s.DINGTALK_MINIAPP:qn(e.swan)?s.BAIDU_MINIAPP:qn(e.tt)?s.TOUTIAO_MINIAPP:qn(e.qq)?s.QQ_MINIAPP:qn(e.jd)?s.JD_MINIAPP:qn(e.ks)?s.KUAISHOU_MINIAPP:void 0,Qn=e=>void 0!==Wn(e),$n=e=>{const t=Wn(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),n=t?.uniPlatform;if("string"==typeof n)return xn[n]??s.UNIAPP}catch{return s.UNIAPP}return Hn(e)?s.WEB:s.UNIAPP},Yn=(e,t)=>{const s=Vn(Kn(e,t));if(s)return s;const n=Vn(e.uni);return n||(e.uni??e)},Jn=(e,n)=>{const r=e??t();if(n){const e=n===s.UNIAPP||jn(r),t=e?$n(r):n;return{platform:n,hostPlatform:t,framework:e?"uniapp":Hn(r)?"web":"native",global:e?Yn(r,t):Gn(Kn(r,n))??r}}if(jn(r)){const e=$n(r);return{platform:s.UNIAPP,hostPlatform:e,framework:"uniapp",global:Yn(r,e)}}return Bn(r.swan)?{platform:s.BAIDU_MINIAPP,hostPlatform:s.BAIDU_MINIAPP,framework:"native",global:Gn(r.swan)??r.swan}:Bn(r.tt)?{platform:s.TOUTIAO_MINIAPP,hostPlatform:s.TOUTIAO_MINIAPP,framework:"native",global:Gn(r.tt)??r.tt}:Bn(r.dd)?{platform:s.DINGTALK_MINIAPP,hostPlatform:s.DINGTALK_MINIAPP,framework:"native",global:Gn(r.dd)??r.dd}:Bn(r.my)?{platform:s.ALIPAY_MINIAPP,hostPlatform:s.ALIPAY_MINIAPP,framework:"native",global:Gn(r.my)??r.my}:Bn(r.wx)?{platform:s.WECHAT_MINIAPP,hostPlatform:s.WECHAT_MINIAPP,framework:"native",global:Gn(r.wx)??r.wx}:Bn(r.qq)?{platform:s.QQ_MINIAPP,hostPlatform:s.QQ_MINIAPP,framework:"native",global:Gn(r.qq)??r.qq}:Bn(r.jd)?{platform:s.JD_MINIAPP,hostPlatform:s.JD_MINIAPP,framework:"native",global:Gn(r.jd)??r.jd}:Bn(r.ks)?{platform:s.KUAISHOU_MINIAPP,hostPlatform:s.KUAISHOU_MINIAPP,framework:"native",global:Gn(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:s.REACT_NATIVE,hostPlatform:s.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:Hn(r)?s.ELECTRON_RENDERER:s.ELECTRON_MAIN,hostPlatform:Hn(r)?s.ELECTRON_RENDERER:s.ELECTRON_MAIN,framework:"electron",global:r}:zn(r)||Hn(r)?{platform:s.WEB,hostPlatform:s.WEB,framework:zn(r)?"worker":"web",global:r}:{platform:s.UNKNOWN,hostPlatform:s.UNKNOWN,framework:"native",global:r}},Xn=e=>e===s.WECHAT_MINIAPP||e===s.QQ_MINIAPP||e===s.TOUTIAO_MINIAPP||e===s.BAIDU_MINIAPP||e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP||e===s.LARK_MINIAPP||e===s.KUAISHOU_MINIAPP||e===s.JD_MINIAPP||e===s.MINIAPP_360||e===s.HARMONY_MINIAPP||e===s.QUICKAPP||e===s.UNIAPP,Zn=["request","upload","socket","proto"],er=(e,t=Zn)=>{const s=((e,t=Zn)=>t.filter(t=>!e[t]))(e,t);if(0!==s.length)throw n("Platform missing required capabilities.",{code:r.MISSING_CAPABILITY,stage:i.INIT,retryable:!1,details:{required:[...t],missing:s}})},tr={nested:{easemob:{nested:{pb:{nested:{MessageBody:{fields:{type:{type:"Type",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},contents:{rule:"repeated",type:"Content",id:4},ext:{rule:"repeated",type:"KeyValue",id:5},ackMessageId:{type:"uint64",id:6},msgConfig:{type:"MessageConfig",id:7},ackContent:{type:"string",id:8},meta:{type:"string",id:9},editMessageId:{type:"uint64",id:11},editScope:{type:"EditScope",id:12},stream:{type:"Stream",id:13},userInfoUpdateTime:{type:"int32",id:14},namecardUpdateTime:{type:"int32",id:15},sendToPeer:{type:"bool",id:16},ackMessageIds:{rule:"repeated",type:"uint64",id:17},clearAllUnreadMessageCount:{type:"bool",id:18}},nested:{Content:{fields:{type:{type:"Type",id:1},text:{type:"string",id:2},latitude:{type:"double",id:3},longitude:{type:"double",id:4},address:{type:"string",id:5},displayName:{type:"string",id:6},remotePath:{type:"string",id:7},secretKey:{type:"string",id:8},fileLength:{type:"int32",id:9},action:{type:"string",id:10},params:{rule:"repeated",type:"KeyValue",id:11},duration:{type:"int32",id:12},size:{type:"Size",id:13},thumbnailRemotePath:{type:"string",id:14},thumbnailSecretKey:{type:"string",id:15},thumbnailDisplayName:{type:"string",id:16},thumbnailFileLength:{type:"int32",id:17},thumbnailSize:{type:"Size",id:18},customEvent:{type:"string",id:19},customExts:{rule:"repeated",type:"KeyValue",id:20},buildingName:{type:"string",id:21},subType:{type:"SubType",id:22},title:{type:"string",id:23},summary:{type:"string",id:24},combineLevel:{type:"int32",id:25},imageType:{type:"int32",id:26}},nested:{Type:{values:{TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8}},Size:{fields:{width:{type:"double",id:1},height:{type:"double",id:2}}},SubType:{values:{COMBINE:0,GIF:1,SUB_STREAM:10}}}},Type:{values:{NORMAL:0,CHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8}},EditScope:{values:{BODY:1,BODY_AND_EXT:2}},MessageConfig:{fields:{allowGroupAck:{type:"bool",id:1}}},Stream:{fields:{streamType:{type:"string",id:1},streamSeq:{type:"uint64",id:2},streamStatus:{type:"StreamStatus",id:3},streamError:{type:"uint32",id:4},streamFinishReason:{type:"int32",id:5}},nested:{StreamStatus:{values:{STREAM_START:0,STREAM_START_COMPLETED:1,STREAM_IN_PROGRESS:2,STREAM_COMPLETED:3,STREAM_FULL:4}}}}}},KeyValue:{oneofs:{value:{oneof:["varintValue","floatValue","doubleValue","stringValue"]}},fields:{key:{type:"string",id:1},type:{type:"ValueType",id:2},varintValue:{type:"int64",id:3},floatValue:{type:"float",id:4},doubleValue:{type:"double",id:5},stringValue:{type:"string",id:6}},nested:{ValueType:{values:{BOOL:1,INT:2,UINT:3,LLINT:4,FLOAT:5,DOUBLE:6,STRING:7,JSON_STRING:8}}}},JID:{fields:{appKey:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},clientResource:{type:"string",id:4}}},ConferenceBody:{fields:{sessionId:{type:"string",id:1},operation:{type:"Operation",id:2},conferenceId:{type:"string",id:3},type:{type:"Type",id:4},content:{type:"string",id:5},network:{type:"string",id:6},version:{type:"string",id:7},identity:{type:"Identity",id:8},duration:{type:"string",id:9},peerName:{type:"string",id:10},endReason:{type:"EndReason",id:11},status:{type:"Status",id:12},isDirect:{type:"bool",id:13},controlType:{type:"StreamControlType",id:14},routeFlag:{type:"int32",id:15},routeKey:{type:"string",id:16}},nested:{Status:{fields:{errorCode:{type:"int32",id:1}}},Operation:{values:{JOIN:0,INITIATE:1,ACCEPT_INITIATE:2,ANSWER:3,TERMINATE:4,REMOVE:5,STREAM_CONTROL:6,MEDIA_REQUEST:7}},Type:{values:{VOICE:0,VIDEO:1}},Identity:{values:{CALLER:0,CALLEE:1}},EndReason:{values:{HANGUP:0,NORESPONSE:1,REJECT:2,BUSY:3,FAIL:4,UNSUPPORTED:5,OFFLINE:6}},StreamControlType:{values:{PAUSE_VOICE:0,RESUME_VOICE:1,PAUSE_VIDEO:2,RESUME_VIDEO:3}}}},MSync:{fields:{version:{type:"Version",id:1,options:{default:"MSYNC_V1"}},guid:{type:"JID",id:2},auth:{type:"string",id:3},compressAlgorimth:{type:"uint32",id:4},crypto:{type:"uint32",id:5},userAgent:{type:"string",id:6},pov:{type:"uint64",id:7},command:{type:"Command",id:8},deviceId:{type:"uint32",id:10},encryptType:{rule:"repeated",type:"EncryptType",id:11,options:{packed:!1}},encryptKey:{type:"string",id:12},payload:{type:"bytes",id:9},traceId:{type:"uint64",id:20}},nested:{Version:{values:{MSYNC_V1:0,MSYNC_V2:1}},Command:{values:{SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4}}}},EncryptType:{values:{ENCRYPT_NONE:0,ENCRYPT_AES_128_CBC:1,ENCRYPT_AES_256_CBC:2}},CommSyncUL:{fields:{meta:{type:"Meta",id:1},key:{type:"uint64",id:2},queue:{type:"JID",id:3},isRoam:{type:"bool",id:4},lastFullRoamKey:{type:"uint64",id:5}}},CommSyncDL:{fields:{status:{type:"Status",id:1},metaId:{type:"uint64",id:2},serverId:{type:"uint64",id:3},metas:{rule:"repeated",type:"Meta",id:4},nextKey:{type:"uint64",id:5},queue:{type:"JID",id:6},isLast:{type:"bool",id:7},timestamp:{type:"uint64",id:8},isRoam:{type:"bool",id:9}}},CommNotice:{fields:{queue:{type:"JID",id:1}}},CommUnreadUL:{fields:{}},CommUnreadDL:{fields:{status:{type:"Status",id:1},unread:{rule:"repeated",type:"MetaQueue",id:2},timestamp:{type:"uint64",id:3}}},MetaQueue:{fields:{queue:{type:"JID",id:1},n:{type:"uint32",id:2}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},timestamp:{type:"uint64",id:4},ns:{type:"NameSpace",id:5},payload:{type:"bytes",id:6},routetype:{type:"RouteType",id:7},ext:{rule:"repeated",type:"KeyValue",id:8},meta:{type:"bytes",id:9},directedUsers:{rule:"repeated",type:"string",id:10},env:{type:"string",id:13}},nested:{NameSpace:{values:{STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,CONFERENCE:4,NOTIFY:5,QUERY:6}},RouteType:{values:{ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},reason:{type:"string",id:2},redirectInfo:{rule:"repeated",type:"RedirectInfo",id:3}},nested:{ErrorCode:{values:{OK:0,FAIL:1,UNAUTHORIZED:2,MISSING_PARAMETER:3,WRONG_PARAMETER:4,REDIRECT:5,TOKEN_EXPIRED:6,PERMISSION_DENIED:7,NO_ROUTE:8,UNKNOWN_COMMAND:9,PB_PARSER_ERROR:10,BIND_ANOTHER_DEVICE:11,IM_FORBIDDEN:12,TOO_MANY_DEVICES:13,PLATFORM_LIMIT:14,USER_MUTED:15,ENCRYPT_DISABLE:16,ENCRYPT_ENABLE:17,DECRYPT_FAILURE:18,PERMISSION_DENIED_EXTERNAL:19}}}},RedirectInfo:{fields:{host:{type:"string",id:1},port:{type:"uint32",id:2}}},Provision:{fields:{osType:{type:"OsType",id:1},version:{type:"string",id:2},networkType:{type:"NetworkType",id:3},appSign:{type:"string",id:4},compressType:{rule:"repeated",type:"CompressType",id:5,options:{packed:!1}},encryptType:{rule:"repeated",type:"EncryptType",id:6,options:{packed:!1}},encryptKey:{type:"string",id:7},status:{type:"Status",id:8},deviceUuid:{type:"string",id:9},isManualLogin:{type:"bool",id:10},password:{type:"string",id:11},deviceName:{type:"string",id:12},resource:{type:"string",id:13},auth:{type:"string",id:14},serviceId:{type:"string",id:16},actionVersion:{type:"string",id:17},authToken:{type:"string",id:18},osCustomValue:{type:"uint32",id:19},sessionId:{type:"string",id:20},reason:{type:"string",id:21},protocolCompressType:{rule:"repeated",type:"CompressType",id:22},protocolCompressDirection:{type:"CompressDirection",id:23}},nested:{OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}},CompressType:{values:{COMPRESS_NONE:0,COMPRESS_ZLIB:1,COMPRESS_LZ4:2}},CompressDirection:{values:{ONLY_UP:0,ONLY_DOWN:1,BI:2}}}},Logout:{fields:{sessionId:{type:"string",id:1},reason:{type:"string",id:2},status:{type:"Status",id:3}}},MUCBody:{fields:{mucId:{type:"JID",id:1},operation:{type:"Operation",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},setting:{type:"Setting",id:5},reason:{type:"string",id:6},isChatroom:{type:"bool",id:7},status:{type:"Status",id:8},isThread:{type:"bool",id:9},mucParentId:{type:"JID",id:10},mucName:{type:"string",id:11},eventInfo:{type:"EventInfo",id:12},mucMemberCount:{type:"int32",id:13},ext:{type:"string",id:14},leaveOtherRooms:{type:"bool",id:15},members:{rule:"repeated",type:"string",id:16}},nested:{Operation:{values:{CREATE:0,DESTROY:1,JOIN:2,LEAVE:3,APPLY:4,APPLY_ACCEPT:5,APPLY_DECLINE:6,INVITE:7,INVITE_ACCEPT:8,INVITE_DECLINE:9,KICK:10,GET_BLACKLIST:11,BAN:12,ALLOW:13,UPDATE:14,BLOCK:15,UNBLOCK:16,PRESENCE:17,ABSENCE:18,DIRECT_JOINED:19,ASSIGN_OWNER:20,ADD_ADMIN:21,REMOVE_ADMIN:22,ADD_MUTE:23,REMOVE_MUTE:24,UPDATE_ANNOUNCEMENT:25,DELETE_ANNOUNCEMENT:26,UPLOAD_FILE:27,DELETE_FILE:28,ADD_USER_WHITE_LIST:29,REMOVE_USER_WHITE_LIST:30,BAN_GROUP:31,REMOVE_BAN_GROUP:32,THREAD_CREATE:33,THREAD_DESTROY:34,THREAD_JOIN:35,THREAD_LEAVE:36,THREAD_KICK:37,THREAD_UPDATE:38,THREAD_PRESENCE:39,THREAD_ABSENCE:40,DISABLE_GROUP:41,ABLE_GROUP:42,SET_METADATA:43,DELETE_METADATA:44,GROUP_MEMBER_METADATA_UPDATE:45}},Setting:{fields:{name:{type:"string",id:1},desc:{type:"string",id:2},type:{type:"Type",id:3},maxUsers:{type:"int32",id:4},owner:{type:"string",id:5}},nested:{Type:{values:{PRIVATE_OWNER_INVITE:0,PRIVATE_MEMBER_INVITE:1,PUBLIC_JOIN_APPROVAL:2,PUBLIC_JOIN_OPEN:3,PUBLIC_ANONYMOUS:4}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2},chatroomInfo:{type:"string",id:3}},nested:{ErrorCode:{values:{OK:0,PERMISSION_DENIED:1,WRONG_PARAMETER:2,MUC_NOT_EXIST:3,USER_NOT_EXIST:4,UNKNOWN:5}}}},EventInfo:{fields:{eventType:{type:"EventType",id:1,options:{default:"EVENT_NONE"}},ext:{type:"string",id:2}},nested:{EventType:{values:{EVENT_NONE:0,CIRCLE_CHANNEL:1}}}}}},RosterBody:{fields:{operation:{type:"Operation",id:1},status:{type:"Status",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},reason:{type:"string",id:5},rosterVer:{type:"string",id:6},biDirection:{type:"bool",id:7}},nested:{Operation:{values:{GET_ROSTER:0,GET_BLACKLIST:1,ADD:2,REMOVE:3,ACCEPT:4,DECLINE:5,BAN:6,ALLOW:7,REMOTE_ACCEPT:8,REMOTE_DECLINE:9}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2}},nested:{ErrorCode:{values:{OK:0,USER_NOT_EXIST:1,USER_ALREADY_FRIEND:2,USER_ALREADY_BLACKLIST:3}}}}}},StatisticsBody:{fields:{operation:{type:"Operation",id:1},os:{type:"OsType",id:2},version:{type:"string",id:3},network:{type:"NetworkType",id:4},imTime:{type:"uint32",id:5},chatTime:{type:"uint32",id:6},location:{type:"string",id:7},reason:{type:"string",id:10}},nested:{Operation:{values:{INFORMATION:0,USER_REMOVED:1,USER_LOGIN_ANOTHER_DEVICE:2,USER_KICKED_BY_CHANGE_PASSWORD:3,USER_KICKED_BY_OTHER_DEVICE:4}},OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}}}}}}}}}},sr=e=>{if(!e||0===e.trim().length)throw n("Proto type name is required.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e}})};class nr{constructor(){this.codecMap=/* @__PURE__ */new Map}register(e,t){sr(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:s=>{const o=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw n("Proto payload must be an object.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(s,e),a=t.fromObject(o);return t.encode(a).finish()},decode:e=>{const s=t.decode(e);return t.toObject(s,{longs:String,enums:Number,defaults:!1})}})}get(e){return sr(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw n("Proto codec not found.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e}})}}let rr=!1,ir=null,or=null,ar=null;const cr=e=>e.startsWith(".")?e.slice(1):e,dr=e=>e instanceof ot.Namespace,lr=e=>e instanceof ot.Type,ur=e=>{for(const t of e.nestedArray)lr(t)?tt(t):dr(t)&&ur(t)},hr=()=>{rr||(ot.util.Long=nt,ot.configure(),rr=!0),st();const e=ot.Root.fromJSON(tr);return ur(e),e},pr=(e,t)=>{const s=e.nestedArray;for(const n of s){if(lr(n)){const e=cr(n.fullName);tt(n),t.registerType(e,n);continue}dr(n)&&pr(n,t)}},mr=(e,t,s)=>{const o=t instanceof Error?t.message:String(t);return n(`Static proto ${s} failed.`,{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e,operation:s,cause:o}})},fr=()=>ir||(ir=hr(),ir),gr=()=>{if(ar)return ar;const e=(()=>{if(or)return or;const e=new nr,t=fr();return pr(t,e),or=e,e})();return ar={encode(t,s){try{return e.getOrThrow(cr(t)).encode(s)}catch(n){throw mr(t,n,"encode")}},decode(t,s){try{return e.getOrThrow(cr(t)).decode(s)}catch(n){throw mr(t,n,"decode")}}},ar},yr=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Ir=e=>"function"==typeof e.on&&"function"==typeof e.off,vr=(e,t,s)=>{if(yr(e))return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)};if(Ir(e)){const n=e;return n.on(t,s),()=>{n.off(t,s)}}throw n("Socket event listener API is unsupported.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!1,details:{event:t}})},Cr=(e,t,s)=>{if(yr(e)){const n=(...r)=>{e.removeEventListener(t,n),s(...r)};return e.addEventListener(t,n),()=>{e.removeEventListener(t,n)}}if(Ir(e)){const n=e;if("function"==typeof n.once)return n.once?.(t,s),()=>{n.off(t,s)};let r=()=>{};return r=vr(e,t,(...e)=>{r(),s(...e)}),r}throw n("Socket one-time listener API is unsupported.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!1,details:{event:t}})},Sr=e=>{return"string"==typeof e||(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))||"undefined"!=typeof Blob&&e instanceof Blob?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e&&"object"==typeof e&&"data"in e?Sr(e.data):null;var t},Er=e=>{const t=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set,a=/* @__PURE__ */new Set,c=/* @__PURE__ */new Set;return vr(e,"open",()=>{t.forEach(e=>{e()})}),vr(e,"message",(...e)=>{const t=Sr(e[0]);null!==t&&s.forEach(e=>{e(t)})}),vr(e,"error",(...e)=>{const t=e[0];a.forEach(e=>{e(t)})}),vr(e,"close",(...e)=>{const t=(e=>{const[t,s]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof s?s:ArrayBuffer.isView(s)?(new TextDecoder).decode(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)):void 0}})(e);c.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==o.OPEN)throw n("Socket is not open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,s){e.close(t,s)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(s.add(e),()=>{s.delete(e)}),onError:e=>(a.add(e),()=>{a.delete(e)}),onClose:e=>(c.add(e),()=>{c.delete(e)})}},br=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((s,o)=>{let a;try{a=new t(e.url,e.protocols);try{a.binaryType="arraybuffer"}catch{}}catch(m){return void o(n("Socket creation failed.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{cause:m instanceof Error?m.message:String(m)}}))}let c,d=()=>{},l=()=>{},u=!1;const h=()=>{void 0!==c&&(clearTimeout(c),c=void 0)},p=()=>{u||(u=!0,d(),l(),h(),a.close(),o(n("Socket connection timed out.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{url:e.url,reason:"timeout"}})))};d=Cr(a,"open",()=>{u||(u=!0,d(),l(),h(),s(Er(a)))}),l=Cr(a,"error",e=>{if(u)return;u=!0,d(),l(),h();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;o(n("Socket connection failed before open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(c=setTimeout(p,e.timeoutMs))})}},Tr=(e,t)=>{throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:"abort"!==e,details:{reason:e,url:t.url}})},Ar=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,s])=>{t.append(e,s)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw n("Web upload adapter only supports web-file source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const s=t.source.file;if(!s)throw n("Upload source file is required for web-file uploads.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const o="undefined"!=typeof Blob&&s instanceof Blob,a=t.source.name??"upload.bin",c=t.fileFieldName??"file";o?e.append(c,s,a):e.append(c,s)})(t,e),t},wr=(e,t,s)=>new Promise((o,a)=>{const c=e(),d=s.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const s=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:s})})})(c,s),c.addEventListener("abort",()=>{try{Tr("abort",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("timeout",()=>{try{Tr("timeout",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("error",()=>{try{Tr("network",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("load",()=>{o({status:c.status,body:c.responseText})});try{const e=Ar(s);c.timeout=d,c.open(s.method??"POST",s.url),((e,t)=>{Object.entries(t??{}).forEach(([t,s])=>{e.setRequestHeader(t,s)})})(c,s.headers),c.send(e)}catch(l){a(n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:s.url,reason:"invalid-config",cause:l instanceof Error?l.message:String(l)}}))}}),Nr=(e,t)=>e?"timeout":"abort",Mr=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,s=e?.fetchImpl;if("function"==typeof t||"function"==typeof s)return{upload(o){if("function"==typeof t)return wr(t,e,o);if("function"==typeof s)return(async(e,t,s)=>{const o=s.timeoutMs??t?.timeoutMs??3e4;let a=!1;const c="undefined"!=typeof AbortController?new AbortController:void 0,d=c&&Number.isFinite(o)?setTimeout(()=>{a=!0,c.abort()},o):void 0,l=((e,t)=>e??t?.signal)(s.signal,c);try{const t=Ar(s),n=await e(s.url,{method:s.method??"POST",headers:s.headers,body:t,signal:l}),r=await n.text(),i=s.source.size;return"number"==typeof i&&s.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:n.status,body:r}}catch(u){const e=u instanceof Error&&"AbortError"===u.name;throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!e,details:{reason:e?Nr(a):"network",url:s.url,cause:u instanceof Error?u.message:String(u)}})}finally{d&&clearTimeout(d)}})(s,e,o);throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{reason:"missing-upload-runtime",url:o.url}})}}},Rr=(e,t)=>{const s=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{s.append(e,t)}),s.append(t.fileFieldName??"file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw n("React Native upload adapter only supports rn-uri source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),s},_r=e=>{const t=e?.fetchImpl,s=e?.formDataCtor;if("function"==typeof t&&"function"==typeof s)return{async upload(o){const a=o.timeoutMs??e?.timeoutMs??3e4,c="function"==typeof AbortController?new AbortController:void 0;let d=!1;const l=c&&Number.isFinite(a)?setTimeout(()=>{d=!0,c.abort()},a):void 0;try{const e=Rr(s,o),n=await t(o.url,{method:o.method??"POST",headers:o.headers,body:e,signal:o.signal??c?.signal}),r=await n.text(),i=o.source.size;return"number"==typeof i&&o.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:n.status,body:r}}catch(u){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===r.UPLOAD_FAILED&&t.stage===i.UPLOAD})(u))throw u;const e=u instanceof Error&&"AbortError"===u.name;throw n("React Native upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!e||d,details:{url:o.url,reason:e?d?"timeout":"abort":"network",cause:u instanceof Error?u.message:String(u)}})}finally{void 0!==l&&clearTimeout(l)}}}},Dr=(e,t)=>e+t&4294967295,Ur=(e,t,s,n,r,i)=>{return Dr((o=Dr(Dr(t,e),Dr(n,i)))<<(a=r)|o>>>32-a,s);var o,a},Lr=(e,t,s,n,r,i,o)=>Ur(t&s|~t&n,e,t,r,i,o),Or=(e,t,s,n,r,i,o)=>Ur(t&n|s&~n,e,t,r,i,o),kr=(e,t,s,n,r,i,o)=>Ur(t^s^n,e,t,r,i,o),Pr=(e,t,s,n,r,i,o)=>Ur(s^(t|~n),e,t,r,i,o),xr=(e,t)=>{let[s,n,r,i]=e;s=Lr(s,n,r,i,t[0]??0,7,-680876936),i=Lr(i,s,n,r,t[1]??0,12,-389564586),r=Lr(r,i,s,n,t[2]??0,17,606105819),n=Lr(n,r,i,s,t[3]??0,22,-1044525330),s=Lr(s,n,r,i,t[4]??0,7,-176418897),i=Lr(i,s,n,r,t[5]??0,12,1200080426),r=Lr(r,i,s,n,t[6]??0,17,-1473231341),n=Lr(n,r,i,s,t[7]??0,22,-45705983),s=Lr(s,n,r,i,t[8]??0,7,1770035416),i=Lr(i,s,n,r,t[9]??0,12,-1958414417),r=Lr(r,i,s,n,t[10]??0,17,-42063),n=Lr(n,r,i,s,t[11]??0,22,-1990404162),s=Lr(s,n,r,i,t[12]??0,7,1804603682),i=Lr(i,s,n,r,t[13]??0,12,-40341101),r=Lr(r,i,s,n,t[14]??0,17,-1502002290),n=Lr(n,r,i,s,t[15]??0,22,1236535329),s=Or(s,n,r,i,t[1]??0,5,-165796510),i=Or(i,s,n,r,t[6]??0,9,-1069501632),r=Or(r,i,s,n,t[11]??0,14,643717713),n=Or(n,r,i,s,t[0]??0,20,-373897302),s=Or(s,n,r,i,t[5]??0,5,-701558691),i=Or(i,s,n,r,t[10]??0,9,38016083),r=Or(r,i,s,n,t[15]??0,14,-660478335),n=Or(n,r,i,s,t[4]??0,20,-405537848),s=Or(s,n,r,i,t[9]??0,5,568446438),i=Or(i,s,n,r,t[14]??0,9,-1019803690),r=Or(r,i,s,n,t[3]??0,14,-187363961),n=Or(n,r,i,s,t[8]??0,20,1163531501),s=Or(s,n,r,i,t[13]??0,5,-1444681467),i=Or(i,s,n,r,t[2]??0,9,-51403784),r=Or(r,i,s,n,t[7]??0,14,1735328473),n=Or(n,r,i,s,t[12]??0,20,-1926607734),s=kr(s,n,r,i,t[5]??0,4,-378558),i=kr(i,s,n,r,t[8]??0,11,-2022574463),r=kr(r,i,s,n,t[11]??0,16,1839030562),n=kr(n,r,i,s,t[14]??0,23,-35309556),s=kr(s,n,r,i,t[1]??0,4,-1530992060),i=kr(i,s,n,r,t[4]??0,11,1272893353),r=kr(r,i,s,n,t[7]??0,16,-155497632),n=kr(n,r,i,s,t[10]??0,23,-1094730640),s=kr(s,n,r,i,t[13]??0,4,681279174),i=kr(i,s,n,r,t[0]??0,11,-358537222),r=kr(r,i,s,n,t[3]??0,16,-722521979),n=kr(n,r,i,s,t[6]??0,23,76029189),s=kr(s,n,r,i,t[9]??0,4,-640364487),i=kr(i,s,n,r,t[12]??0,11,-421815835),r=kr(r,i,s,n,t[15]??0,16,530742520),n=kr(n,r,i,s,t[2]??0,23,-995338651),s=Pr(s,n,r,i,t[0]??0,6,-198630844),i=Pr(i,s,n,r,t[7]??0,10,1126891415),r=Pr(r,i,s,n,t[14]??0,15,-1416354905),n=Pr(n,r,i,s,t[5]??0,21,-57434055),s=Pr(s,n,r,i,t[12]??0,6,1700485571),i=Pr(i,s,n,r,t[3]??0,10,-1894986606),r=Pr(r,i,s,n,t[10]??0,15,-1051523),n=Pr(n,r,i,s,t[1]??0,21,-2054922799),s=Pr(s,n,r,i,t[8]??0,6,1873313359),i=Pr(i,s,n,r,t[15]??0,10,-30611744),r=Pr(r,i,s,n,t[6]??0,15,-1560198380),n=Pr(n,r,i,s,t[13]??0,21,1309151649),s=Pr(s,n,r,i,t[4]??0,6,-145523070),i=Pr(i,s,n,r,t[11]??0,10,-1120210379),r=Pr(r,i,s,n,t[2]??0,15,718787259),n=Pr(n,r,i,s,t[9]??0,21,-343485551),e[0]=Dr(s,e[0]),e[1]=Dr(n,e[1]),e[2]=Dr(r,e[2]),e[3]=Dr(i,e[3])},Fr=(e,t)=>{const s=new Array(16).fill(0);for(let n=0;n<16;n+=1){const r=t+4*n;s[n]=(e[r]??0)|(e[r+1]??0)<<8|(e[r+2]??0)<<16|(e[r+3]??0)<<24}return s},Br=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},qr=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)xr(t,Fr(e,s));const n=new Array(16).fill(0);let r=0;for(;s<e.length;s+=1){const t=r>>2;n[t]=(n[t]??0)|(e[s]??0)<<r%4*8,r+=1}const i=r>>2;n[i]=(n[i]??0)|128<<r%4*8,r>55&&(xr(t,n),n.fill(0));const o=8*e.length;return n[14]=4294967295&o,n[15]=Math.floor(o/4294967296),xr(t,n),t.map(Br).join("")},Kr=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw n("Image decode capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,s)=>{const o=new Image;o.onload=()=>{e({image:o,width:o.naturalWidth||o.width,height:o.naturalHeight||o.height,cleanup:()=>{URL.revokeObjectURL(t)}})},o.onerror=()=>{URL.revokeObjectURL(t),s(n("Image decode failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{reason:"image load error"}}))},o.src=t})},Gr=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw n("Web image processor only supports web file source",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.file},Vr=()=>({async getImageInfo(e){const t=Gr(e),s=await Kr(t);try{return{width:s.width,height:s.height,mimeType:e.mimeType,fileSize:e.size,isGif:"image/gif"===e.mimeType}}finally{s.cleanup()}},async generateBigImage(e,t){const s=Gr(e),o=await Kr(s);try{const s=((e,t,s)=>{const n=Math.min(e,t);if(n<=s)return{width:e,height:t};const r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}})(o.width,o.height,t.maxShortEdge),c=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const s=document.createElement("canvas");return s.width=e,s.height=t,s}throw n("Canvas capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(s.width,s.height),d=c.getContext("2d");if(!d)throw n("Canvas 2d context is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1});d.drawImage(o.image,0,0,s.width,s.height);const l="image/png"===(a=e.mimeType)||"image/webp"===a?a:"image/jpeg",u=await(async(e,t,s)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:s});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((o,a)=>{e.toBlob(e=>{e?o(e):a(n("Image encode failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,s)});throw n("Canvas encode capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas encode unavailable"}})})(c,l,t.quality),h=(e=>e.name??"image")(e),p="undefined"!=typeof File?new File([u],h,{type:l,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:p??u,name:h,mimeType:l,size:p?.size??u.size},width:s.width,height:s.height,fileName:h,fileType:l,fileSize:p?.size??u.size,webFile:p}}finally{o.cleanup()}var a},async computeMd5(e){const t=Gr(e),s=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw n("Binary read capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,s)=>{const o=new FileReader;o.onerror=()=>{s(n("Binary read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1}))},o.onload=()=>{o.result instanceof ArrayBuffer?t(o.result):s(n("Binary read returned invalid result",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1}))},o.readAsArrayBuffer(e)})})(t);return qr(new Uint8Array(s))}}),Hr=e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"errMsg"in e){const t=e.errMsg;if("string"==typeof t)return t}return String(e)},zr=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw n("Miniapp image processor only supports miniapp path source",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.path},jr=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw n("Miniapp file system capability is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"getFileSystemManager"}})},Wr=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},Qr=async(e,t)=>new Promise((s,n)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{n(e instanceof Error?e:new Error(Hr(e)))}})}).catch(e=>{throw n("Miniapp image info read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{src:t,cause:Hr(e)}})}),$r=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,Yr=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await Qr(e,t);return $r(t,s)},Jr=e=>({async getImageInfo(t){const s=zr(t),n=await Qr(e,s),r=Wr(n.type)??t.mimeType;return{width:n.width,height:n.height,mimeType:r,fileSize:t.size,isGif:"image/gif"===r}},async generateBigImage(t,s){const o=zr(t);if("function"!=typeof e.compressImage)throw n("Miniapp image compress capability is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"compressImage"}});const a=await Qr(e,o),c=$r(o,a),d=((e,t,s)=>{const n=Math.min(e,t);if(n<=s)return{width:e,height:t};const r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}})(a.width,a.height,s.maxShortEdge),l=await new Promise((t,n)=>{e.compressImage?.({src:c,quality:Math.max(0,Math.min(100,Math.round(100*s.quality))),compressedWidth:d.width,compressedHeight:d.height,success:e=>{e.tempFilePath?t(e.tempFilePath):n(new Error("compressImage missing tempFilePath"))},fail:e=>{n(e instanceof Error?e:new Error(Hr(e)))}})}).catch(e=>{throw n("Miniapp image compress failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{src:c,cause:Hr(e)}})}),u=await Yr(e,l),h=await Qr(e,u),p=Wr(h.type)??t.mimeType,m=await(async(e,t,s)=>{const o=jr(e);return o.getFileInfo?new Promise((e,s)=>{o.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{s(e instanceof Error?e:new Error(Hr(e)))}})}).catch(e=>{throw n("Miniapp file info read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{filePath:t,cause:Hr(e)}})}):s})(e,u,t.size);return{source:{sourceType:"miniapp-path",path:u,name:t.name,mimeType:p,size:m},width:h.width,height:h.height,fileName:t.name,fileType:p,fileSize:m}},async computeMd5(t){const s=zr(t),o=await Yr(e,s),a=await(async(e,t)=>{const s=jr(e),o=await new Promise((e,n)=>{s.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{n(e instanceof Error?e:new Error(Hr(e)))}})}).catch(e=>{throw n("Miniapp file read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{filePath:t,cause:Hr(e)}})});return o instanceof ArrayBuffer?new Uint8Array(o):"function"==typeof TextEncoder?(new TextEncoder).encode(o):Uint8Array.from(Array.from(o).map(e=>255&e.charCodeAt(0)))})(e,o);return qr(a)}}),Xr=/* @__PURE__ */new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),Zr=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],ei=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},ti=e=>{if(!e)return!1;const t=ei(e,"name");if(t&&Xr.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,ei(e,"message"),ei(e,"errMsg")].some(e=>null!==e&&Zr.some(t=>t.test(e)))},si=e=>{if(e instanceof Error)return e;const t=ei(e,"message")??ei(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},ni="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ri=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),ii=e=>e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP,oi=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),s=t.endsWith("==")?2:t.endsWith("=")?1:0,n=Math.max(0,Math.floor(3*t.length/4)-s),r=new Uint8Array(n);let i=0;for(let o=0;o<t.length;o+=4){const e=ni.indexOf(t[o]??""),s=ni.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:ni.indexOf(a),l="="===c?0:ni.indexOf(c);if(e<0||s<0||d<0||l<0)return new ArrayBuffer(0);const u=e<<18|s<<12|d<<6|l;for(const t of[16,8,0])i<n&&(r[i]=u>>t&255,i+=1)}return r.buffer},ai=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),ci=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},di=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(ai(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?di(s.data,t+1):e},li=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return ci(e);if(ai(e))try{return ci(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return ci(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e))return e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)?Uint8Array.from(e):void 0;if("object"!=typeof e)return;const s=e;if("data"in s&&s.data!==e){const e=li(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=li(s.buffer,t+1);if(!e)return;const n="number"==typeof s.byteOffset&&Number.isInteger(s.byteOffset)?s.byteOffset:0,r="number"==typeof s.byteLength&&Number.isInteger(s.byteLength)?s.byteLength:e.byteLength-n;if(n<0||r<0||n+r>e.byteLength)return;return e.slice(n,n+r)}},ui=(e,t)=>{if("string"==typeof e)return e;const s=e instanceof Uint8Array?e:new Uint8Array(e);if(ii(t)){const n=(e=>{let t="";for(let s=0;s<e.length;s+=3){const n=e[s]??0,r=e[s+1],i=e[s+2],o=n<<16|(r??0)<<8|(i??0);t+=ni[o>>18&63],t+=ni[o>>12&63],t+=void 0===r?"=":ni[o>>6&63],t+=void 0===i?"=":ni[63&o]}return t})(s);return a.warn("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:s.byteLength,encodedCharacters:n.length,sourcePrefixHex:ri(s.subarray(0,8))}),n}const n=new ArrayBuffer(s.byteLength);return new Uint8Array(n).set(s),n},hi=(e,t)=>"string"!=typeof e&&ii(t),pi=(e,t)=>{const s=di(e.data);if("string"==typeof s){if(!ii(t))return s;const n=oi(s),r=new Uint8Array(n);return a.warn("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:s===e.data?"string":"wrapped-string",sourceCharacters:s.length,decodedBytes:n.byteLength,decodedPrefixHex:ri(r.subarray(0,8)),decodedSuffixHex:ri(r.subarray(Math.max(0,r.length-8)))}),n}const n=li(s);if(!n){const n="object"==typeof e.data&&null!==e.data?e.data:void 0;return void a.warn("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof s,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:n?Object.keys(n).slice(0,10):[],isBuffer:e.isBuffer})}if(!ii(t))return n.buffer;const r=(e=>{let t="";for(const n of e){if(9!==n&&10!==n&&13!==n&&32!==n&&!(n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||43===n||45===n||47===n||61===n||95===n))return;t+=String.fromCharCode(n)}const s=t.replace(/\s/g,"");if(0!==s.length&&s.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(s))return s})(n);if(!r)return a.warn("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(s),sourceBytes:n.byteLength,sourcePrefixHex:ri(n.subarray(0,8))}),n.buffer;const i=oi(r),o=new Uint8Array(i);return a.warn("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(s),sourceBytes:n.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:ri(o.subarray(0,8)),decodedSuffixHex:ri(o.subarray(Math.max(0,o.length-8)))}),i},mi=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),fi=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],gi=e=>e instanceof Error?e.message:mi(e)&&"string"==typeof e.errMsg?e.errMsg:mi(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),yi=e=>e?{...e}:{},Ii=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,vi=e=>Ii(e.statusCode)?e.statusCode:Ii(e.status)?e.status:void 0,Ci=e=>{if(!mi(e))return{};const t={};return Object.entries(e).forEach(([e,s])=>{"string"==typeof s&&(t[e]=s)}),t},Si=e=>({...Ci(e.headers),...Ci(e.header)}),Ei=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},bi=e=>{try{e.close()}catch{}},Ti=(e,t)=>new Promise((s,o)=>{let c=!1,d=()=>{};const l=(e,s,a)=>{c||(c=!0,d(),o(n(e,{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:a,details:{url:t.url,method:"GET",cause:gi(s)}})))},u=e.downloadFile?.({url:t.url,header:yi(t.headers),timeout:t.timeoutMs??15e3,success:n=>{const r=n.tempFilePath??n.apFilePath;r?((e,t)=>new Promise((s,n)=>{const r=e.getFileSystemManager?.();r?r.readFile({filePath:t,success:e=>{const t=li(e.data);t?s(t.buffer):n(new Error("downloaded file response is not binary"))},fail:n}):n(new Error("getFileSystemManager returned no file system manager"))}))(e,r).then(e=>{c||(c=!0,d(),a.warn("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:n.apFilePath?"apFilePath":"tempFilePath",status:n.statusCode??200,bytes:e.byteLength}),s({status:n.statusCode??200,headers:n.header??{},data:e}))}).catch(e=>{l("Mini program downloaded file read failed.",e,!1)}):l("Mini program download did not return a file path.",n,!1)},fail:e=>{l("Mini program file download failed.",e,!0)}});d=Ei(t.signal,()=>{u?.abort(),l("Mini program file download aborted.","abort",!1)})}),Ai=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((s,o)=>{let a=()=>{};const c=e.request({url:t.url,method:t.method??"GET",header:yi(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{a();const c=vi(e);void 0!==c?s({status:c,headers:Si(e),data:e.data}):o(n("Mini program request response status is invalid.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{a(),o(n("Mini program request failed.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:gi(e)}}))}});a=Ei(t.signal,()=>{c.abort(),o(n("Mini program request aborted.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Ti(e,t)}),wi=(e,t)=>({connect:a=>new Promise((c,d)=>{let l,u,h=!1;const p=()=>{void 0!==u&&(clearTimeout(u),u=void 0)},m=(e,t,s)=>{h||(h=!0,p(),l&&bi(l),d(n(t,{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:s,details:{url:a.url,cause:gi(e)}})))},f=e=>{if(!(fi(s=e,"send")&&fi(s,"close")&&fi(s,"onOpen")&&fi(s,"onMessage")&&fi(s,"onError")&&fi(s,"onClose")))return void m(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var s;const a=e;if(h)return void bi(a);l=a;const d=()=>{a.offOpen?.(u),a.offError?.(f)},u=()=>{h?bi(a):(h=!0,p(),d(),c(((e,t,s=o.CONNECTING)=>{const a=/* @__PURE__ */new Set,c=/* @__PURE__ */new Set,d=/* @__PURE__ */new Set,l=/* @__PURE__ */new Set;let u=s;return e.onOpen(()=>{u=o.OPEN,a.forEach(e=>{e()})}),e.onMessage(e=>{const s=pi(e,t);void 0!==s&&c.forEach(e=>{e(s)})}),e.onError(e=>{d.forEach(t=>{t(e)})}),e.onClose(e=>{u=o.CLOSED,l.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return u},send(s){if(u!==o.OPEN)throw n("Mini program socket is not open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{readyState:u}});return new Promise((o,a)=>{e.send({data:ui(s,t),...hi(s,t)?{isBuffer:!0}:{},success:o,fail:e=>{a(n("Mini program socket send failed.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{cause:gi(e)}}))}})})},close(t,s){u=o.CLOSING,e.close({code:t,reason:s})},onOpen:e=>(a.add(e),()=>{a.delete(e)}),onMessage:e=>(c.add(e),()=>{c.delete(e)}),onError:e=>(d.add(e),()=>{d.delete(e)}),onClose:e=>(l.add(e),()=>{l.delete(e)})}})(a,t,o.OPEN)))},f=e=>{d(),m(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};a.onOpen(u),a.onError(f)};let g;"number"==typeof a.timeoutMs&&a.timeoutMs>0&&(u=setTimeout(()=>{m("timeout","Mini program socket connection timed out.",!0)},a.timeoutMs));try{g=e.connectSocket({url:a.url,...t===s.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(a.protocols)?[...a.protocols]:"string"==typeof a.protocols?[a.protocols]:void 0,fail:e=>{m(e,"Mini program socket connect failed.",!0)}})}catch(I){return void m(I,"Mini program socket creation failed.",!0)}var y;"object"!=typeof(y=g)||null===y||"function"!=typeof y.then?f(g):Promise.resolve(g).then(e=>f(e),e=>m(e,"Mini program socket connect failed.",!0))})}),Ni=e=>({upload(t){const s=t.method??"POST";return"POST"!==s?Promise.reject(n("Mini program upload only supports POST.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,method:s,reason:"unsupported-method"}})):new Promise((s,o)=>{const a=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw n("Mini program upload only supports miniapp-path source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let c=()=>{};const d=e.uploadFile({url:t.url,filePath:a.path,name:t.fileFieldName??"file",header:yi(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{c();const d=vi(e);void 0!==d?s({status:d,body:e.data}):o(n("Mini program upload response status is invalid.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,path:a.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{c(),o(n("Mini program upload failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!0,details:{url:t.url,path:a.path,cause:gi(e)}}))}});d.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),c=Ei(t.signal,()=>{d.abort(),o(n("Mini program upload aborted.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,path:a.path,reason:"abort"}}))})})}}),Mi=(e,t)=>{const n=(e=>e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP)(t);return{async getItem(t){if(fi(e,"getStorageSync"))try{const s=(e=>mi(e)&&"data"in e?e.data:e)(e.getStorageSync(n?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return fi(e,"getStorage")?new Promise(s=>{e.getStorage({key:t,success:e=>{s("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{s(null)}})}):null},async setItem(t,s){if(fi(e,"setStorageSync"))try{n?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(r){if(ti(r))throw si(r)}else if(fi(e,"setStorage"))return new Promise((n,i)=>{try{e.setStorage({key:t,data:s,success:n,fail:e=>{ti(e)?i(si(e)):n()}})}catch(r){if(ti(r))return void i(si(r));n()}})},async removeItem(t){if(fi(e,"removeStorageSync"))try{e.removeStorageSync(n?{key:t}:t)}catch{}else if(fi(e,"removeStorage"))return new Promise(s=>{try{e.removeStorage({key:t,success:s,fail:()=>{s()}})}catch{s()}})}}},Ri=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>fi(e,"getNetworkType")?new Promise(t=>{e.getNetworkType?.({success:e=>{t(e.networkType??"unknown")},fail:()=>{t("unknown")}})}):Promise.resolve("unknown"),onNetworkChange(t){const s=e=>{t(e.isConnected)};return fi(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),fi(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{fi(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},n=()=>{t(!1)};return fi(e,"onAppShow")&&e.onAppShow(s),fi(e,"onAppHide")&&e.onAppHide(n),t(!0),()=>{fi(e,"offAppShow")&&e.offAppShow(s),fi(e,"offAppHide")&&e.offAppHide(n)}}}),_i=(e,t=s.WECHAT_MINIAPP,o=t)=>{const a=(e=>{if(fi(e,"request")&&fi(e,"connectSocket")&&fi(e,"uploadFile"))return e;throw n("Mini program platform capability is missing.",{code:r.MISSING_CAPABILITY,stage:i.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),c="function"==typeof a.getImageInfo?Jr(a):void 0;return{request:Ai(a),socket:wi(a,o),upload:Ni(a),runtime:Ri(a,t),storage:Mi(a,o),imageProcessor:c}},Di=["request","upload","socket"],Ui={request:"request",upload:"upload",socket:"connect"},Li=[s.WEB,s.ELECTRON_RENDERER,s.REACT_NATIVE],Oi=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},ki=e=>Li.includes(e),Pi=(e,t)=>e!==s.UNIAPP?ki(e):!Qn(t)&&!Fi(t)&&Hn(t),xi=e=>Oi(e,"getImageInfo")&&Oi(e,"getFileSystemManager"),Fi=e=>!Qn(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),Bi=(e,t)=>{if(ki(e)&&e!==s.REACT_NATIVE)return Vr();if(Xn(e)&&xi(t))return Jr(t);if(e===s.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Hn(e))return Vr();if(xi(e.uni))return Jr(e.uni);if(xi(e.wx))return Jr(e.wx)}},qi=e=>{const t=e.localStorage;if(t)return{getItem:e=>Promise.resolve(t.getItem(e)),setItem:(e,s)=>(t.setItem(e,s),Promise.resolve()),removeItem:e=>(t.removeItem(e),Promise.resolve())};const s=/* @__PURE__ */new Map;return{getItem(e){const t=s.has(e)?s.get(e)??null:null;return Promise.resolve(t)},setItem:(e,t)=>(s.set(e,t),Promise.resolve()),removeItem:e=>(s.delete(e),Promise.resolve())}},Ki=(e,t,n,r)=>{if(e===s.UNIAPP&&Fi(n)&&void 0!==n.uni&&Bn(n.uni))return{..._i(n.uni,e,t),proto:gr()};if(((e,t)=>!Pi(e,t)&&Xn(e))(e,n)&&Bn(r))return{..._i(r,e,t),proto:gr()};const i=n.XMLHttpRequest,o=Pi(e,n),a=o?c({fetchImpl:n.fetch}):void 0,d=o?br({webSocketCtor:n.WebSocket}):void 0,l=e===s.REACT_NATIVE?_r({fetchImpl:n.fetch,formDataCtor:n.FormData}):o?Mr({xhrFactory:"function"==typeof i?()=>new i:void 0,fetchImpl:n.fetch}):void 0,u=o&&e!==s.REACT_NATIVE?(h={platform:e,windowRef:n.window,documentRef:n.document,navigatorRef:n.navigator},{getPlatform:()=>h.platform,getNetworkType:()=>!1===h.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(h.navigatorRef?.connection?.type??h.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=h.windowRef;if(!t)return()=>{};const s=()=>{e(!0)},n=()=>{e(!1)};return t.addEventListener("online",s),t.addEventListener("offline",n),"boolean"==typeof h.navigatorRef?.onLine&&e(h.navigatorRef.onLine),()=>{t.removeEventListener("online",s),t.removeEventListener("offline",n)}},onAppVisibilityChange(e){const t=h.documentRef;if(!t)return()=>{};const s=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",s),s(),()=>{t.removeEventListener("visibilitychange",s)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var h;return{request:a,upload:l,socket:d,runtime:u,proto:gr(),storage:qi(n),imageProcessor:o&&e!==s.REACT_NATIVE?Vr():Bi(e,r)}},Gi=(e,t,s)=>{if(!t)return{...e,...s};const o=Di.filter(e=>void 0!==s[e]);if(o.length>0)throw n("Transport adapter conflicts with network overrides.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{conflictingCapabilities:o}});const a=(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(s);return{...e,request:t.request,upload:t.upload,socket:t.socket,...a}},Vi=(e,t)=>{if(void 0!==e)return e;throw n("Platform adapter initialization failed.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{capability:t}})},Hi=(e,t)=>Jn(t,e).platform,zi=e=>{(e=>{if(!e)return;const t=Di.flatMap(t=>{const s=Ui[t];return Oi(e[t],s)?[]:[`${t}.${s}`]});if(0!==t.length)throw n("Transport adapter has invalid capabilities.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{source:"transportAdapter",invalidCapabilities:t}})})(e?.transportAdapter);const s=t(e?.runtimeInput),o=Jn(s,e?.prefer),a=o.platform,c=Ki(a,o.hostPlatform,s,o.global),d=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,c),l=Gi(c,e?.transportAdapter,d),u=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(l);er(u);return{platform:a,platformId:a,capability:u,request:Vi(l.request,"request"),upload:Vi(l.upload,"upload"),socket:Vi(l.socket,"socket"),runtime:Vi(l.runtime,"runtime"),proto:Vi(l.proto,"proto"),storage:Vi(l.storage,"storage"),imageProcessor:l.imageProcessor}},ji=e=>{if(e)return e;const s=t(),o=br({webSocketCtor:s.WebSocket});if(o)return o;throw n("Socket capability is missing for current platform.",{code:r.MISSING_CAPABILITY,stage:i.SOCKET,retryable:!1,details:{capability:"socket"}})},Wi={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Qi{constructor(e={}){this.attemptCount=0,this.config={...Wi,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),s=Math.min(t,this.config.maxDelay);return s/2+s/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return a.debug(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const $i={interval:3e4,timeout:6e4},Yi="function"==typeof TextDecoder?new TextDecoder:null;class Ji{constructor(e={}){this.websocket=null,this.heartbeatTimer=null,this.timeoutTimer=null,this.lastPongTime=0,this.onTimeoutCallback=null,this.sendPing=null,this.probeResolvers=[],this.messageDisposer=null,this.handlePong=e=>{const t=this.extractMessageText(e);if(!t)return;const s=this.parseJson(t);if(!Ji.isRecord(s))return;"pong"===Ji.readString(s.type)&&(this.markAlive(),a.debug("Pong received"))},this.config={...$i,...e}}start(e,t,s){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=s??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),a.debug("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),a.debug("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===o.OPEN)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{a.error("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),a.debug("Ping sent")}catch(e){a.error("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?Yi?.decode(t)??kn(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{a.warn("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==o.OPEN)return!1;this.attachWebSocket(e);const s=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},s);this.probeResolvers.push(s=>{clearTimeout(t),e(s)}),this.sendPingInternal()})}catch(s){return a.warn("Heartbeat probe failed",s),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const s of t)s(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}let Xi=null;function Zi(){return Xi||(Xi=fr()),Xi}const eo="websdk2:device-info",to="webim",so="web",no=e=>{const s=Date.now(),n=e.deviceId,r=e.customOSPlatform,i=void 0!==r?e.customDeviceName:void 0,o=t().localStorage,a=()=>{if(!o)return null;try{const t=o.getItem(eo);if(!t)return null;const s=JSON.parse(t);if("object"==typeof(e=s)&&null!==e&&!Array.isArray(e)&&"string"==typeof s.deviceId&&"string"==typeof s.deviceName&&"string"==typeof s.deviceUuid)return{deviceId:s.deviceId,deviceName:s.deviceName,deviceUuid:s.deviceUuid}}catch{return null}var e;return null},c=e=>{if(o)try{o.setItem(eo,JSON.stringify(e))}catch{}},d=e=>void 0===r?e:{deviceId:`custom${r}_${e.deviceUuid}`,deviceName:i??n,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=a();if(e)return d(e);if(n===to){const e=`${so}_${s}`,t=d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e});return c(t),t}if(void 0!==r){const e=d({deviceId:`webim_${so}_${n}`,deviceName:n,deviceUuid:`${so}_${s}`});return c(e),e}const t={deviceId:`webim_${so}_${n}`,deviceName:`webim_${so}_${n}`,deviceUuid:`webim_${so}_${n}`};return c(t),t}if(n===to){const e=`random_${so}_${s}`;return d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e})}if(void 0!==r){return d({deviceId:`webim_${so}_${n}`,deviceName:n,deviceUuid:`random_${so}_${s}`})}return{deviceId:`webim_${so}_${n}`,deviceName:`webim_${so}_${n}`,deviceUuid:`webim_${so}_${n}`}},ro=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),io=e=>{if(/^\d+$/.test(e))return e;const t=nt.fromString("1099511628211",!0);let s=nt.fromString("1469598103934665603",!0);for(let n=0;n<e.length;n+=1)s=s.xor(nt.fromInt(e.charCodeAt(n),!0)).multiply(t).toUnsigned();return s.isZero()?"1":s.toString()},oo=e=>{if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?`${e}`:"";if("bigint"==typeof e)return e.toString();if(e&&"object"==typeof e&&"low"in e&&"high"in e&&"number"==typeof e.low&&"number"==typeof e.high){const t=e;return new nt(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},ao=e=>{const t=[];for(const[s,n]of Object.entries(e))if(void 0!==n)if("boolean"!=typeof n)if("number"!=typeof n)if("string"!=typeof n)try{t.push({key:s,type:In,stringValue:JSON.stringify(n)})}catch{t.push({key:s,type:yn,stringValue:Object.prototype.toString.call(n)})}else t.push({key:s,type:yn,stringValue:n});else Number.isInteger(n)?t.push({key:s,type:hn,varintValue:n}):t.push({key:s,type:gn,doubleValue:n});else t.push({key:s,type:un,varintValue:n?1:0});return t},co=e=>{if(!e||0===e.length)return{};const t={};for(const s of e){const e="string"==typeof s.key?s.key:"";if(!e)continue;const n="number"==typeof s.type?s.type:yn;if(n!==un)if(n!==hn&&n!==pn&&n!==mn)if(n!==fn)if(n!==gn){if(n!==In)t[e]="string"==typeof s.stringValue?s.stringValue:"";else if("string"==typeof s.stringValue)try{t[e]=JSON.parse(s.stringValue)}catch{t[e]=s.stringValue}}else t[e]=Number(s.doubleValue??0);else t[e]=Number(s.floatValue??0);else t[e]=Number(s.varintValue??0);else t[e]=Boolean(s.varintValue)}return t},lo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),uo=e=>{const t=Array.isArray(e.contents)?e.contents[0]:void 0;return lo(t)?t:void 0};class ho{constructor(e,t=!1){this.userId=e,this.useCustomAttachmentUpload=t}decodeMetadata(e,t,s,n){const r=this.resolveMessageMetaPayload(e.meta,n),i={},o={modifiedInfo:this.resolveModifiedInfo(r),reactions:this.resolveReactions(r),isContentReplaced:this.resolveContentReplaced(r),chatThread:this.resolveChatThreadMessageContext(r),chatThreadOverview:this.resolveChatThreadOverview(r),isPeerRead:this.resolvePeerRead(r,t,s),groupReadCount:this.resolveGroupReadCount(r,t),stream:this.decodeStreamMeta(e.stream,uo(e))};for(const[a,c]of Object.entries(o))void 0!==c&&Object.assign(i,{[a]:c});return o.chatThread&&(i.isChatThread=!0),lo(e.msgConfig)&&e.msgConfig.allowGroupAck&&(i.needReadReceipt=!0),i}decodeContent(e){const t="number"==typeof e.type?e.type:Is,s="string"==typeof e.remotePath&&e.remotePath.length>0||"string"==typeof e.title&&e.title.length>0||"string"==typeof e.summary&&e.summary.length>0||"number"==typeof e.combineLevel&&e.combineLevel>0,n=Object.prototype.hasOwnProperty.call(e,"subType")&&0===e.subType;if(t===ws||t===Is&&(n||s)){return{type:"combine",body:{title:"string"==typeof e.title?e.title:"",summary:"string"==typeof e.summary?e.summary:"",filename:"string"==typeof e.displayName?e.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof e.remotePath?e.remotePath:void 0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,combineLevel:"number"==typeof e.combineLevel?e.combineLevel:0}}}if(t===Is)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===Ts)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===As){const t=co(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Ss)return{type:"location",body:{latitude:"number"==typeof e.latitude?e.latitude:0,longitude:"number"==typeof e.longitude?e.longitude:0,address:"string"==typeof e.address?e.address:void 0,buildingName:"string"==typeof e.buildingName?e.buildingName:void 0}};if(t===vs){const t=e.size??{},s="number"==typeof t.width?t.width:0,n="number"==typeof t.height?t.height:0,r=d(e.imageType)===l,i="string"==typeof e.remotePath?e.remotePath:"",o=u(i,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:s,height:n,isGif:1===e.subType,isOriginalImage:r,originalImageUrl:o.originalImageUrl,bigImageUrl:o.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??o.thumbnailUrl}}}if(t===Cs){const t=e.size??{},s="number"==typeof t.width?t.width:void 0,n="number"==typeof t.height?t.height:void 0,r="string"==typeof e.thumbnailRemotePath?e.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,width:s,height:n,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:r}}}if(t===Es){return{type:"voice",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}if(t===bs){return{type:"file",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}return null}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const s=e,n=Number(oo(s.streamSeq));if(!Number.isFinite(n))return;const r="number"==typeof s.streamStatus?s.streamStatus:Rs,i="number"==typeof s.streamError?s.streamError:0,o="number"==typeof s.streamFinishReason?s.streamFinishReason:void 0,a=this.resolveContentText(t),c=a;return{customType:"string"==typeof s.streamType?s.streamType:void 0,seq:n,status:this.mapStreamStatus(r,i),errorType:i,finishReason:o,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?ss.ERROR:e===Ns?ss.START:e===Ms?ss.START_COMPLETED:e===_s?ss.COMPLETED:e===Ds?ss.FULL:ss.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}resolveContentReplaced(e){const t=this.parseMetaPayload(e);if(t&&Object.prototype.hasOwnProperty.call(t,"callback_replace"))return Boolean(t.callback_replace)}resolveMessageMetaPayload(e,t){const s=this.parseMetaPayload(e),n=this.parseMetaPayload(t);return s&&n?{...n,...s}:s??n??e??t}resolvePeerRead(e,t,s){if("singleChat"!==t||"SEND"!==s)return;const n=this.parseMetaPayload(e);return"boolean"==typeof n?.isRead?n.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const s=this.parseMetaPayload(e),n=s?.group_read_ack;return"number"==typeof n&&Number.isInteger(n)&&n>=0?n:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),s=t?.edit_msg;if(!lo(s))return;const n="string"==typeof s.operator?s.operator:"",r=this.toFiniteNumber(s.count),i=this.toFiniteNumber(s.edit_time);return n&&void 0!==r&&void 0!==i?{operatorId:n,operationCount:r,operationTime:i}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),s=t?.thread;if(!lo(s)||0===Object.keys(s).length)return;const n=this.readString(s.msg_parent_id??s.messageId),r=this.readString(s.muc_parent_id??s.parentId);if(!n||!r)return;const i=this.readString(s.thread_name??s.chatThreadName);return{messageId:n,parentId:r,...i?{chatThreadName:i}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),s=t?.thread_overview??t?.threadOverview;if(!lo(s)||0===Object.keys(s).length)return;const n=this.readString(s.id??s.thread_id??s.chatThreadId),r=this.readString(s.muc_parent_id??s.parentId);if(!n||!r)return;const i=this.readString(s.name),o=this.resolveChatThreadOverviewLastMessage(s.last_message??s.lastMessage,n);return{chatThreadId:n,parentId:r,...i?{name:i}:{},...void 0!==o?{lastMessage:o}:{},...this.numberField("createdAt",s.create_timestamp??s.createdAt),...this.numberField("updatedAt",s.update_timestamp??s.updatedAt),...this.numberField("messageCount",s.message_count??s.messageCount)}}resolveChatThreadOverviewLastMessage(e,t){if(!lo(e)||0===Object.keys(e).length)return null;const s=this.readString(e.msgId??e.msg_id??e.id);if(!s)return null;const n=this.toFiniteNumber(e.timestamp)??0,r=this.resolveThreadLastMessagePayload(e),i=this.readString(r?.from)??this.readString(e.from)??"",o=this.readString(r?.to)??this.readString(e.to)??t,a=Array.isArray(r?.bodies)?r.bodies:[],c=lo(a[0])?a[0]:null,d=this.readString(c?.type)??this.readString(e.type),l=this.mapThreadMessageType(d),u=this.normalizeThreadLastMessageBody(l,c,e),h=t,p=i===this.userId?"SEND":"RECEIVE";return{msgServerId:s,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:h,conversationType:"groupChat",type:l,sendStatus:"sent",ext:lo(r?.ext)?r.ext:{},timestamp:n,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(lo(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return null}mapThreadMessageType(e){switch(e){case"txt":default:return"text";case"img":return"image";case"loc":return"location";case"audio":return"voice";case"video":return"video";case"file":return"file";case"cmd":return"cmd";case"custom":return"custom";case"combine":return"combine";case"text":case"image":case"voice":case"location":return e}}normalizeThreadLastMessageBody(e,t,s){if(!t){return{content:this.readString(s.msg??s.content??s.text)??""}}switch(e){case"text":default:return{content:this.readString(t.msg??t.content??t.text)??""};case"image":{const e=this.readString(t.url)??"",s=u(e,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(t.filename)??"image",filetype:this.readString(t.filetype)??"application/octet-stream",width:this.toFiniteNumber(t.width)??0,height:this.toFiniteNumber(t.height)??0,isGif:!0===t.isGif,isOriginalImage:!1,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,thumbnailUrl:this.readString(t.thumb)??s.thumbnailUrl,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)}}case"voice":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"voice",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"video":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"video",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,width:this.toFiniteNumber(t.width),height:this.toFiniteNumber(t.height),thumbnailUrl:this.readString(t.thumb),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"file":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"file",filetype:this.readString(t.filetype)??"application/octet-stream",secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"location":return{latitude:this.toFiniteNumber(t.lat??t.latitude)??0,longitude:this.toFiniteNumber(t.lng??t.longitude)??0,address:this.readString(t.addr??t.address),buildingName:this.readString(t.buildingName)};case"cmd":return{action:this.readString(t.action)??""};case"custom":return{event:this.readString(t.event??t.customEvent)??"",params:lo(t.params??t.customExts)?t.params??t.customExts:{}};case"combine":return{title:this.readString(t.title)??"",summary:this.readString(t.summary)??"",filename:this.readString(t.filename)??"combine",filetype:"application/octet-stream",url:this.readString(t.url),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength),combineLevel:this.toFiniteNumber(t.combineLevel)??0}}}readString(e){return"string"==typeof e&&e.length>0?e:void 0}numberField(e,t){const s=this.toFiniteNumber(t);return void 0===s?{}:{[e]:s}}parseMetaPayload(e){const t=this.normalizeMetaPayload(e);if(t){if(0===t.length)return null;try{const e=JSON.parse(kn(t));return lo(e)?e:null}catch{return null}}if(lo(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return lo(t)?t:null}catch{return null}return null}toFiniteNumber(e){const t="number"==typeof e?e:"string"==typeof e?Number(e):Number.NaN;return Number.isFinite(t)?t:void 0}resolveReactions(e){const t=this.parseMetaPayload(e),s=t?.reaction;if(Array.isArray(s)&&0!==s.length)return s.filter(lo).map(e=>({reaction:"string"==typeof e.reaction?e.reaction:"",count:"number"==typeof e.count?e.count:0,userList:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof e.state?e.state:void 0}))}normalizeMetaPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}}const po=(e,t)=>{for(const s of[e,t])if(s&&"object"==typeof s&&"name"in s&&"string"==typeof s.name&&s.name.length>0)return s.name;return""},mo=/* @__PURE__ */new Set(["mute"]),fo={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},go=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},yo=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Io=(e,t)=>{const s=e?.map(e=>go(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},vo=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=yo(t);if(!n)return;const r=n.muteExpire??n.mute_expire??n.expire??n.expired??n.expireAt??n.expiredAt,i=Number(r);return Number.isFinite(i)&&i>0?i:void 0},Co=e=>{const t=yo(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=fo[n];if(!e)continue;let t=r;if(mo.has(n))t=!0===r||"true"===r;else if("max_users"===n){const e=Number(r);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},So=e=>{const t=yo(e);if(!t)return{attributes:{},keyList:[]};const s=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},n=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},r=Array.isArray(s.successKeys)?s.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(r.map(e=>[e,n[e]]).filter(e=>"string"==typeof e[1])),keyList:r,from:go(t.operator)??go(t.username)}},Eo=(e,t)=>({eventName:e,payload:t}),bo=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=go(e.from?.name),n=(r=e.to,go(r?.[0]?.name));var r;switch(e.operation){case 1:return Eo(Bt,t);case 10:return Eo(Gt,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:n??s});case 17:return Eo(qt,{...t,memberIds:Io(e.members,s),ext:e.ext??e.eventExt});case 18:return Eo(Kt,{...t,memberIds:Io(e.members,s)});case 20:return Eo(Yt,{...t,oldOwnerId:s,newOwnerId:n});case 21:return Eo(Qt,{...t,adminId:n??s});case 22:return Eo($t,{...t,adminId:n??s});case 23:{const s=(e=>{const t=yo(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const n={};for(const[r,i]of Object.entries(s)){const e=Number(i);r&&Number.isFinite(e)&&(n[r]=e)}return Object.keys(n).length>0?n:null})(e.ext??e.eventExt),r=s?Object.keys(s):Io(e.members,n),i=46388736e5;return Eo(Vt,{...t,userIds:r,muteMembers:s??Object.fromEntries(r.map(e=>[e,i])),muteExpire:vo(e.reason,e.eventExt)??i})}case 24:return Eo(Ht,{...t,userIds:Io(e.members,n)});case 25:return Eo(Jt,{...t,announcement:e.reason??""});case 26:return Eo(Jt,{...t,announcement:""});case 29:return Eo(zt,{...t,userIds:Io(e.members,n)});case 30:return Eo(jt,{...t,userIds:Io(e.members,n)});case 31:return Eo(Wt,{...t,isMuted:!0});case 32:return Eo(Wt,{...t,isMuted:!1});case 14:return Eo(Xt,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Co(e.eventExt)});case 43:{const n=So(e.eventExt);return Eo(Zt,{...t,attributes:n.attributes,from:n.from??s})}case 44:{const n=So(e.eventExt);return Eo(es,{...t,keyList:n.keyList,from:n.from??s})}default:return null}},To=/* @__PURE__ */new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Ao={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},wo=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},No=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Mo=(e,t)=>{const s=e?.map(e=>wo(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Ro=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=No(t);if(!n)return;const r=n.muteExpire??n.mute_expire??n.expire??n.expired??n.expireAt??n.expiredAt,i=Number(r);return Number.isFinite(i)&&i>0?i:void 0},_o=e=>{const t=No(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=Ao[n];if(!e)continue;let t=r;if(To.has(n))t=!0===r||"true"===r;else if("max_users"===n){const e=Number(r);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},Do=(e,t)=>{const s=No(t)??No(e);return pt(s??void 0)??void 0},Uo=(e,t)=>{const s=No(t)??No(e);return wo(s?.fileId)??wo(s?.file_id)??wo(e)??""},Lo=(e,t)=>({eventName:e,payload:t}),Oo=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=wo(e.from?.name),n=(r=e.to,wo(r?.[0]?.name));var r;switch(e.operation){case 4:return Lo(at.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return Lo(at.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return Lo(at.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:n,reason:e.reason});case 7:return Lo(at.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return Lo(at.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return Lo(at.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return Lo(at.USER_REMOVED,t);case 1:return Lo(at.GROUP_DESTROYED,t);case 19:return Lo(at.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=No(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const n={};for(const[r,i]of Object.entries(s)){const e=wo(r),t=Number(i);e&&Number.isFinite(t)&&t>0&&(n[e]=t)}return Object.keys(n).length>0?n:null})(e.ext),r=s?Object.keys(s):Mo(e.members,n);return Lo(at.MUTE_LIST_ADDED,{...t,userIds:r,muteExpire:r.map(e=>s?.[e]).find(e=>void 0!==e)??Ro(e.reason,e.eventExt)})}case 24:return Lo(at.MUTE_LIST_REMOVED,{...t,userIds:Mo(e.members,n)});case 29:return Lo(at.ALLOW_LIST_ADDED,{...t,userIds:Mo(e.members,n)});case 30:return Lo(at.ALLOW_LIST_REMOVED,{...t,userIds:Mo(e.members,n)});case 31:return Lo(at.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return Lo(at.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return Lo(at.ADMIN_ADDED,{...t,administratorId:n??s});case 22:return Lo(at.ADMIN_REMOVED,{...t,administratorId:n??s});case 20:return Lo(at.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:n});case 17:{const n=Mo(e.members,s);return Lo(at.MEMBERS_JOINED,{...t,memberIds:n})}case 18:{const n=Mo(e.members,s);return Lo(at.MEMBERS_EXITED,{...t,memberIds:n})}case 25:return Lo(at.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return Lo(at.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return Lo(at.SHARED_FILE_ADDED,{...t,sharedFile:Do(e.reason,e.eventExt)});case 28:return Lo(at.SHARED_FILE_DELETED,{...t,fileId:Uo(e.reason,e.eventExt)});case 14:return Lo(at.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:_o(e.eventExt)});case 41:return Lo(at.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Lo(at.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const n=(e=>{const t=No(e);if(!t)return{attribute:{}};const s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Object.fromEntries(Object.entries(s).filter(e=>"string"==typeof e[1]));return{userId:wo(t.username),attribute:n}})(e.eventExt);return Lo(at.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:n.userId,attribute:n.attribute,from:s,source:e.source??"direct"})}default:return null}},ko=/* @__PURE__ */new WeakMap,Po=(e,t)=>{ko.set(e,t)},xo=e=>ko.get(e)??null,Fo=(e,t)=>{const s=xo(e);s&&Po(t,s)},Bo=/* @__PURE__ */new WeakMap,qo=e=>Bo.get(e),Ko="singleChat",Go="groupChat",Vo={MARK_0:0,MARK_1:1,MARK_2:2,MARK_3:3,MARK_4:4,MARK_5:5,MARK_6:6,MARK_7:7,MARK_8:8,MARK_9:9,MARK_10:10,MARK_11:11,MARK_12:12,MARK_13:13,MARK_14:14,MARK_15:15,MARK_16:16,MARK_17:17,MARK_18:18,MARK_19:19},Ho=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},zo=e=>{if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&e.trim().length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},jo=e=>{if(!Array.isArray(e))return;const t=e.map(e=>Ho(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},Wo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Qo=(...e)=>{for(const t of e){const e=Ho(t);if(e)return e}},$o=(e,t)=>Boolean(e&&t&&e===t),Yo=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),Jo=(e,t,s)=>{const n=jo(e);if(n&&n.length>0)return n;const r=(t??[]).map(e=>Ho(e.name)).filter(e=>"string"==typeof e);if(r.length>0)return r;const i=Ho(s?.name);return i?[i]:[]},Xo=e=>{const t=zo(e);if(void 0!==t)return t;if("string"==typeof e){const t=e.match(/(\d+)/);if(t){const e=Number(t[1]);return Number.isFinite(e)?e:void 0}}},Zo=(e,t)=>{const s=Qo(e.to?.[0]?.clientResource);if(1!==e.to?.length||Ho(e.to[0]?.name)!==t.userId||!Yo(t.userId,s,t))return null;const n=(r=e.from,Ho(r?.name)??"");var r;if(!n)return a.warn("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return a.warn("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:n,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:s,timestamp:e.timestamp,raw:e.raw}},ea=(e,t)=>{if(!e.groupId)return a.warn("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const s=Qo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Yo(Ho(e.from?.name),s,t))return null;const n=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return a.warn("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===n)return null;const r=Jo(e.members,e.to,e.from);return{category:"group",operation:n,groupId:e.groupId,userIds:r.length>0?r:void 0,operatorId:Ho(e.from?.name),groupName:e.groupName,deviceId:s,timestamp:e.timestamp,raw:e.raw}},ta=(e,t)=>{if(!e.threadId)return a.warn("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const s=Qo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Yo(Ho(e.from?.name),s,t))return null;const n=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return a.warn("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===n)return null;const r=Jo(e.members,e.to,e.from);return{category:"thread",operation:n,threadId:e.threadId,parentId:e.parentId,userIds:r.length>0?r:void 0,operatorId:Ho(e.from?.name),threadName:e.threadName,deviceId:s,timestamp:e.timestamp,raw:e.raw}},sa=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const s=Qo(e.res,e.raw?.resource,e.raw?.clientResource);if($o(s,t.clientResource))return a.debug("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const n="chat"===(r=e.type)||"singleChat"===r?Ko:Go;var r;const i=Ho(e.id)??(n===Ko?Ho(e.from):void 0);if(!i)return a.warn("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return a.warn("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:n,mark:"mark"===e.operation||"mark_delete"===e.operation?Xo(e.ext):void 0,operatorId:Ho(e.from),deviceId:s,timestamp:zo(e.ts),raw:e.raw}},na=(e,t)=>{const s=Qo(e.resource,e.raw?.resource,e.raw?.clientResource);if($o(s,t.clientResource))return a.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const n=Ho(e.to);if(!n)return a.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const r=Ho(e.lastMsgId),i=jo(e.msgIdList)??(r?[r]:void 0),o=zo(e.deleteTime);if(!i&&void 0===o)return a.warn("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:n}),null;const c=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(a.warn("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===c?null:{category:"messageRemoved",operation:c,conversationId:n,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?Go:Ko,messageIds:i,beforeTimestamp:o,deviceId:s,raw:e.raw}},ra=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var ia=4096,oa=65547,aa=15,ca=2113929216,da=65536,la=65536,ua=10485760,ha={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},pa={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function ma(e){if(!(e>0))return la;if(e<=la)return la;if(e>1073741823)return e;for(var t=la;t<e;)t*=2;return t}var fa={byU16:0,byU32:1},ga=0,ya=1,Ia=2,va=0,Ca=1;function Sa(e,t){return e[t]|e[t+1]<<8}function Ea(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function ba(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var Ta="fast";function Aa(e){return 2654435761*(e>>>0)>>>20&4095}function wa(e){return 2654435761*(e>>>0)>>>19&8191}function Na(e,t,s){if("fast"===Ta){var n=Ea(e,t);return s===fa.byU16?wa(n):Aa(n)}throw new Error("Unsupported hash strategy: "+Ta)}function Ma(e,t,s,n,r){s[t]=e-r}function Ra(e,t,s,n,r){Ma(t,Na(e,t,n),s,0,r)}function _a(e,t,s,n){return t[e]+n}function Da(e,t,s,n,r){return _a(Na(e,t,n),s,0,r)}function Ua(e,t,s,n){for(var r=t;t<n-3;){if(Ea(e,t)!==Ea(e,s)){for(;t<n&&e[t]===e[s];)t++,s++;return t-r}t+=4,s+=4}for(;t<n&&e[t]===e[s];)t++,s++;return t-r}function La(e,t,s,n,r,i,o,a,c,d){var l,u,h,p=e.hashTable,m=n,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,I=y+e.dictSize,v=e.dictSize>0?I-n:0,C=n,S=n+r,E=S-12,b=S-5,T=0,A=i>0?i:s.length,w=0;if(r>ca)return 0;switch(c){case ga:default:l=n,u=n;break;case ya:l=n-e.currentOffset,u=n-e.dictSize;break;case Ia:l=n-e.currentOffset,u=n}if(a===fa.byU16&&r>=oa)return 0;if(r<13)return Pa(t,s,C,S,T,A,o);Ra(t,m,p,a,l),h=Na(t,++m,a);e:for(;;){var N,M,R=m,_=1,D=64;do{var U=h;if(m=R,R+=_,_=D++>>>6,R>E)return Pa(t,s,C,S,T,A,o);N=_a(U,p,0,l),c===Ia&&(N<n?(w=v,u=y):(w=0,u=n)),h=Na(t,R,a),Ma(m,U,p,0,l)}while(d===Ca&&N<f||a!==fa.byU16&&N+65535<m||!Oa(t,g,m,N,w,c,n));for(;m>C&&N+w>u;){var L=N+w-1;if(t[m-1]!==(c===Ia&&N<n?g[L-y+e.dictionaryStart]:t[L]))break;m--,N--}var O=m-C;if(M=T++,o&&T+O+8+Math.floor(O/255)>A)return 0;if(O>=aa){var k=O-aa;for(s[M]=240;k>=255;)s[T++]=255,k-=255;s[T++]=k}else s[M]=O<<4;if(O>=16&&s.set&&t.subarray)s.set(t.subarray(C,C+O),T),T+=O;else for(var P=0;P<O;P++)s[T++]=t[C+P];t:for(;;){var x;if(ba(s,T,m-N),T+=2,c===Ia&&N<n){var F=m+(I-(N+w));if(F>b&&(F=b),(m+=4+(x=ka(t,g,m+4,N+w+4-y+e.dictionaryStart,F,I-y)))===F&&F<b){var B=Ua(t,m,n,b);x+=B,m+=B}}else m+=4+(x=Ua(t,m+4,N+4,b));if(o&&T+6+(x>>>8)>A)return 0;if(x>=15){for(s[M]+=15,x-=15;x>=510;)s[T++]=255,s[T++]=255,x-=510;x>=255&&(x-=255,s[T++]=255),s[T++]=x}else s[M]+=x;if(C=m,m>E)break e;if(Ra(t,m-2,p,a,l),N=Da(t,m,p,a,l),c===Ia&&(N<n?(w=v,u=y):(w=0,u=n)),Ra(t,m,p,a,l),!((d!==Ca||N>=f)&&N+65535>=m&&Oa(t,g,m,N,w,c,n)))break t;s[M=T++]=0}h=Na(t,++m,a)}return Pa(t,s,C,S,T,A,o)}function Oa(e,t,s,n,r,i,o){var a,c=Ea(e,s);i===Ia&&n+r<o?a=Ea(t,n+r):a=Ea(e,n+r);return c===a}function ka(e,t,s,n,r,i,o){for(var a=s;n<i&&s<r&&t[n]===e[s];)n++,s++;return s-a}function Pa(e,t,s,n,r,i,o){var a=n-s;if(o&&r+a+1+Math.floor((a+255-aa)/255)>i)return 0;if(a>=aa){for(t[r++]=240,a-=aa;a>=255;)t[r++]=255,a-=255;t[r++]=a}else t[r++]=a<<4;var c=s,d=n,l=d-c;if(l>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),r),r+=l;else for(var u=c;u<d;u++)t[r++]=e[u];return r}function xa(e,t,s,n){var r,i=0;if(n&&t.ip>=s)return-1;do{if(i+=r=e[t.ip++],t.ip>s)return-1;if(i>2147483647)return-1}while(255===r);return i}function Fa(e,t,s,n,r,i,o,a,c,d,l,u,h){if(null==e)return-1;if(i<0)return-1;var p=s,m=s+n,f=r,g=r+i,y=l-h,I=u+h,v=h<65536;if(0===i)return 1===n&&0===e[p]?0:-1;if(0===n)return-1;for(;;){var C,S,E,b;if(p>=m)return-(p-s)-1;if((S=(C=e[p++])>>>4)===aa){var T=xa(e,N={ip:p},m-aa,!0);if(p=N.ip,-1===T)return-(p-s)-1;if(f+(S+=T)<f)return-(p-s)-1;if(p+S<p)return-(p-s)-1}if(E=f+S,o&&(E>g-12||p+S>m-8)||!o&&E>g-8){if(!o&&E!==g)return-(p-s)-1;if(o&&(p+S!==m||E>g))return-(p-s)-1;if(S>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+S),f);else for(var A=0;A<S;A++)t[f+A]=e[p+A];p+=S,f+=S;break}if(S>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+S),f);else for(A=0;A<S;A++)t[f+A]=e[p+A];if(f=E,(p+=S)+2>m)return-(p-s)-1;var w=Sa(e,p);if(p+=2,b=E-w,v&&b+h<l)return-(p-s)-1;if(0===w)return-(p-s)-1;if(15===(S=15&C)){var N;T=xa(e,N={ip:p},m-5+1,!1);if(p=N.ip,-1===T)return-(p-s)-1;if(f+(S+=T)<f)return-(p-s)-1}if(S+=4,d===Ia&&b<l){if(f+S>g-5)return-(p-s)-1;if(S<=l-b){var M=I-(l-b);for(A=0;A<S;A++)t[f+A]=t[M+A];f+=S}else{var R=l-b;for(M=I-R,A=0;A<R;A++)t[f+A]=t[M+A];var _=S-R;if(_>(f+=R)-l)for(var D=l,U=f+_;f<U;)t[f++]=t[D++];else{for(A=0;A<_;A++)t[f+A]=t[l+A];f+=_}}}else{if(b<y)return-(p-s)-1;if(E=f+S,f-b<8)for(t[f]=t[b],t[f+1]=t[b+1],t[f+2]=t[b+2],t[f+3]=t[b+3],f+=4,b+=4;f<E;)t[f++]=t[b++];else for(;f<E;)t[f++]=t[b++]}}return o?f-r:p-s}function Ba(){return{hashTable:new Uint32Array(ia),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function qa(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function Ka(e,t,s,n,r,i,o,a){n=n||0;var c=e.dictionaryStart+e.dictSize,d=n;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,s=e.dictionaryStart+e.dictSize,n=0;n<e.hashTable.length;n++)e.hashTable[n]<t?e.hashTable[n]=0:e.hashTable[n]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=s-e.dictSize}}(e);var l,u=n+r;e.dictionary&&u>e.dictionaryStart&&u<c&&(e.dictSize=c-u,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var h=e.dictSize<65536&&e.dictSize<e.currentOffset?Ca:va;return e.dictionary&&c===n?(l=La(e,t,s,n,r,o||0,a||!1,fa.byU32,ya,h),e.dictSize+=r,e.currentOffset+=r,l):(l=La(e,t,s,n,r,o||0,a||!1,fa.byU32,Ia,h),e.dictionary=t,e.dictionaryStart=n,e.dictSize=r,e.currentOffset+=r,l)}function Ga(e,t,s,n){var r=e.dictionaryStart+e.dictSize;n>65536&&(n=65536),n>e.dictSize&&(n=e.dictSize);var i=r-n;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(i,i+n),s);else for(var o=0;o<n;o++)t[s+o]=e.dictionary[i+o];return e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,n}function Va(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function Ha(e,t,s,n){return e.prefixSize=n,e.prefixEnd=s+n,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function za(e,t,s,n,r,i,o){var a;if(e.prefixEnd===i){if((a=Fa(t,s,n,r,i,o,!0,0,0,Ia,e.prefixEnd-e.prefixSize,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize+=a,e.prefixEnd+=a}else{if(e.extDictSize=e.prefixSize,e.extDictStart=e.prefixEnd-e.extDictSize,(a=Fa(t,s,n,r,i,o,!0,0,0,Ia,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function ja(e){var t=(e=e||{}).minWorkArea||la,s=e.maxWorkArea||ua,n=e.shrinkThreshold||t;t<la&&(t=la),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=da+t,this.maxBufferSize=da+s,this.shrinkThreshold=da+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ha.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=Ba()}function Wa(e){var t=(e=e||{}).minWorkArea||la,s=e.maxWorkArea||ua,n=e.shrinkThreshold||t;t<la&&(t=la),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=da+t,this.maxBufferSize=da+s,this.shrinkThreshold=da+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ha.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}ja.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<da?this.offset:da,r=this.offset>da?this.offset-da:0;t.set(this.ringBuffer.subarray(r,r+n),0),Ga(this.stream,t,0,n),s=n}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},ja.prototype.compress=function(e,t){var s=e.length;if(s<=0)return pa.PARAM_ERROR;if(s>this.maxBufferSize-da)return pa.PARAM_ERROR;if(s>this.ringBufferSize-da){var n=ma(s),r=da+n;if(r>this.maxBufferSize&&(r=this.maxBufferSize),!this._resizeBuffer(r))return pa.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(Ga(this.stream,this.ringBuffer,0,da),this.offset=da);var i=this.offset;this.ringBuffer.set(e,i);var o=Ka(this.stream,this.ringBuffer,t,i,s,0,t.length,!0);return o<=0?pa.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),o)},ja.prototype.reset=function(){this.offset=0,qa(this.stream)},ja.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},ja.prototype._tryAutoShrink=function(){this.shrinkMode!==ha.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ha.AUTO_IMMEDIATE||this.shrinkMode===ha.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},ja.prototype.getWorkArea=function(){return this.ringBufferSize-da},ja.prototype.getRingBufferSize=function(){return this.ringBufferSize},ja.prototype.getBaseBufferSize=function(){return this.minBufferSize},ja.prototype.getMaxBufferSize=function(){return this.maxBufferSize},ja.prototype.getCurrentOffset=function(){return this.offset},ja.prototype.getShrinkMode=function(){return this.shrinkMode},ja.prototype.setShrinkMode=function(e){this.shrinkMode=e},ja.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},ja.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-da,s=this.maxBufferSize-da;if(e<t||e>s)return pa.PARAM_ERROR;this.shrinkThreshold=da+e},Wa.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<da?this.offset:da,r=this.offset>da?this.offset-da:0;t.set(this.ringBuffer.subarray(r,r+n),0),s=n,Ha(this.streamDecode,0,0,n)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Wa.prototype.decompress=function(e,t,s){var n=e.length;if(n<=0||s<=0)return pa.PARAM_ERROR;if(s>this.maxBufferSize-da)return pa.PARAM_ERROR;if(s>this.ringBufferSize-da){var r=ma(s),i=da+r;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return pa.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var o=this.offset-da;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+da),0),Ha(this.streamDecode,this.ringBuffer,0,da),this.offset=da}var a=za(this.streamDecode,e,this.ringBuffer,0,n,this.offset,s);return a<=0?pa.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Wa.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Wa.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Wa.prototype._tryAutoShrink=function(){this.shrinkMode!==ha.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ha.AUTO_IMMEDIATE||this.shrinkMode===ha.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Wa.prototype.getWorkArea=function(){return this.ringBufferSize-da},Wa.prototype.getRingBufferSize=function(){return this.ringBufferSize},Wa.prototype.getBaseBufferSize=function(){return this.minBufferSize},Wa.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Wa.prototype.getCurrentOffset=function(){return this.offset},Wa.prototype.getShrinkMode=function(){return this.shrinkMode},Wa.prototype.setShrinkMode=function(e){this.shrinkMode=e},Wa.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Wa.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-da,s=this.maxBufferSize-da;if(e<t||e>s)return pa.PARAM_ERROR;this.shrinkThreshold=da+e};const Qa={LZ4_MAX_INPUT_SIZE:ca,BLOCK_MAX_SIZE:65536,DICT_SIZE:da,DEFAULT_WORK_AREA:la,DEFAULT_MAX_WORK:ua,SHRINK_MODE:ha,LZ4_ERROR:pa,alignToPowerOf2:ma,calcDefaultBufferSize:function(){return 131072},calcDefaultMaxBufferSize:function(){return 10551296},setHashStrategy:function(e){if("fast"!==e&&"compatible"!==e)throw new Error("Invalid hash strategy: "+e+'. Use "fast" or "compatible".');Ta=e},getHashStrategy:function(){return Ta},compress:function(e,t,s,n,r){if(null==e)return 0;if(null==t)return 0;if(s=s||0,n=void 0===n?e.length:n,r=r||0,s<0||r<0)return 0;if(n<0)return 0;if(s+n>e.length)return 0;if(n>ca)return 0;if(0===n)return t.length>r?(t[r]=0,1):0;var i=n<oa?fa.byU16:fa.byU32;return La({hashTable:new Uint32Array(i===fa.byU16?8192:ia),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,0,!1,i,ga,va)},compressLimited:function(e,t,s,n,r,i){if(null==e)return 0;if(null==t)return 0;if(s=s||0,n=void 0===n?e.length:n,r=r||0,s<0||r<0)return 0;if(n<0||i<0)return 0;if(s+n>e.length)return 0;if(n>ca)return 0;if(i<1)return 0;if(0===n)return t[r]=0,1;var o=n<oa?fa.byU16:fa.byU32;return La({hashTable:new Uint32Array(o===fa.byU16?8192:ia),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,i,!0,o,ga,va)},compressBound:function(e){return e<0||e>ca?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,s,n,r,i){return null==e||null==t?-1:(r=r||0,(s=s||0)<0||r<0||n<0||i<0||s+n>e.length||r+i>t.length?-1:Fa(e,t,s,n,r,i,!0,0,0,ga,r,null,0))},decompressFast:function(e,t,s,n,r){return Fa(e,t,s=s||0,0,n=n||0,r,!1,0,0,ya,n-65536,0,65536)},createStream:Ba,resetStream:qa,loadDict:function(e,t,s,n){if(e.initCheck&&qa(e),n<4)return e.dictionary=null,e.dictSize=0,0;n>65536&&(s=s+n-65536,n=65536);var r=s-e.currentOffset;e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n;for(var i=s,o=s+n;i<=o-4;)Ra(t,i,e.hashTable,fa.byU32,r),i+=3;return n},compressContinue:Ka,saveDict:Ga,createStreamDecode:Va,setStreamDecode:Ha,decompressSafeContinue:za,RingBufferEncoder:ja,RingBufferDecoder:Wa,_hashU16:wa,_hashU32:Aa,_TABLE_TYPE:fa},$a=268435455,Ya=new Uint32Array(256);let Ja=!1;function Xa(e){!function(){if(!Ja){for(let e=0;e<256;e+=1){let t=e;for(let e=0;e<8;e+=1)t=1&t?3988292384^t>>>1:t>>>1;Ya[e]=t>>>0}Ja=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const n=e[s]??0;t=t>>>8^(Ya[255&(t^255&n)]??0)}return(4294967295^t)>>>0}var Za=/* @__PURE__ */(e=>(e[e.NONE=-1]="NONE",e[e.UPLINK_ONLY=0]="UPLINK_ONLY",e[e.DOWNLINK_ONLY=1]="DOWNLINK_ONLY",e[e.BIDIRECTIONAL=2]="BIDIRECTIONAL",e))(Za||{});const ec=268435455;class tc{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Qa.DEFAULT_WORK_AREA,maxWorkArea:Qa.DEFAULT_MAX_WORK,shrinkMode:Qa.SHRINK_MODE.MANUAL};this.encoder=new Qa.RingBufferEncoder(e),this.decoder=new Qa.RingBufferDecoder(e)}compress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length>ec)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=Qa.compressBound(t.length),n=new Uint8Array(s),r=this.encoder.compress(t,n);if(r<0)throw new Error(`LZ4 compression failed with error code: ${r}`);const i=n.subarray(0,r),o=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>$a)throw new Error("encodeLength: Length exceeds maximum: 268435455");if(0===e)return new Uint8Array([0]);const t=[];let s=e;for(;s>0;){let e=127&s;s>>>=7,s>0&&(e|=128),t.push(e)}return new Uint8Array(t)}(t.length),a=Xa(t),c=new Uint8Array(o.length+4+r);let d=0;c.set(o,d),d+=o.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(i,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const s={offset:0},n=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let s=0,n=0;for(;t.offset<e.length;){const r=e[t.offset]??0;if(t.offset+=1,s|=(127&r)<<n,!(128&r))return s>>>0;if(n+=7,n>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,s);if(n>ec)throw new Error(`Original size exceeds maximum allowed: ${n}`);if(t.length<s.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const r=new DataView(t.buffer,t.byteOffset+s.offset,4).getUint32(0,!1);s.offset+=4;const i=t.subarray(s.offset),o=new Uint8Array(n),a=this.decoder.decompress(i,o,n);if(a<0||a!==n)throw new Error(`LZ4 decompression failed: expected ${n}, got ${a}`);const c=Xa(o);if(c!==r)throw new Error(`CRC32 checksum mismatch: expected ${r}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const sc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nc=(e,t)=>rt(e,t).finish();class rc{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=no({useFixedDeviceId:e.useFixedDeviceId??!0,deviceId:e.deviceId??"webim",customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform}),s=`${Date.now()}:`;return{appKey:e.appKey,userId:e.userId,token:e.token,domain:e.domain??"easemob.com",version:e.version??"4.11.0",uiKitVersion:e.uiKitVersion,osType:void 0!==e.customOSPlatform?5:e.osType??16,deviceId:t.deviceId,deviceName:t.deviceName,deviceUuid:t.deviceUuid,clientResource:t.deviceId,customOSPlatform:e.customOSPlatform,loginExtensionInfo:e.loginExtensionInfo,encryptType:[qs],compressType:[Ks],sessionId:s,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.payloadDecoder=new ho(this.context.userId,e.useCustomAttachmentUpload??!1)}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=Zi(),t=e.lookupType("easemob.pb.Provision"),s=e.lookupType("easemob.pb.MSync"),n={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Ks],encryptType:[qs],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},r=nc(t,n),i={version:0,guid:ro({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:as,deviceId:0,encryptType:[qs],payload:r,traceId:h()};return nc(s,i)}encodeHeartbeat(){const e=Zi(),t=e.lookupType("easemob.pb.CommUnreadUL"),s=e.lookupType("easemob.pb.MSync"),n=nc(t,{}),r={version:0,encryptType:[qs],command:is,payload:n,traceId:h()};return nc(s,r)}encodeStatisticRebuild(){const e=Zi(),t=e.lookupType("easemob.pb.StatisticsBody"),s=e.lookupType("easemob.pb.Meta"),n=e.lookupType("easemob.pb.CommSyncUL"),r=e.lookupType("easemob.pb.MSync"),i=nc(t,{operation:0}),o=s.decode(new Uint8Array);o.id=Date.now(),o.ns=Us,o.payload=i;const a=n.decode(new Uint8Array);a.meta=o;const c=nc(n,a);return nc(r,{version:0,encryptType:[qs],command:rs,payload:c,traceId:h()})}decodeProvision(e){const t=Zi().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},n="number"==typeof s.errorCode?s.errorCode:Hs,r="string"==typeof s.reason?s.reason:void 0,i="string"==typeof t.resource?t.resource:void 0,o="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:n===Vs,statusCode:n,reason:r,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Zi().lookupType("easemob.pb.Logout").decode(e),s=t.status&&"object"==typeof t.status?t.status:void 0;return{sessionId:"string"==typeof t.sessionId?t.sessionId:void 0,reason:"string"==typeof t.reason?t.reason:void 0,statusCode:"number"==typeof s?.errorCode?s.errorCode:void 0}}decodeSyncStatisticOperations(e){const t=Zi().lookupType("easemob.pb.CommSyncDL").decode(e),s=Array.isArray(t.metas)?t.metas:[],n=[];for(const r of s){const e=this.decodeStatisticMeta(r);e&&n.push(e)}return n}decodeMsync(e){const t=Zi().lookupType("easemob.pb.MSync").decode(e);return{command:"number"==typeof t.command?t.command:-1,payload:this.normalizeBinaryPayload(t.payload)}}normalizeBinaryPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array}decodeSync(e){const t=Zi(),s=t.lookupType("easemob.pb.CommSyncDL"),n=t.lookupType("easemob.pb.MessageBody"),r=s.decode(e);a.debug("decodeSync commSyncDl",{hasMetas:Array.isArray(r.metas)});const i=Array.isArray(r.metas)?r.metas:[],o=this.decodeAck(r);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const c=oo(r.metaId),d=oo(r.nextKey),l=r.queue??void 0,u="boolean"==typeof r.isLast?r.isLast:void 0,h=[],p=[];if(c&&"0"!==c){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,n):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&p.push(...e)}return{ack:o,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u,replacedMessage:e}}for(const a of i){const e=this.decodeChatMeta(a,n);e&&h.push(e);const t=this.decodeChatActionMeta(a,n);t&&p.push(t);const s=this.decodeNotifyMeta(a);s.length>0&&p.push(...s)}return{ack:o,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u}}decodeReplacedMessage(e,t){for(const s of e){const e=this.decodeChatMeta(s,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const s=e,n=s.payload;let r=null;if(n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!r)return null;if(("number"==typeof s.ns?s.ns:void 0)!==Ls)return null;try{const e=t.decode(r);if(!e||"object"!=typeof e)return null;const n=e;return this.decodeMessage(s,n)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const s=e,n=s.payload;let r=null;if(n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!r)return null;if(("number"==typeof s.ns?s.ns:void 0)!==Ls)return null;try{const e=t.decode(r);if(!e||"object"!=typeof e)return null;const n=e,i="number"==typeof n.type?n.type:ds;if(i!==ps&&i!==fs&&i!==gs&&i!==ys&&i!==ms)return null;const o=this.readJid(s.to),c=Number(oo(s.timestamp))||Date.now(),d=this.resolveActionConversationType(o.domain,n.meta,n),{senderId:l,receiverId:u}=this.resolveIncomingMessageParties(s,n,d),h=this.resolveActionConversationId(l,u,d);if(i===gs)return!0===n.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:c}}:h?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:c}}:null;if(i===ps){a.debug("Received READ_ACK MessageBody",n);const e=(Array.isArray(n.ackMessageIds)?n.ackMessageIds:[]).map(e=>oo(e)).filter(e=>Boolean(e)),t=oo(n.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!h)return null;const s=co(Array.isArray(n.ext)?n.ext.filter(sc):void 0),r=sc(s.group_ack_count)?s.group_ack_count:{},i=e.flatMap(e=>{const t=r[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:c,..."groupChat"===d?{receiptDetails:i}:{}}}}if(i===ms){const e=oo(n.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(i===fs){const e=oo(n.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=oo(n.editMessageId),m=(Array.isArray(n.contents)?n.contents:[])[0],f=m?this.decodeContent(m):null;if(!p||!h||!f)return null;const g=this.payloadDecoder.resolveModifiedInfo(n.meta);return{type:"message_updated",data:{messageId:p,conversationId:h,conversationType:d,timestamp:c,message:{type:f.type,body:f.body,ext:co(n.ext),...g?{modifiedInfo:g}:{}}}}}catch{return null}}decodeNotifyMeta(e){if(!e||"object"!=typeof e)return[];const t=e,s="number"==typeof t.ns?t.ns:void 0;if(s!==Ps&&s!==ks&&s!==Os&&s!==Us)return[];const n=t.payload;let r=null;return n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),r?s===ks?this.decodeRosterMeta(t,r):s===Os?this.decodeMucMeta(t,r):s===Us?this.decodeStatisticGroupReceiptNotifies(t,r):this.decodeNotifyPayload(r):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const s=Zi(),n=s.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof n.location||0===n.location.length)return[];const r=JSON.parse(n.location);if(!sc(r)||!Array.isArray(r.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=/* @__PURE__ */new Map;for(const e of r.group_ack){if(!sc(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[s,n]of Object.entries(e)){if("groupId"===s)continue;const e="number"==typeof n?n:"string"==typeof n&&n.trim().length>0?Number(n):Number.NaN;!s||!Number.isInteger(e)||e<0||o.set(s,{conversationId:t,count:e})}}return a.debug("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:s}])=>({messageId:e,conversationId:t,count:s}))}),Array.from(o,([e,{conversationId:t,count:s}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:s}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Us)return null;const s=t.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;try{const e=Zi(),t=e.lookupType("easemob.pb.StatisticsBody").decode(n);return{operation:"number"==typeof t.operation?t.operation:-1,reason:"string"==typeof t.reason?t.reason:void 0}}catch{return null}}decodeRosterMeta(e,t){try{const s=Zi(),n=s.lookupType("easemob.pb.RosterBody").decode(t),r="number"==typeof n.operation?n.operation:-1,i=this.readRosterJid(n.from),o=this.readRosterJidList(n.to),a="string"==typeof n.reason?n.reason:"",c="string"==typeof n.rosterVer&&n.rosterVer.trim().length>0?n.rosterVer:void 0,d=i.name??"",l=o[0]?.name??"";if(!d&&!l)return[];const u=Zo({operation:r,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:n},this.msyncCodecContext());if(u)return[this.createMultiDeviceNotify(u)];const h=this.mapRosterOperationToEvent(r,{from:d,to:l,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const s=Zi(),n=s.lookupType("easemob.pb.MUCBody").decode(t),r="number"==typeof n.operation?n.operation:-1,i=!0===n.isChatroom,o=!0===n.isThread,a=this.readJid(n.from),c=Array.isArray(n.to)?n.to.map(e=>this.readJid(e)):[],d=n.eventInfo&&"object"==typeof n.eventInfo?n.eventInfo:void 0,l=Array.isArray(n.members)?n.members.filter(e=>"string"==typeof e):[],u=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=ta({operation:r,threadId:this.readJid(n.mucId).name??"",threadName:"string"==typeof n.mucName?n.mucName:void 0,parentId:this.readJid(n.mucParentId).name??void 0,from:a,to:c,members:l,timestamp:this.readMetaTimestamp(e),raw:n},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const s=37===r&&c.some(e=>e.name===this.context.userId),i=this.readJid(n.mucId).name??"",o=this.readJid(n.mucParentId).name??"";return s&&i&&o?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:i,name:"string"==typeof n.mucName?n.mucName:void 0,muc_parent_id:o,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!i){const t=ea({operation:r,groupId:this.readJid(n.mucId).name??"",groupName:"string"==typeof n.mucName?n.mucName:void 0,from:a,to:c,reason:"string"==typeof n.reason?n.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:l,timestamp:this.readMetaTimestamp(e),raw:n},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=i?bo({operation:r,chatRoomId:this.readJid(n.mucId).name??"",chatRoomName:"string"==typeof n.mucName?n.mucName:void 0,from:a,to:c,reason:"string"==typeof n.reason?n.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof n.ext?n.ext:void 0,members:l}):Oo({operation:r,groupId:this.readJid(n.mucId).name??"",groupName:"string"==typeof n.mucName?n.mucName:void 0,from:a,to:c,reason:"string"==typeof n.reason?n.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof n.ext?n.ext:void 0,members:l,source:u});return h?[{type:i?"chatroom":"group",eventName:i?"onChatRoomNotify":"onGroupNotify",data:h}]:[]}catch{return[]}}mapRosterOperationToEvent(e,t){const s={from:t.from,to:t.to,message:t.message,userInfo:{userId:t.from||t.to}};switch(((e,t)=>{t&&Bo.set(e,t)})(s,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:s};case 3:return{eventName:"onContactDeleted",payload:s};case 4:return{eventName:"onContactAdded",payload:s};case 5:case 9:return{eventName:"onContactRefuse",payload:s};case 8:return{eventName:"onContactAgreed",payload:s};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const s=e[i];if(void 0===s)return[];t+=`%${s.toString(16)}`}const s=decodeURIComponent(t),n=JSON.parse(s);a.debug("Decoded MSync notify payload",{payload:n});const r="string"==typeof n.type?n.type:"";if(!r)return[];if("thread"===r){return[{type:r,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:sc(n.data)?n.data:n}}]}if("conv"===r){const e=sc(n.data)?n.data:n,t=[],s="string"==typeof e.op?e.op:"";if("pin"===s||"pin_delete"===s)return[{type:r,eventName:"onPinnedMessageChanged",data:e}];const i=sa({operation:s,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===r){const e=sc(n.data)?n.data:n,t=na({chatType:"string"==typeof e.chatType?e.chatType:void 0,to:"string"==typeof e.to?e.to:void 0,resource:"string"==typeof e.resource?e.resource:void 0,msgIdList:Array.isArray(e.msgIdList)?e.msgIdList.filter(e=>"string"==typeof e):void 0,deleteTime:e.deleteTime,lastMsgId:"string"==typeof e.lastMsgId?e.lastMsgId:void 0,messageRoamingType:"string"==typeof e.messageRoamingType?e.messageRoamingType:void 0,raw:e},this.msyncCodecContext());return t?[this.createMultiDeviceNotify(t)]:[]}if("user_notification_mute"===r){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const s=[];for(const n of e){if(!Wo(n))continue;const e=Qo(n.operator_resource,n.resource,n.clientResource);if($o(e,t.clientResource))continue;const r=Ho(n.group)??Ho(n.user);if(!r||!Wo(n.data))continue;const i=Ho(n.group)?Go:Ko,o=n.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:r,conversationType:i,remindType:Ho(o.type),silentMode:o,deviceId:e,raw:n})}return s})(sc(n.data)&&Array.isArray(n.data.values)?n.data.values:Array.isArray(n.values)?n.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:r,data:n.data??n}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,s=Number(oo(t));if(Number.isFinite(s)&&s>0)return s}msyncCodecContext(){return{userId:this.context.userId,clientResource:this.context.clientResource}}createMultiDeviceNotify(e){return{type:"multiDevice",eventName:ra(e.category),data:e}}decodeNotice(e){const t=Zi().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Zi().lookupType("easemob.pb.CommUnreadDL").decode(e);return{queues:(Array.isArray(t.unread)?t.unread:[]).map(e=>e&&"object"==typeof e?e:null).map(e=>e?.queue&&"object"==typeof e.queue?e.queue:null).filter(e=>Boolean(e))}}encodeBackQueue(e){const t=Zi(),s=t.lookupType("easemob.pb.CommSyncUL"),n=t.lookupType("easemob.pb.MSync"),r=nc(s,{queue:e}),i={version:0,encryptType:[qs],command:rs,payload:r,traceId:h()};return nc(n,i)}encodeLastSession(e,t){const s=Zi(),n=s.lookupType("easemob.pb.CommSyncUL"),r=s.lookupType("easemob.pb.MSync"),i=nc(n,{queue:e,key:t}),o={version:0,encryptType:[qs],command:rs,payload:i,traceId:h()};return nc(r,o)}encodeChatMessage(e,t){const s=Zi(),n=s.lookupType("easemob.pb.CommSyncUL"),r=s.lookupType("easemob.pb.MSync"),i=this.buildChatMeta(e,t),o=nc(n,{meta:i}),a={version:0,encryptType:[qs],command:rs,payload:o,traceId:h()};return nc(r,a)}encodeCombineMessageMeta(e){const t=Zi().lookupType("easemob.pb.Meta"),s=io(e.msgServerId||e.msgLocalId),n=this.buildChatMeta(e,s,!0);return nc(t,n)}buildChatMeta(e,t,s=!1){const n=Zi().lookupType("easemob.pb.MessageBody"),r=this.buildContent(e),i=this.resolveMessageProfileVersionFields(e),o=this.buildMessageMeta(e),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=s?e.from||e.sender.userId:this.context.userId,d=s&&e.to||a.name,l={type:this.resolveChatType(e),from:{name:c},to:{name:d},contents:[r],ext:ao(e.ext??{}),...o?{meta:o}:{},...i,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},u=nc(n,l),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e);return{id:t,to:ro({appKey:this.context.appKey,name:d,domain:h,clientResource:s?void 0:a.clientResource}),...s?{timestamp:e.timestamp}:{},ns:Ls,payload:u,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}}}encodeActionMessage(e,t){const s=Zi(),n=s.lookupType("easemob.pb.MessageBody"),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o=s.lookupEnum("easemob.pb.MessageBody.EditScope"),c=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),d=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],l={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:c.name},contents:d,ext:ao(e.ext??{})};"recall"!==e.kind&&"deliveryAck"!==e.kind||(l.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(l.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(l.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(l.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(l.sendToPeer=e.sendToPeer??!1,l.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind&&(l.editMessageId=e.messageId,l.editScope=e.ext&&Object.keys(e.ext).length>0?o.values.BODY_AND_EXT:o.values.BODY);const u=nc(n,l);if("clearAllConversationUnreadMessageCount"===e.kind){const e=n.decode(u),s=n.fields.clearAllUnreadMessageCount;a.debug("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:l.type,fieldId:s?.id,requestedValue:l.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const p={id:t,to:ro({appKey:this.context.appKey,name:c.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:c.clientResource}),ns:Ls,payload:u,routetype:xs,directedUsers:[],ext:[]},m=nc(r,{meta:p}),f={version:0,encryptType:[qs],command:rs,payload:m,traceId:h()};return nc(i,f)}encodeChatRoomOperation(e,t){const s=Zi(),n=s.lookupType("easemob.pb.MUCBody"),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o={mucId:ro({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=nc(n,o),c={id:t,from:ro({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:Os,payload:a},d=nc(r,{meta:c}),l={version:0,encryptType:[qs],command:rs,payload:d,traceId:h()};return nc(i,l)}decodeServerMessageMeta(e){const t=Zi(),s=t.lookupType("easemob.pb.Meta"),n=t.lookupType("easemob.pb.MessageBody");try{const t=s.decode(e);return this.decodeChatMeta(t,n)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?On(e):e&&"object"==typeof e&&"data"in e?this.normalizeIncoming(e.data):new Uint8Array}decompressIncoming(e){if(!this.compressor||!this.compressor.enableDownlinkCompression)return e;try{return this.compressor.decompress(e)}catch{return this.compressionFailureCount+=1,null}}prepareOutgoing(e){if(!this.compressor||!this.compressor.enableUplinkCompression)return e;try{return this.compressor.compress(e)}catch{throw this.compressionFailureCount+=1,new Error("compress outgoing message failed")}}resetCompressionNegotiation(){this.compressor?.reset(),this.disableCompression()}toProtocolId(e){return io(e)}decodeChatRoomJoinInfo(e){const t=Zi().lookupType("easemob.pb.MUCBody");for(const n of e){if(!sc(n)||n.ns!==Os)continue;const e=n.payload,r=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(r)try{const e=t.decode(r);if(!sc(e)||!sc(e.status))continue;const s=e.status.chatroomInfo;if("string"!=typeof s||""===s)continue;const n=JSON.parse(s);if(!sc(n))continue;const i=n[this.context.userId];if(!sc(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(s){a.error("Failed to decode chat room info from ACK",s)}}}decodeAck(e){const t=oo(e.metaId);if(!t||"0"===t)return;const s=e.status??{},n="number"==typeof s.errorCode?s.errorCode:Hs,r="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:oo(e.serverId),ok:n===Vs,statusCode:n,reason:r}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:ls;if(!this.isPublicMessageType(s))return null;const n=(Array.isArray(t.contents)?t.contents:[])[0];if(!n)return null;const r=this.resolveConversationType(s),{senderUserId:i,senderId:o,receiverId:a}=this.resolveIncomingMessageParties(e,t,r),c=o===this.context.userId?"SEND":"RECEIVE",d="singleChat"===r?"SEND"===c?a:o:a,l=this.decodeContent(n);if(!l)return null;const u=co(t.ext),h=co(e.ext),p=Number(oo(e.timestamp))||Date.now(),m=oo(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveProfileVersionTime(t.userInfoUpdateTime),I=this.resolveProfileVersionTime(t.namecardUpdateTime),v=this.payloadDecoder.decodeMetadata(t,r,c,e.meta),C={msgServerId:m,msgLocalId:"",from:o,to:a,sender:{userId:i},conversationId:d,conversationType:r,type:l.type,sendStatus:"sent",ext:u,timestamp:p,body:l.body,direct:c,isOnline:this.resolveMessageIsOnline(s,h)};Po(C,{userInfoUpdateTime:y,namecardUpdateTime:I});const S=v.stream;return S&&(C.type="text",C.body={content:S.fullText},C.stream=S),void 0!==f&&(C.isBroadcast=f),void 0!==g&&(C.priority=g),Object.assign(C,v),C}resolveMessageProfileVersionFields(e){const t=xo(e),s={};return"number"==typeof t?.userInfoUpdateTime&&(s.userInfoUpdateTime=t.userInfoUpdateTime),"groupChat"===e.conversationType&&"number"==typeof t?.namecardUpdateTime&&(s.namecardUpdateTime=t.namecardUpdateTime),s}buildMessageMeta(e){const t={};return e.isChatThread&&(t.thread={}),Object.keys(t).length>0?JSON.stringify(t):""}resolveProfileVersionTime(e){return yt(oo(e))}isPublicMessageType(e){return e===ls||e===us||e===hs}resolveMessageIsOnline(e,t){if(e===hs)return!0;const s=t.is_online;return"boolean"==typeof s?s:"number"==typeof s?0!==s:"string"!=typeof s||"0"!==s}buildContent(e){if("text"===e.type){const t=e.body;return{type:Is,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:Ts,action:t.action}}if("custom"===e.type){const t=e.body;return{type:As,customEvent:t.event,customExts:ao(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Ss,latitude:t.latitude,longitude:t.longitude,address:t.address,buildingName:t.buildingName}}if("image"===e.type){const t=e.body,s=t.isGif||t.isOriginalImage?"original":"large";return{type:vs,displayName:t.filename,remotePath:t.originalImageUrl??"",imageType:p(s),secretKey:t.secret,fileLength:t.fileLength,size:{width:t.width,height:t.height},subType:t.isGif?1:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailDisplayName:t.filename}}if("video"===e.type){const t=e.body;return{type:Cs,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,size:t.width&&t.height?{width:t.width,height:t.height}:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailSecretKey:t.secret,thumbnailDisplayName:t.filename}}if("voice"===e.type){const t=e.body;return{type:Es,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,thumbnailDisplayName:t.filename}}if("combine"===e.type){const t=e.body;return{type:Is,subType:0,text:Ke(e)??"版本过低",displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,title:t.title,summary:t.summary,combineLevel:t.combineLevel}}const t=e.body;return{type:bs,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,thumbnailDisplayName:t.filename}}decodeContent(e){return this.payloadDecoder.decodeContent(e)}resolveChatType(e){switch(e.conversationType){case"groupChat":return us;case"chatRoom":return hs;default:return ls}}resolveActionConversationType(e,t,s){const n=this.resolveConversationTypeFromMeta(t);if(n)return n;const r=s?.msgConfig&&"object"==typeof s.msgConfig?s.msgConfig:null;return!0===r?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),s=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,n=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof s?.chat_type?s.chat_type:void 0);if("chat:user"===n||"singleChat"===n)return"singleChat";if("chat:group"===n||"groupChat"===n)return"groupChat";if("chat:room"===n||"chatRoom"===n)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,s){return"singleChat"===s?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const s=`${this.context.userId}/`;if(!e.startsWith(s))return{name:e};const n=e.slice(s.length);return n?{name:this.context.userId,clientResource:n}:{name:e}}resolveIncomingMessageParties(e,t,s){const n=this.readJid(e.from),r=this.readJid(e.to),i=po(t.from,e.from),o=po(t.to,e.to);if(!("singleChat"===s&&i===this.context.userId&&o===this.context.userId))return{senderUserId:i,senderId:i,receiverId:o};return{senderUserId:i,senderId:n.clientResource&&n.clientResource!==this.context.clientResource?`${i}/${n.clientResource}`:i,receiverId:r.clientResource?`${o}/${r.clientResource}`:o}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return gs;case"sendMessageReadReceipts":return ps;case"deliveryAck":return ms;case"recall":return fs;case"update":return ys;default:return ls}}resolveConversationType(e){return e===us?"groupChat":e===hs?"chatRoom":"singleChat"}resolveDirectedUsers(e){return"singleChat"===e.conversationType?[]:Array.isArray(e.receiverList)?e.receiverList:[]}resolveDeliverOnlineOnly(e){if("boolean"==typeof e.deliverOnlineOnly)return e.deliverOnlineOnly;if("cmd"===e.type){const t=e.body;return Boolean(t.deliverOnlineOnly)}return!1}resolveMetaExt(e){return"chatRoom"!==e.conversationType?[]:e.priority?ao({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?Bs:this.resolveDeliverOnlineOnly(e)?Fs:xs}resolveBroadcast(e){if(!Object.prototype.hasOwnProperty.call(e,"is_broadcast"))return;const t=e.is_broadcast;return"boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?"1"===t||"true"===t.toLowerCase():Boolean(t)}resolvePriority(e){if(!Object.prototype.hasOwnProperty.call(e,"chatroom_msg_tag"))return;const t=Number(e.chatroom_msg_tag);return 0===t?"high":2===t?"low":"normal"}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[Gs]}configureCompression(e,t){if(!e||!e.includes(Gs))return void this.disableCompression();this.compressor||(this.compressor=new tc);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===Za.UPLINK_ONLY||s===Za.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===Za.DOWNLINK_ONLY||s===Za.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Za.UPLINK_ONLY:1===e?Za.DOWNLINK_ONLY:2===e?Za.BIDIRECTIONAL:Za.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Za.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const ic=t=>new C("Connection attempt cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:t,cancelled:!0,retryable:!0}}),oc=t=>t instanceof C&&t.code===e.CONNECTION_CANCELLED&&!0===t.details?.cancelled;class ac{constructor(e,t){this.serverUrlIndex=0,this.websocket=null,this.provisionTimeoutId=null,this.reconnectAttempts=0,this.messageReceiver=null,this.provisionPromise=null,this.provisionResolve=null,this.provisionReject=null,this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames=/* @__PURE__ */new Set,this.offlineMessageQueueReports=/* @__PURE__ */new Map,this.offlineMessageQueueCounts=/* @__PURE__ */new Map,this.offlineMessageTotalCount=0,this.reconnectTimerId=null,this.reconnectDelayReject=null,this.reconnectTask=null,this.pendingReconnectReason=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.hasEverConnected=!1,this.isOnline=!0,this.internalHandlerId="__internal:connection-manager",this.suppressNextCloseEvent=!1,this.socketDisposers=[],this.inboundMessageQueue=Promise.resolve(),this.socketGeneration=0,this.connectionAttemptGeneration=0,this.activeConnectionAttemptCancel=null,this.activeLoginDeadline=null,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:f,autoReconnectNumMax:10,connectTimeout:m,...e},this.eventHub=t,this.msyncCodec=new rc({appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,userId:e.userId,token:e.token,useReplacedMessageContents:e.useReplacedMessageContents,useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,serviceId:e.serviceId}),this.serverUrls=this.normalizeServerUrls(e),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:Be.DISCONNECTED,serverUrl:this.config.serverUrl,userId:e.userId,token:e.token,reconnectAttempts:0},this.connectionRetry=new Qi({maxAttempts:this.config.autoReconnectNumMax,initialDelay:I,maxDelay:y,backoffMultiplier:g}),this.heartbeatManager=new Ji({interval:this.config.heartBeatWait,timeout:v}),this.connectionEventNormalizer=new Pn,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[Ge.SEND_TIMEOUT]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(t,s){const n=Date.now();if(s<=n)throw new C("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=t,this.connection.token=t,this.msyncCodec.updateToken(t),this.setupTokenLifecycle(t,s,n),a.warn("Connection token renewed",{userId:this.config.userId,expireAt:s}),{token:t,expireAt:s}}handleOnline(){if(a.warn("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0,this.terminalDisconnectError)return void a.warn("Network online recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});const e=this.offlineRecoverPending?Ve.OFFLINE_RECOVER:Ve.ONLINE;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){a.warn("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.stopHeartbeat(),this.closeWebSocket(Ve.OFFLINE,!0),a.warn("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(this.terminalDisconnectError)return void a.warn("Foreground recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void a.warn("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(Ve.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Ve.HEARTBEAT_FAILED)}}catch(t){if(a.warn("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(Ve.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Ve.HEARTBEAT_FAILED)}}resumeReconnect(e){if(this.terminalDisconnectError)a.warn("Reconnect recovery skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()});else if(this.isLoggedIn)return this.reconnectTask||this.reconnectInProgress?(this.pendingReconnectReason=e,void a.warn("Reconnect recovery queued",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()})):void(this.connection.status===Be.CONNECTED&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),a.warn("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===Ve.SEND_TIMEOUT&&a.warn("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,terminalDisconnectCode:this.terminalDisconnectError?.code,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId,hasReconnectTask:null!==this.reconnectTask,hasActiveConnectionAttempt:null!==this.activeConnectionAttemptCancel}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof C))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(kn(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){const e=this.reconnectDelayReject;this.reconnectDelayReject=null,this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null),e?.(ic("retry-delay"))}resolveLoginStageTimeout(e){return this.isLoginPhase&&this.activeLoginDeadline?this.activeLoginDeadline.clamp(e):e}isLoginDeadlineExpired(){return Boolean(this.isLoginPhase&&this.activeLoginDeadline&&this.activeLoginDeadline.remainingMs()<=0)}requireLoginTimeoutError(){const t=this.activeLoginDeadline;return t?(t.expire(),t.createTimeoutError()):new C("Login timeout",{code:e.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",retryable:!0}})}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay(),t=this.resolveLoginStageTimeout(e);if(t<=0)throw this.requireLoginTimeoutError();a.warn("Reconnect retry scheduled",{delayMs:Math.round(t),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise((e,s)=>{this.reconnectDelayReject=e=>{this.reconnectDelayReject=null,s(e)},this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,this.reconnectDelayReject=null,e()},t)})}buildConnectionEventPayload(e,t){const s=this.connection.error instanceof C?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:s?.code,errorMessage:s?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,t){if(e===Be.DISCONNECTED&&!this.hasEverConnected)return;if(e===Be.RECONNECT_FAILED&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===Be.DISCONNECTED||e===Be.RECONNECT_FAILED))return;const s=this.buildConnectionEventPayload(e,t),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,s,n=!1){const r=this.connection.status!==e;(r||n)&&(r&&(this.connection.status=e,this.connection.lastConnectedAt=e===Be.CONNECTED?Date.now():void 0),s&&this.dispatchConnectionEvent(e,t),a.debug("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,s=Date.now()){this.clearTokenTimers();const n=Math.max(t-s,0),r=s+Math.floor(.8*n);this.tokenLifecycle={token:e,issuedAt:s,expireAt:t,willExpireAt:r,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(r-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void a.warn("Provision auth token has invalid payload");const s=Number(t.expires_in);if(!Number.isFinite(s))return void a.warn("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,s)}catch(t){a.warn("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,a.warn("Token will expire"),this.eventHub.dispatch(qe.TOKEN_WILL_EXPIRE,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,a.warn("Token expired"),this.eventHub.dispatch(qe.TOKEN_EXPIRED,void 0))}isTokenExpiredConnectionError(t){return t instanceof C&&t.code===e.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(t){a.warn("Connection closing because token expired",{source:t}),this.connection.error=new C("Token expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:t,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(Ve.TOKEN_EXPIRED,!0,!0),this.updateStatus(Be.DISCONNECTED,Ve.TOKEN_EXPIRED,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(Ve.HEARTBEAT_FAILED)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,v)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(t){if(!this.reconnectInProgress)if(this.connection.status!==Be.CONNECTED&&this.connection.status!==Be.CONNECTING){this.isLoginPhase=!0,this.activeLoginDeadline=t??null,this.terminalDisconnectError=null,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(Ve.LOGIN,!0),this.isLoggedIn=!0}catch(s){throw this.isLoggedIn=!1,s instanceof C&&s.code===e.CONNECTION_LOGIN_TIMEOUT&&"login"===s.details?.stage&&(this.cancelActiveConnectionAttempt(),this.closeWebSocket(Ve.ERROR,!1,!1),this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!1)),s}finally{this.isLoginPhase=!1,this.activeLoginDeadline=null}}else a.warn("Connection already established or connecting")}async connectWithRetry(t,s){if(a.warn("Reconnect flow requested",{reason:t,throwOnFailure:s,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void a.warn("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:t,...this.getReconnectDiagnostic()});if(this.connection.status===Be.CONNECTED&&this.websocket)return;if(this.reconnectPaused)return void a.warn("Reconnect flow skipped",{guard:"reconnect-paused",reason:t,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let n=null,r=null,i=null;const o=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),a.warn("Reconnect flow started",{reason:t,throwOnFailure:s,maxAttempts:o,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<o;){if(this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(!this.isLoginPhase&&(this.reconnectPaused||!this.isOnline||!this.isLoggedIn)){i=ic("ws");break}this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const e=this.isLoginPhase?Be.CONNECTING:Be.RECONNECTING;a.warn("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:o,reason:t,nextStatus:e,...this.getReconnectDiagnostic()}),this.updateStatus(e,t,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(t)}catch(c){if(n=c,this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(oc(c)){i=c,a.warn("Reconnect attempt cancelled",{attempt:this.reconnectAttempts,reason:t,...this.getReconnectDiagnostic()});break}if(a.warn("Connection attempt failed",{attempt:this.reconnectAttempts,reason:t,error:n}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(n))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(n)){r=n;break}}if(this.connectionRetry.getAttemptCount()>=o)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){a.warn("Reconnect retry loop interrupted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,...this.getReconnectDiagnostic()});break}try{await this.waitForReconnectDelay()}catch(c){if(!oc(c))throw c;i=c,a.warn("Reconnect retry delay cancelled",{reason:t,attempt:this.reconnectAttempts,...this.getReconnectDiagnostic()});break}}if(i){if(s)throw i;return}if(r){if(this.connection.error=r,s)throw this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!1),r;return this.reconnectPaused=!0,void this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!0)}if(s)throw this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!1),n??new C("Connection failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,a.warn("Reconnect attempts exhausted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,lastError:n,...this.getReconnectDiagnostic()}),this.updateStatus(Be.RECONNECT_FAILED,Ve.LIMIT,!0)}finally{this.reconnectInProgress=!1,a.warn("Reconnect flow finished",{reason:t,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.cancelActiveConnectionAttempt(),this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(Ve.RECONNECT,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(Be.CONNECTED,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),a.warn("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}triggerReconnect(e){if(a.warn("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.terminalDisconnectError)return a.warn("Reconnect trigger skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(!this.isLoggedIn)return a.warn("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectTask)return a.warn("Reconnect task reused",{reason:e,...this.getReconnectDiagnostic()}),this.reconnectTask;if(this.reconnectInProgress)return a.warn("Reconnect trigger skipped",{guard:"reconnect-in-progress-without-task",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectPaused)return a.warn("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();this.connection.status===Be.CONNECTED&&this.websocket&&this.closeWebSocket(e,!0,!0);const t=this.connectWithRetry(e,!1).finally(()=>(this.reconnectTask===t&&(this.reconnectTask=null),this.startPendingReconnectIfNeeded()??void 0));return this.reconnectTask=t,t}recoverConnectionForSend(){return this.connection.status===Be.CONNECTED&&this.websocket?Promise.resolve():this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.isLoginPhase||0===this.config.autoReconnectNumMax?(a.warn("Send connection recovery skipped",{guard:"connection-not-recoverable",...this.getReconnectDiagnostic()}),Promise.resolve()):this.reconnectTask?(a.warn("Send connection recovery reused",this.getReconnectDiagnostic()),this.reconnectTask):(this.reconnectPaused=!1,this.resetReconnectState(),a.warn("Send connection recovery requested",this.getReconnectDiagnostic()),this.triggerReconnect(Ve.RECONNECT))}startPendingReconnectIfNeeded(){const e=this.pendingReconnectReason;return this.pendingReconnectReason=null,!e||null!==this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.connection.status===Be.CONNECTED&&this.websocket?null:(this.reconnectPaused=!1,this.resetReconnectState(),a.warn("Queued reconnect recovery started",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e))}handleDisconnection(e){a.warn("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(Be.DISCONNECTED,e,!0),e!==Ve.TOKEN_EXPIRED&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,t,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(Be.DISCONNECTED,e,t)):s&&this.updateStatus(Be.DISCONNECTED,e,t)}createWebSocketConnection(){const t=this.resolveLoginStageTimeout(this.config.connectTimeout);return t<=0?Promise.reject(this.requireLoginTimeoutError()):new Promise((s,n)=>{const r=++this.connectionAttemptGeneration,i=this.pickNextServerUrl();a.debug("WebSocket connecting",{url:i}),this.clearSocketListeners();let o=!1,c=!1,d=null;const l=()=>{this.connectionAttemptGeneration===r&&(this.activeConnectionAttemptCancel=null)},u=e=>{o||(o=!0,d&&(clearTimeout(d),d=null),l(),n(e))};this.activeConnectionAttemptCancel=()=>{const e=ic(c?"provision":"ws");this.rejectPendingProvision(e),u(e)},d=setTimeout(()=>{a.warn("WebSocket connection attempt timed out",{url:i,connectTimeout:t,...this.getReconnectDiagnostic()}),u(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new C("Connection timeout",{code:e.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},t),this.socketAdapter.connect({url:i,timeoutMs:t}).then(e=>{if(o||r!==this.connectionAttemptGeneration||this.reconnectPaused)return a.warn("WebSocket connection result discarded",{url:i,cancelled:o||r!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),e.close(),void u(ic("ws"));d&&(clearTimeout(d),d=null),this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),c=!0,this.startProvision().then(()=>{if(this.resetProvisionHandlers(),o||r!==this.connectionAttemptGeneration||this.reconnectPaused)return a.warn("Provision result discarded",{url:i,cancelled:o||r!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),this.closeWebSocket(Ve.ERROR,!1,!1),void u(ic("provision"));o||(o=!0,d&&(clearTimeout(d),d=null),l(),s())}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(Ve.ERROR,!1,!1),u(e instanceof Error?e:new Error(String(e)))})}).catch(t=>{if(o)return;const s=t instanceof C?t:new C("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});this.handleConnectionError(s,Ve.ERROR),u(s)})}).catch(t=>{if(t instanceof C)throw t;const s=new C("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});throw this.handleConnectionError(s,Ve.ERROR),s})}cancelActiveConnectionAttempt(){this.activeConnectionAttemptCancel?.()}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(a.warn("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(Ve.CLOSE))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new C("Provision interrupted",{code:e.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(t,s){a.error("Connection error:",t),this.connection.error=t,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null);const n=t instanceof C?t:new C(t.message,{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",retryable:!0}});if(this.rejectPendingProvision(n)||this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(s)}handleTerminalConnectionError(e,t){if(a.warn("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.terminalDisconnectError=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.pendingReconnectReason=null,this.isLoggedIn=!1,this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(Be.DISCONNECTED,t,!0,!0)}async handleWebSocketMessage(t,s){try{if(s!==this.socketGeneration)return;a.debug("WebSocket message received",{dataType:typeof t});const r=await this.msyncCodec.normalizeIncoming(t);if(s!==this.socketGeneration)return;if(a.debug("handleWebSocketMessage data",{length:r.length}),!r.length)return;const i=this.msyncCodec.decompressIncoming(r);if(!i){const t=null!==this.provisionReject;return a.error("Failed to decompress mSync payload, closing connection",{stage:t?"provision":"connected"}),void(t?(this.rejectPendingProvision(new C("Failed to decompress Provision payload",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(Ve.ERROR,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(i))return void a.debug("Ignore server normal close payload",{length:i.length});let o=null;try{o=this.msyncCodec.decodeMsync(i)}catch(n){const e=n instanceof Error?n:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void a.warn("Discard invalid mSync payload",{length:i.length,message:e.message,prefixHex:Array.from(i.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(i.subarray(Math.max(0,i.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw a.warn("Invalid mSync payload signature",{length:i.length,prefixHex:Array.from(i.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),a.debug("handleWebSocketMessage decoded",{command:o.command}),o.command){case as:this.handleProvisionMessage(o.payload);break;case cs:this.handleLogoutMessage(o.payload);break;case os:this.handleNoticeMessage(o.payload);break;case is:this.handleUnreadMessage(o.payload);break;case rs:this.handleSyncMessage(o.payload)}}catch(n){const e=n instanceof Error?n:new Error("Failed to handle mSync payload");a.error("Failed to handle mSync payload",e),this.handleConnectionError(e,Ve.ERROR)}}startProvision(){const t=this.resolveLoginStageTimeout(S);if(t<=0)return Promise.reject(this.requireLoginTimeoutError());this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new C("Provision timeout",{code:e.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},t);try{const e=this.msyncCodec.encodeProvision();a.debug("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new C("Provision send failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(t){const s=this.msyncCodec.decodeProvision(t);if(this.isLoginPhase&&this.activeLoginDeadline?.markProvisionReceived(),this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),s.ok)this.msyncCodec.updateResource(s.resource),this.setupTokenLifecycleFromProvision(s.authToken),this.provisionResolve?.();else{a.warn("Provision rejected",{statusCode:s.statusCode,reason:s.reason});const t=Un(s.statusCode,s.reason),n=t.code===e.UNKNOWN?e.CONNECTION_PROVISION_REJECTED:t.code;this.provisionReject?.(new C("Provision rejected",{code:n,details:{stage:"provision",reason:s.reason,statusCode:s.statusCode,retryable:t.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),s=t?this.getQueueId(t):null,n=!!t&&this.isSelfQueue(t),r=!!t&&this.isQueueInList(t);t&&s&&(n||r||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),s=t.filter(e=>this.getQueueId(e));if(s.length){s.length!==t.length&&a.warn("Unread queues without usable identity were ignored",{ignoredCount:t.length-s.length}),this.startOfflineMessageSync(s);for(const e of s)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,Ve.ERROR);if(!this.messageReceiver)return;const s=this.messageReceiver.handleSyncPayload(e);if(a.debug("handleSyncMessage result",{result:s}),!s)return;(void 0!==s.queue||void 0!==s.nextKey||void 0!==s.isLast)&&this.handleSyncQueueState(s)}handleSyncQueueState(e){a.debug("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:s,queueId:n}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(n)){const t=this.offlineMessageQueueCounts.get(n)??0;this.offlineMessageQueueCounts.set(n,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const r=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(n),this.removeQueueEntry(s),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(r){if(r!==this.nextKey||!this.isSameQueue(s,this.currentQueue))return this.nextKey=r,this.currentQueueId=n,this.currentQueue=s,void this.sendLastSession(s,r);this.removeQueueEntry(s),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,s=t?this.getQueueName(t):null,n=t?this.getQueueId(t):null,r=void 0!==t&&null!==n&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&n&&r)return{queue:t,queueId:n};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,c=i??o??this.queues[0],d=c?this.getQueueName(c):null,l=c?this.getQueueId(c):null;return c&&l?(a.warn("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:s,responseQueueId:n,fallbackQueueName:d,fallbackQueueId:l,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:c,queueId:l}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);a.warn("Logout message received",t)}resolveStatisticDisconnectError(t){for(const s of t)switch(s.operation){case 1:return new C("User has been removed",{code:e.USER_REMOVED,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 2:return new C("The user is already logged on another device",{code:e.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1,...s.reason?{loginInfoCustomExt:s.reason}:{}}});case 3:return new C("The user was kicked by changing password",{code:e.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 4:return new C("The user was kicked by other device",{code:e.USER_KICKED_BY_OTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.closeWebSocket(Ve.CLOSE,!0,!0),this.updateStatus(Be.DISCONNECTED,Ve.CLOSE,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),a.warn("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){return ji(e.socketAdapter)}attachSocketListeners(t,s){this.clearSocketListeners(),this.socketDisposers=[t.onMessage(e=>{this.websocket===t&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(e,s)))}),t.onError(()=>{if(this.websocket!==t)return;a.warn("WebSocket error",{stage:"ws"});const s=new C("WebSocket connection error",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(s,Ve.ERROR)}),t.onClose(e=>{this.websocket===t&&this.handleWebSocketClose(e)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===o.OPEN)try{const t=this.msyncCodec.prepareOutgoing(e);a.debug("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{a.error("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){a.error("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);a.debug("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){a.debug("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const s=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(s)}sendNextQueue(){a.debug("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=/* @__PURE__ */new Set;for(const s of e){const e=this.getQueueId(s);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=E({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of t){this.offlineMessageQueueCounts.set(e,0);const t=this.offlineMessageReport?.startRequest({requestName:"MSYNC_SYNCOFFLINEMESSAGE",method:"WS",url:e});t&&this.offlineMessageQueueReports.set(e,t)}this.offlineMessageSyncLifecycleActive&&this.eventHub.dispatch(qe.OFFLINE_MESSAGE_SYNC_START,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const t=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:t}),this.offlineMessageQueueReports.delete(e),this.offlineMessageQueueNames.delete(e),this.offlineMessageQueueNames.size>0||(this.offlineMessageSyncing=!1,this.offlineMessageReport?.finish({code:0,success:!0,resultCount:this.offlineMessageTotalCount}),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleActive=!1,this.eventHub.dispatch(qe.OFFLINE_MESSAGE_SYNC_FINISH,void 0)))}isQueueInList(e){return this.queues.some(t=>this.isSameQueue(t,e))}isSelfQueue(e){const t=this.getQueueName(e),s=this.getQueueResource(e),n=this.msyncCodec.getContext();return t===n.userId&&s===n.clientResource}getQueueName(e){return"string"==typeof e.name&&e.name.trim().length>0?e.name:null}getQueueResource(e){return this.getQueueField(e,"clientResource")}getQueueId(e){const t=this.getQueueName(e);if(t)return`name:${t}`;const s=this.getQueueField(e,"domain"),n=this.getQueueResource(e);if(s)return`domain:${s}|resource:${n??""}`;if(n)return`resource:${n}`;const r=this.getQueueField(e,"appKey");return r?`appKey:${r}`:null}getQueueField(e,t){const s=e[t];return"string"==typeof s&&s.trim().length>0?s:null}isSameQueue(e,t){if(!e||!t)return!1;const s=this.getQueueId(e),n=this.getQueueId(t);return null!==s&&s===n}resetSyncState(){this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames.clear(),this.offlineMessageReport?.discard(),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageTotalCount=0}}const cc=new Uint8Array([99,109]),dc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),lc=e=>Array.isArray(e)&&e.every(dc),uc=e=>"string"==typeof e?e:void 0,hc=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,pc=e=>{const t=new Uint8Array(4);return t[0]=e>>>24&255,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t},mc=(t,s)=>{const n=t[s],r=t[s+1],i=t[s+2],o=t[s+3];if("number"!=typeof n||"number"!=typeof r||"number"!=typeof i||"number"!=typeof o)throw new T("Combine payload length header is invalid",{code:e.COMBINE_PARSE_FAILED});return n<<24|r<<16|i<<8|o},fc=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},gc=(e,t)=>{const s=Zi().lookupType(e).decode(t);if(!dc(s))throw new Error(`${e} decoded result is invalid`);return s},yc=e=>dc(e)&&"string"==typeof e.name?e.name:"",Ic=(e,t,s)=>{const n=(lc(e.contents)?e.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const r=(e=>{const t=hc(e.type)??Is,s=Boolean(uc(e.remotePath))||Boolean(uc(e.title))||Boolean(uc(e.summary))||(hc(e.combineLevel)??0)>0,n=t===Is&&0===e.subType&&s;if(t===ws||n){const t=hc(e.combineLevel)??0;return{type:"combine",body:{title:uc(e.title)??"",summary:uc(e.summary)??"",filename:uc(e.displayName)??"combine",filetype:"application/octet-stream",url:uc(e.remotePath),secret:uc(e.secretKey),fileLength:hc(e.fileLength),combineLevel:t},combineLevel:t}}if(t===Is)return{type:"text",body:{content:uc(e.text)??""}};if(t===Ts)return{type:"cmd",body:{action:uc(e.action)??""}};if(t===As){const t=co(lc(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:uc(e.customEvent)??"",params:t}}}if(t===Ss)return{type:"location",body:{latitude:hc(e.latitude)??0,longitude:hc(e.longitude)??0,address:uc(e.address),buildingName:uc(e.buildingName)}};if(t===vs){const t=dc(e.size)?e.size:{},s=uc(e.remotePath)??"",n=u(s),r=uc(e.thumbnailRemotePath),i=d(e.imageType)===l;return{type:"image",body:{localUrl:"",filename:uc(e.displayName)??"image",filetype:"application/octet-stream",width:hc(t.width)??0,height:hc(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:uc(e.secretKey),fileLength:hc(e.fileLength),thumbnailUrl:r??n.thumbnailUrl}}}if(t===Cs){const t=dc(e.size)?e.size:{};return{type:"video",body:{url:uc(e.remotePath)??"",filename:uc(e.displayName)??"video",filetype:"application/octet-stream",duration:hc(e.duration)??0,width:hc(t.width),height:hc(t.height),secret:uc(e.secretKey),fileLength:hc(e.fileLength),thumbnailUrl:uc(e.thumbnailRemotePath)}}}if(t===Es)return{type:"voice",body:{url:uc(e.remotePath)??"",filename:uc(e.displayName)??"voice",filetype:"application/octet-stream",duration:hc(e.duration)??0,secret:uc(e.secretKey),fileLength:hc(e.fileLength)}};if(t===bs)return{type:"file",body:{url:uc(e.remotePath)??"",filename:uc(e.displayName)??"file",filetype:"application/octet-stream",secret:uc(e.secretKey),fileLength:hc(e.fileLength)}};return null})(n);if(!r)throw new Error("MessageBody content type is unsupported");const i=yc(e.from)||yc(s?.from)||`unknown-${t}`,o=yc(e.to)||yc(s?.to)||`unknown-${t}`,a=(c=e.type)===us?"groupChat":c===hs?"chatRoom":"singleChat";var c;const h=o||i,p=Number(oo(s?.timestamp))||Date.now(),m=co(lc(e.ext)?e.ext:void 0),f={msgServerId:oo(s?.id),msgLocalId:"",type:r.type,sender:{userId:i},conversationId:h,conversationType:a,timestamp:p,body:r.body,ext:m};return"number"==typeof r.combineLevel&&(f.body.combineLevel=r.combineLevel),f},vc=(e,t)=>{const s=[];try{const r=gc("easemob.pb.Meta",e),i=(n=r.payload)instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):void 0;if(i&&i.length>0){const e=gc("easemob.pb.MessageBody",i);return Ic(e,t,r)}s.push("Meta payload is empty")}catch(r){s.push(r instanceof Error?r.message:String(r))}var n;try{const s=gc("easemob.pb.MessageBody",e);return Ic(s,t)}catch(r){s.push(r instanceof Error?r.message:String(r))}try{const s=gc("easemob.pb.MessageBody.Content",e);return Ic({type:ls,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[s],ext:[]},t)}catch(r){s.push(r instanceof Error?r.message:String(r))}throw new Error(s.join("; "))},Cc=(t,s)=>{const n=kn(t);try{const t=JSON.parse(n);if(!dc(t))throw new T("Combine payload item is invalid",{code:e.COMBINE_PARSE_FAILED,details:{index:s}});return t}catch(r){if(r instanceof T)throw r;try{return vc(t,s)}catch(i){throw new T("Combine payload item parse failed",{code:e.COMBINE_PARSE_FAILED,details:{index:s,cause:r instanceof Error?r.message:String(r),protobufCause:i instanceof Error?i.message:String(i)}})}}},Sc=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Ec{constructor(e,t,s,n){this.websocket=null,this.pendingMessages=/* @__PURE__ */new Map,this.ackTimeout=A,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=s,this.msyncCodec=e,this.attachmentUploader=n??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(t,s){const n=this.msyncCodec.toProtocolId(t.msgLocalId);if(ns(t))throw new b("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==o.OPEN){const s=this.msyncCodec.toProtocolId(t.msgLocalId);throw new b("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:s,retryable:!0}})}let r={...t,sendStatus:"sending"};Fo(t,r),a.debug("Message send queued",{msgLocalId:t.msgLocalId,protocolId:n,type:t.type,conversationType:t.conversationType,conversationId:t.conversationId});try{const e="combine"===r.type?this.prepareCombineMessage(r):r,t={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,s):e,sendStatus:"sending"};Fo(r,t),r=t,s?.onSending?.(t);const n=await this.doSendMessage(t);return s?.onSuccess?.(n),n}catch(i){const e={...r,sendStatus:"failed"};throw Fo(r,e),s?.onFailed?.(e,i instanceof Error?i:new Error(String(i))),i}}async sendAction(e,t){const s=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&a.debug("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:s,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const n=this.msyncCodec.encodeActionMessage(e,s);"clearAllConversationUnreadMessageCount"===e.kind&&a.debug("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:s,payloadBytes:n.byteLength});const r="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(s,n,t,this.createPendingDataReport({category:"message",operationName:r,operationType:"MESSAGE",requestName:r,msgId:e.messageId,messageType:Sc(e.conversationType)}))}async sendChatRoomOperation(e,t){const s=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),n=this.msyncCodec.encodeChatRoomOperation(e,s),r="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(s,n,t,this.createPendingDataReport({category:"chatroom",operationName:r,operationType:"CHATROOM",requestName:r,msgId:e.chatRoomId}))}async doSendMessage(t){const s=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:t.msgLocalId,messageType:Sc(t.conversationType)});return new Promise((n,r)=>{const i=this.msyncCodec.toProtocolId(t.msgLocalId),c=setTimeout(()=>{this.pendingMessages.delete(i),this.finishPendingDataReport(s,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),r(new b("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(i,{kind:"message",message:t,protocolId:i,timeoutId:c,resolve:e=>{clearTimeout(c),n(e)},reject:e=>{clearTimeout(c),r(e)},report:s});try{if(!this.websocket||this.websocket.readyState!==o.OPEN)throw new b("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}});const n=this.msyncCodec.encodeChatMessage(t,i),d=this.msyncCodec.prepareOutgoing(n);Promise.resolve(this.websocket.send(d)).catch(n=>{const o=n instanceof Error?n.message:String(n);this.pendingMessages.delete(i),clearTimeout(c),this.finishPendingDataReport(s,{code:-1,success:!1,description:o}),a.warn("Message send socket failure",{msgLocalId:t.msgLocalId,protocolId:i,websocketReadyState:this.websocket?.readyState??null,cause:o}),r(new b(`WebSocket send failed: ${o}`,{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0,cause:o}}))}),a.debug("Message sent",{msgLocalId:t.msgLocalId,protocolId:i})}catch(d){if(this.pendingMessages.delete(i),clearTimeout(c),this.finishPendingDataReport(s,{code:d instanceof b?d.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof b)throw d;throw new b("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}})}})}async sendProtocolPayload(t,s,n,r){return new Promise((i,a)=>{const c=setTimeout(()=>{this.pendingMessages.delete(t),this.finishPendingDataReport(r,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),a(new b("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{protocolId:t,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(t,{kind:"action",protocolId:t,timeoutId:c,createAckError:n,resolve:i,reject:a,report:r});try{if(!this.websocket||this.websocket.readyState!==o.OPEN)throw new b("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0}});const n=this.msyncCodec.prepareOutgoing(s);Promise.resolve(this.websocket.send(n)).catch(s=>{const n=s instanceof Error?s.message:String(s);this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(r,{code:-1,success:!1,description:n}),a(new b(`WebSocket action send failed: ${n}`,{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0,cause:n}}))})}catch(d){if(this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(r,{code:d instanceof b?d.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof b)throw d;a(new b("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{protocolId:t,retryable:!1}}))}})}prepareCombineMessage(t){const s=t.body,n=s.messageList??[];He(n);const r=ze(n);je(r);const i=((t,s)=>{try{const n=t.map((t,n)=>{const r=s(t,n);if(0===r.length)throw new b("Combine payload item encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{index:n}});return r}),r=cc.length+n.reduce((e,t)=>e+4+t.length,0)+1,i=new Uint8Array(r);let o=0;i.set(cc,o),o+=cc.length;for(const e of n){const t=pc(e.length);i.set(t,o),o+=t.length,i.set(e,o),o+=e.length}const a=fc(i.subarray(0,i.length-1));return i[i.length-1]=a,i}catch(n){if(n instanceof b)throw n;throw new b("Combine payload encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{cause:n instanceof Error?n.message:String(n)}})}})(n,e=>this.msyncCodec.encodeCombineMessageMeta(e)),o=new ArrayBuffer(i.byteLength);new Uint8Array(o).set(i);const a=new File([o],s.filename||"combine",{type:s.filetype||"application/octet-stream"}),c=We(a);if(!c&&!this.attachmentUploader)throw new b("Combine payload local url generation failed",{code:e.COMBINE_ENCODE_FAILED});Qe.set(t.msgLocalId,a);const d={...t,body:{...s,combineLevel:r,fileLength:i.byteLength,filename:s.filename||"combine",filetype:s.filetype||"application/octet-stream",url:c??s.url}};return Fo(t,d),$e(t,d),d}handleAck(e,t,s,n){const r=this.pendingMessages.get(e);if(!r)return void a.debug("Received ACK without a tracked pending message",{protocolId:e});if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:200,success:!0}),void r.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:n});const i={...r.message,...this.resolveReplacedMessage(r.message,s),sendStatus:"sent",msgServerId:t||s?.msgServerId||r.message.msgServerId};Fo(r.message,i),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:200,success:!0}),"image"!==i.type&&"video"!==i.type&&"voice"!==i.type&&"file"!==i.type&&"combine"!==i.type||Qe.delete(i.msgLocalId),a.debug("Message ACK matched",{protocolId:e,msgLocalId:i.msgLocalId,msgServerId:i.msgServerId??null,type:i.type,conversationType:i.conversationType,conversationId:i.conversationId}),this.eventHub.dispatch(Ge.MESSAGE_SENT,i),r.resolve(i)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const s=this.pendingMessages.get(e);if(!s)return;if("action"===s.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(s.report,{code:t instanceof b?t.code:-1,success:!1,description:t.message}),void s.reject(t);const n={...s.message,sendStatus:"failed"};Fo(s.message,n),this.pendingMessages.delete(e),this.finishPendingDataReport(s.report,{code:t instanceof b?t.code:-1,success:!1,description:t.message}),a.warn("Message send failed after ACK/error",{protocolId:e,msgLocalId:n.msgLocalId,type:n.type,conversationType:n.conversationType,conversationId:n.conversationId,error:t.message}),s.reject(t)}handleAckFailure(e,t,s,n){const r=this.pendingMessages.get(e);if(r)return"action"===r.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t,success:!1,description:s??n.message}),void r.reject(r.createAckError?.(t,s)??n)):void this.handleSendError(e,n)}setWebSocket(e){this.websocket=e}destroy(){for(const[t,s]of this.pendingMessages)clearTimeout(s.timeoutId),this.finishPendingDataReport(s.report,{code:-1,success:!1,description:"Message sender destroyed"}),s.reject(new b("Message sender destroyed",{code:e.MESSAGE_SENDER_DESTROYED,details:"message"===s.kind?{msgLocalId:s.message.msgLocalId,protocolId:t,retryable:!1}:{protocolId:t,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=w){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(a.warn("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=E({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(t)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:t,request:t.startRequest({requestName:e.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(e,t){e&&!e.released&&(e.released=!0,e.request.finish(t),e.operation.finish(t),"message"===e.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<w&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<w&&(this.chatRoomReportSaturated=!1)))}}class bc{constructor(e){this.sessions=/* @__PURE__ */new Map,this.ttlMs=e?.ttlMs??3e5,this.maxSessions=e?.maxSessions??100}getOrCreate(e){this.evictStale();const t=this.sessions.get(e);if(t)return t.lastActivityTs=Date.now(),t;this.sessions.size>=this.maxSessions&&this.evictOldest();const s={msgId:e,startSeq:null,lastDispatchedSeq:-1,fullText:"",completed:!1,chunksBySeq:/* @__PURE__ */new Map,lastActivityTs:Date.now()};return this.sessions.set(e,s),s}get(e){return this.sessions.get(e)}addChunk(e,t){const s=this.getOrCreate(e),n=t.stream.seq;return s.chunksBySeq.has(n)?{duplicate:!0,session:s}:(s.chunksBySeq.set(n,t),s.lastActivityTs=Date.now(),t.stream.status!==ss.START&&t.stream.status!==ss.START_COMPLETED||null!==s.startSeq||(s.startSeq=n),{duplicate:!1,session:s})}getSequentialChunks(e){const t=this.sessions.get(e);if(!t||t.completed||null===t.startSeq)return[];let s=t.lastDispatchedSeq<t.startSeq?t.startSeq:t.lastDispatchedSeq+1;const n=[];for(;t.chunksBySeq.has(s);){const e=t.chunksBySeq.get(s);if(!e)break;n.push(e),s+=1}return n}markDispatched(e,t,s){const n=this.sessions.get(e);if(!n)return;const r=t.stream.seq;n.lastDispatchedSeq=Math.max(n.lastDispatchedSeq,r),n.fullText=s,n.chunksBySeq.delete(r)}markCompleted(e,t,s){const n=this.getOrCreate(e);n.completed=!0,n.completedReason=t,n.fullText=s}clear(e){this.sessions.delete(e)}clearAll(){this.sessions.clear()}evictStale(){const e=Date.now();for(const[t,s]of this.sessions)e-s.lastActivityTs>this.ttlMs&&this.sessions.delete(t)}evictOldest(){let e=null,t=1/0;for(const[s,n]of this.sessions)n.lastActivityTs<t&&(t=n.lastActivityTs,e=s);e&&this.sessions.delete(e)}}class Tc{constructor(e,t){this.completedIds=/* @__PURE__ */new Set,this.eventHub=e,this.cache=t??new bc}handle(e){const t=this.resolveMessageId(e);if(!t)return void a.warn("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void a.debug("stream message already completed, ignore",{msgId:t});if(e.stream.status===ss.FULL)return void this.handleFullChunk(t,e);const s=this.cache.get(t);if(s?.completed)return void a.debug("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:n}=this.cache.addChunk(t,e);n?a.debug("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const s of t){const t=this.cache.get(e);if(!t)return;const n=t.fullText,r=s.stream.deltaText,i=`${n}${r}`,o=s.stream.errorType>0?ss.ERROR:s.stream.status,a=this.buildDispatchMessage(s,{status:o,fullText:i,deltaText:r});if(this.eventHub.dispatch(ct.STREAM_MESSAGE,a),this.cache.markDispatched(e,s,i),o===ss.START_COMPLETED||o===ss.COMPLETED||o===ss.ERROR){const t=o===ss.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else a.debug("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const s=this.cache.get(e),n=s?.fullText??"",r=this.resolveFullText(t,n),i=this.resolveDeltaText(n,r,t.stream.deltaText),o=!s||-1===s.lastDispatchedSeq&&0===s.chunksBySeq.size,a=t.stream.errorType>0?ss.ERROR:o?ss.START_COMPLETED:ss.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:r,deltaText:i});this.eventHub.dispatch(ct.STREAM_MESSAGE,c);const d=a===ss.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,d,r),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const s=this.cache.get(e),n=s?.fullText??"",r=this.resolveFullText(t,n),i=this.resolveDeltaText(n,r,t.stream.deltaText),o=this.buildDispatchMessage(t,{status:ss.ERROR,fullText:r,deltaText:i});this.eventHub.dispatch(ct.STREAM_MESSAGE,o),this.cache.markCompleted(e,"timeout_error",r),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const s=e.stream.fullText;if(s&&s.length>=t.length)return s;const n=e.body.content;return n&&n.length>=t.length?n:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,s){return t.startsWith(e)?t.slice(e.length):s}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class Ac{constructor(e=100){this.seenIds=/* @__PURE__ */new Set,this.orderedIds=[],this.limit=Math.max(1,Math.floor(e))}checkAndRecord(e){if(!e)return!1;if(this.seenIds.has(e))return!0;for(this.seenIds.add(e),this.orderedIds.push(e);this.orderedIds.length>this.limit;){const e=this.orderedIds.shift();e&&this.seenIds.delete(e)}return!1}clear(){this.seenIds.clear(),this.orderedIds.length=0}size(){return this.seenIds.size}}const wc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Nc{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new Tc(s),this.messageContexts=/* @__PURE__ */new Map,this.recentMessageIds=new Ac(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{a.debug("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);a.debug("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:s,messages:n}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),s&&(a.debug("Decoded sync ACK",{ok:s.ok,protocolId:s.protocolId,serverId:s.serverId??null,statusCode:s.statusCode??null,reason:s.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(s,t.replacedMessage));for(const e of n)this.dispatchMessage(e);return t}catch(t){a.error("Failed to decode sync payload",t)}return null}handleAck(t,s){if(t.ok)return a.debug("ACK accepted",{protocolId:t.protocolId,serverId:t.serverId??null,hasReplacedMessage:Boolean(s)}),void(t.chatRoomInfo?this.messageSender.handleAck(t.protocolId,t.serverId,s,t.chatRoomInfo):this.messageSender.handleAck(t.protocolId,t.serverId,s));a.warn("ACK rejected",{protocolId:t.protocolId,statusCode:t.statusCode,reason:t.reason,hasReplacedMessage:Boolean(s)});const n=((t,s)=>{const n=Un(t,s),r=n.code===e.UNKNOWN?e.MESSAGE_SEND_FAILED:n.code;return{code:r,message:Ln[r]??(s?`Message send failed: ${s}`:"Message send failed for an unknown reason"),retryable:n.retryable}})(t.statusCode,t.reason),r=new b(n.message,{code:n.code,details:{protocolId:t.protocolId,serverCode:t.statusCode,reason:t.reason,retryable:!1}});this.messageSender.handleAckFailure(t.protocolId,t.statusCode,t.reason,r)}dispatchMessage(e){if(ns(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?a.debug("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(ct.MESSAGE,e),a.debug("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{a.warn("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const s of e)if("presence"===s.type)this.handlePresenceNotify(s);else if("contact"===s.type)this.handleContactNotify(s);else if("group"===s.type)this.handleGroupNotify(s);else if("thread"===s.type)this.handleChatThreadNotify(s);else if("chatroom"===s.type)this.handleChatRoomNotify(s);else if("reaction"===s.type)this.handleReactionNotify(s);else if("conv"===s.type)this.handleConversationNotify(s);else if("multiDevice"===s.type)this.handleMultiDeviceNotify(s);else if("message_receipts"===s.type){const e=this.toMessageReceiptPayload(s);e&&t.push(e)}else"message_recalled"===s.type?this.handleMessageRecalledNotify(s):"message_updated"===s.type?this.handleMessageUpdatedNotify(s):"message_delivered"===s.type?this.handleMessageDeliveredNotify(s):this.handleUserInfoNotify(s);t.length>0&&this.eventHub.dispatch(ct.MESSAGE_READ_RECEIPTS,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const s=e.data;if(!s||"object"!=typeof s)return;const n=s,r="string"==typeof n.username?n.username:"string"==typeof n.userId?n.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=n.metadata&&"object"==typeof n.metadata&&!Array.isArray(n.metadata)?n.metadata:null,o="number"==typeof n.lastModified?n.lastModified:"string"==typeof n.lastModified?Number(n.lastModified):Number.NaN;if(!r||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:r,metadata:i,lastModified:o};this.eventHub.dispatch(Ge.USER_INFO_NOTIFY,a)}handleContactNotify(e){if(a.debug("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==dt.INVITED&&e.eventName!==dt.DELETED&&e.eventName!==dt.ADDED&&e.eventName!==dt.REFUSE&&e.eventName!==dt.AGREED)return;const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.from&&s.from&&"string"==typeof s.to&&s.to&&"string"==typeof s.message&&this.eventHub.dispatch(e.eventName,s)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t,n=Array.isArray(s.values)?s.values:[];if(0===n.length)return;const r=[];for(const i of n){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),s="string"==typeof e.uid?e.uid:"";s&&r.push({userId:s,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==r.length&&this.eventHub.dispatch(lt.STATUS_CHANGE,r)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(Ge.GROUP_NOTIFY,s)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(Ge.CHATROOM_NOTIFY,s)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const s of t){if(!wc(s)||"string"!=typeof s.messageId)continue;const e=this.resolveReactionConversationContext(s);e&&this.eventHub.dispatch(ct.REACTION_CHANGED,{messageId:s.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(s.reactions),timestamp:this.normalizeTimestamp(s.ts)})}}handleConversationNotify(e){if(!wc(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const s=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===s.clientResource&&"string"==typeof t.from&&t.from===s.userId)return;const n="string"==typeof t.ext?t.ext:"",r="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";n&&i&&o&&this.eventHub.dispatch(ct.PINNED_MESSAGE_CHANGED,{messageId:n,conversationId:"chat"===r?i:o,conversationType:"chat"===r?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!wc(e.data)||"string"!=typeof e.eventName)return;const t=e.data;switch(e.eventName){case"onMultiDeviceContact":case"onMultiDeviceGroup":case"onMultiDeviceThread":case"onMultiDeviceConversation":case"onMultiDeviceMessageRemoved":return void this.eventHub.dispatch(e.eventName,t);default:return}}toMessageReceiptPayload(e){if(!wc(e.data))return null;const t=e.data;if(!Array.isArray(t.messageIds)||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||"number"!=typeof t.timestamp)return null;const s=t.messageIds.filter(e=>"string"==typeof e&&e.length>0);if(0===s.length)return null;const n=s[0];if(!n)return null;const r=this.resolveMessageReceiptContext(n,t.conversationId,t.conversationType);if("groupChat"===r.conversationType){const e=new Set(s),n=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!wc(t))return[];const s=t.messageId,n=t.count;return"string"==typeof s&&e.has(s)&&"number"==typeof n&&Number.isInteger(n)&&n>=0?[{messageId:s,count:n}]:[]}):[];return{messageIds:s,conversationId:r.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:n}}return{messageIds:s,conversationId:r.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!wc(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(ct.MESSAGE_DELIVERED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!wc(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(ct.MESSAGE_RECALLED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}handleMessageUpdatedNotify(e){if(!wc(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!wc(t.message)||"string"!=typeof t.message.type||!wc(t.message.body)||!wc(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...wc(t.message.modifiedInfo)?{modifiedInfo:{operatorId:"string"==typeof t.message.modifiedInfo.operatorId?t.message.modifiedInfo.operatorId:"",operationCount:"number"==typeof t.message.modifiedInfo.operationCount?t.message.modifiedInfo.operationCount:0,operationTime:"number"==typeof t.message.modifiedInfo.operationTime?t.message.modifiedInfo.operationTime:0}}:{}};this.eventHub.dispatch(ct.MESSAGE_UPDATED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",message:s,timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}normalizeUpdatedMessageBody(e,t){if("text"!==e)return t;const s="string"==typeof t.content?t.content:"string"==typeof t.message?t.message:void 0;if(void 0===s)return t;const{message:n,...r}=t;return{...r,content:s}}handleChatThreadNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"onChatThreadChange"===s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(Ge.CHAT_THREAD_NOTIFY,s)}normalizePresenceStatus(e){if(!e||"object"!=typeof e)return[];return Object.entries(e).map(([e,t])=>({device:e,status:Number(t)||0}))}destroy(){this.streamMessageHandler.destroy(),this.recentMessageIds.clear(),this.messageContexts.clear()}rememberMessageContext(e){const t=this.resolveMessageContextId(e),s=this.resolveMessageConversationContext(e);if(t&&s)for(this.messageContexts.delete(t),this.messageContexts.set(t,s);this.messageContexts.size>500;){const e=this.messageContexts.keys().next().value;if(!e)break;this.messageContexts.delete(e)}}resolveMessageReceiptContext(e,t,s){const n=this.messageContexts.get(e);return n||("groupChat"===s?{conversationId:t,conversationType:"groupChat"}:{conversationId:t,conversationType:"singleChat"})}resolveMessageContextId(e){return"string"==typeof e.msgServerId&&e.msgServerId.length>0?e.msgServerId:"string"==typeof e.msgLocalId&&e.msgLocalId.length>0?e.msgLocalId:""}resolveMessageConversationContext(e){if("string"!=typeof e.conversationId||!e.conversationId)return null;if("groupChat"===e.conversationType)return{conversationId:e.conversationId,conversationType:"groupChat"};if("chatRoom"===e.conversationType)return{conversationId:e.conversationId,conversationType:"chatRoom"};if("singleChat"!==e.conversationType)return null;const t=this.msyncCodec.getContext().userId,s="SEND"===e.direct||e.sender.userId===t?e.conversationId:e.sender.userId;return s?{conversationId:s,conversationType:"singleChat"}:null}resolveReactionConversationContext(e){const t="string"==typeof e.from?e.from:"",s="string"==typeof e.to?e.to:"",n="string"==typeof e.channel_type?e.channel_type:"";if(!t||!s)return null;if("groupChat"===n||"groupchat"===n||"group"===n)return{conversationId:s,conversationType:"groupChat",from:t,to:s};if(""!==n&&"chat"!==n&&"singleChat"!==n)return null;return{conversationId:t===this.msyncCodec.getContext().userId?s:t,conversationType:"singleChat",from:t,to:s}}normalizeReactionList(e){if(!Array.isArray(e))return[];const t=[];for(const s of e)wc(s)&&"string"==typeof s.reaction&&t.push({reaction:s.reaction,count:"number"==typeof s.count&&Number.isFinite(s.count)?s.count:0,userList:Array.isArray(s.userList)?s.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof s.isAddedBySelf?s.isAddedBySelf:void 0,op:this.normalizeReactionOperations(s.op)});return t}normalizeReactionOperations(e){if(!Array.isArray(e))return;const t=[];for(const s of e)!wc(s)||"string"!=typeof s.operator||"create"!==s.reactionType&&"delete"!==s.reactionType||t.push({operator:s.operator,reactionType:s.reactionType});return t.length>0?t:void 0}normalizeTimestamp(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){const t=Number(e);return Number.isFinite(t)?t:0}return 0}}const Mc=e=>e instanceof Error?e.message:String(e);class Rc{constructor(e){this.requestAdapter=N(e)}async downloadAndParse(t){const s=t.url.trim();if(!s)throw new M("Combine message url is required",{code:e.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const n="number"==typeof t.maxItems?t.maxItems:Ye;Je(1,n);const r=R(s,t.secret);try{const s=await this.requestAdapter.request({url:r,method:"GET",responseType:"arraybuffer",timeoutMs:t.timeoutMs??15e3,headers:{[_]:h()}});if(401===s.status||403===s.status)throw new D(401===s.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===s.status?e.AUTH_UNAUTHORIZED:e.AUTH_FORBIDDEN,details:{url:r,httpStatus:s.status}});if(s.status>=400)throw new T("Combine payload download failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{status:s.status,url:r}});const i=(t=>{if(t.length<cc.length+1)throw new T("Combine payload is too short",{code:e.COMBINE_PARSE_FAILED});const s=t.subarray(0,cc.length);if(s[0]!==cc[0]||s[1]!==cc[1])throw new T("Combine payload header is invalid",{code:e.COMBINE_PARSE_FAILED});const n=t.subarray(0,t.length-1),r=fc(n),i=t[t.length-1]??0;if(i!==r)throw new T("Combine payload checksum failed",{code:e.COMBINE_PARSE_FAILED,details:{expectedChecksum:r,actualChecksum:i}});const o=[];let a=cc.length;const c=t.length-1;for(;a<c;){if(a+4>c)throw new T("Combine payload length header is incomplete",{code:e.COMBINE_PARSE_FAILED});const s=mc(t,a);if(a+=4,s<=0||a+s>c)throw new T("Combine payload item length is invalid",{code:e.COMBINE_PARSE_FAILED,details:{itemLength:s}});const n=t.subarray(a,a+s);a+=s;const r=Cc(n,o.length);o.push(r)}if(a!==c)throw new T("Combine payload has unexpected trailing bytes",{code:e.COMBINE_PARSE_FAILED,details:{offset:a,expected:c}});return o})((t=>{if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if("string"==typeof t)return On(t);throw new T("Combine payload response type is invalid",{code:e.COMBINE_DOWNLOAD_FAILED})})(s.data));return Je(i.length,n),He(i),i.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(i){if(i instanceof M||i instanceof D||i instanceof T)throw i;throw new T("Combine payload download or parse failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{cause:Mc(i),url:r}})}}}const _c=e=>{switch(e.type){case"image":return e.body.filename??"image";case"video":return e.body.filename??"video";case"voice":return e.body.filename??"voice";case"file":return e.body.filename??"file";default:return"attachment"}},Dc=e=>{switch(e.type){case"image":case"video":case"voice":case"file":return e.body.filetype??"application/octet-stream";default:return"application/octet-stream"}};class Uc{constructor(e){this.requestAdapter=N(e)}async download(t,s=15e3){if("image"!==t.type&&"video"!==t.type&&"voice"!==t.type&&"file"!==t.type)throw new M("message does not contain downloadable attachment",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:n,secret:i}=(e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}})(t);if(!n)throw new M("attachment url is required",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});let o;try{o=await this.requestAdapter.request({url:R(n,i),method:"GET",responseType:"arraybuffer",timeoutMs:s,headers:{[_]:h()}})}catch(a){if("object"==typeof a&&null!==a&&a.code===r.MISSING_CAPABILITY)throw new U("request adapter is required for attachment download");throw a}if(401===o.status)throw new D("attachment download unauthorized",{code:e.AUTH_UNAUTHORIZED,details:{url:n,httpStatus:o.status}});if(403===o.status)throw new D("attachment download forbidden",{code:e.AUTH_FORBIDDEN,details:{url:n,httpStatus:o.status}});if(404===o.status){const t=("string"==typeof o.data?o.data:"").includes("expired");throw new L(t?"attachment file is expired":"attachment not found",t?e.ATTACHMENT_EXPIRED:e.ATTACHMENT_NOT_FOUND)}if(429===o.status)throw new L("attachment download rate limited",e.SERVICE_LIMIT_EXCEEDED);if(o.status>=400)throw new L("attachment download failed",e.FILE_DOWNLOAD_FAILED,{details:{status:o.status,url:n}});return{filename:_c(t),mimeType:Dc(t),size:(()=>{switch(t.type){case"image":case"video":case"voice":return t.body.fileLength;case"file":return t.body.fileLength??t.body.fileSize;default:return}})(),data:new Uint8Array(o.data),downloadUrl:n}}}const Lc=(e,t,s)=>({Authorization:`Bearer ${e}`,Accept:t,[_]:h(),...s??{}}),Oc=async t=>{const s=Lc(t.token,"application/json",t.headers),n=Date.now(),r="upload.multipart.init"===t.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===t.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",i=t.dataReportOperation?.startRequest({requestName:r,method:t.method,url:t.url});let o=0;a.debug("Upload request start",{operation:t.operation,method:t.method});try{const r=await t.requestAdapter.request({url:t.url,method:t.method,headers:s,responseType:"json",timeoutMs:K});o=r.status;const d=Date.now()-n;if(r.status<200||r.status>=300)throw a.warn("Upload response error",{operation:t.operation,method:t.method,status:r.status,duration:d}),new k("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:r.status}});a.debug("Upload response success",{operation:t.operation,method:t.method,status:r.status,duration:d});const l="string"==typeof(c=r.data)?JSON.parse(c):c;return i?.finish({code:r.status,success:!0}),l}catch(d){if(i?.finish({code:0!==o?o:d instanceof k?d.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof k)throw d;throw a.warn("Upload request failed",{operation:t.operation,method:t.method}),new k("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}var c},kc=async t=>{const s=Date.now(),n=t.dataReportOperation?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:t.url});a.debug("Upload part start",{operation:"upload.multipart.part",partNumber:t.partNumber});try{const r=await t.uploadAdapter.upload({url:t.url,method:"PUT",headers:Lc(t.token,"*/*",{"restrict-access":"true"}),source:{sourceType:"web-file",file:t.part,name:`${t.fileName}.part-${t.partNumber}`,mimeType:t.fileType,size:t.part.size},fields:{part_number:t.partNumber},fileFieldName:"part_file",timeoutMs:K,onProgress:e=>t.onProgress?.(e.loaded)}),i=Date.now()-s;if(r.status<200||r.status>=300)throw new k("Upload part failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,partNumber:t.partNumber,status:r.status,response:r.body}});a.debug("Upload part success",{operation:"upload.multipart.part",partNumber:t.partNumber,duration:i}),n?.finish({code:r.status,success:!0})}catch(r){const e=It(r),s=e.details&&"object"==typeof e.details?e.details:void 0;throw n?.finish({code:e.code,success:!1,description:e.message}),a.warn("Upload part failed",{operation:"upload.multipart.part",partNumber:t.partNumber}),new k(e.message,{code:e.code,details:{...s,url:t.url,partNumber:t.partNumber}})}},Pc=async t=>{if(t.fileSize<=O)throw new k("Multipart not required",{code:e.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:s,file:n,conversationId:r,conversationType:i,fileName:o,fileType:a,fileSize:c,messageType:d,imageType:l,md5:u,width:h,height:p}=t,m=(e=>N(e))(s.requestAdapter),f=(t=>{if(t)return t;const s=Mr();if(s)return s;throw new k("Upload adapter is required for multipart upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:g,appName:y}=P(s.appKey),I=`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload`;let v;try{v=await Oc({url:I,method:"POST",token:s.token,operation:"upload.multipart.init",requestAdapter:m,dataReportOperation:t.dataReportOperation})}catch(U){throw new k("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:U,url:I}})}const C=(t=>{const s=t.entities?.[0],n="number"==typeof s?.file_upper_limit?s.file_upper_limit:0,r="number"==typeof s?.part_lower_limit?s.part_lower_limit:G,i="string"==typeof s?.uuid?s.uuid:"";if(!i)throw new k("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{fileMaxSize:n,partMinSize:r,uuid:i}})(v);if(C.fileMaxSize&&c>C.fileMaxSize)throw new k("File size exceeds limit",{code:e.UPLOAD_SIZE_EXCEEDED,details:{fileSize:c,maxSize:C.fileMaxSize}});const S=C.partMinSize||G,E=Math.ceil(c/S),b=Array.from({length:E},()=>0),T=`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload/${C.uuid}`,A=[],w=(e,s)=>{b[e]=s;const n=b.reduce((e,t)=>e+t,0),r=c?n/c*100:void 0;t.callbacks?.onFileUploadProgress?.({loaded:n,total:c,percent:r})};for(let e=0;e<E;e+=1){const r=e*S,i=Math.min(c,r+S),d=n.slice(r,i),l=String(e+1),u=kc({url:T,token:s.token,partNumber:l,part:d,fileName:o,fileType:a,uploadAdapter:f,onProgress:t=>w(e,t),dataReportOperation:t.dataReportOperation}).finally(()=>{const e=A.indexOf(u);e>=0&&A.splice(e,1)});A.push(u),A.length>=x&&await Promise.race(A)}await Promise.all(A);const M=V(i),R=F(`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload/${C.uuid}`,{"restrict-access":"true","chat-type":M,"chat-target":r,"thumbnail-width":t.thumbnailWidth,"thumbnail-height":t.thumbnailHeight,md5:u??"",..."image"===d?{imageType:B(l),width:h,height:p}:{}}),_=await Oc({url:R,method:"POST",token:s.token,operation:"upload.multipart.complete",requestAdapter:m,dataReportOperation:t.dataReportOperation}),D=q({response:_,restBaseUrl:s.restBaseUrl,orgName:g,appName:y,fileType:a,fileName:o,fallbackSize:c,messageType:d,imageType:l,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(D),D},xc=async t=>{const{config:s,file:n,conversationId:r,conversationType:i,messageType:o,imageType:c,md5:d,width:l,height:u,fileName:p,fileType:m,fileSize:f}=t,g=(t=>{if(t)return t;const s=Mr();if(s)return s;throw new k("Upload adapter is required for simple upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:y,appName:I}=P(s.appKey),v=V(i),C=F(`${s.restBaseUrl}/${y}/${I}/chatfiles`,{"chat-type":v,"chat-target":r,md5:d??"",..."image"===o?{imageType:B(c),width:l,height:u}:{}}),S=Date.now(),E=t.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:C});a.debug("Upload request start",{operation:"upload.simple",method:"POST",fileSize:f,messageType:o});const b={};let T;void 0!==t.thumbnailWidth&&(b["thumbnail-width"]=String(t.thumbnailWidth)),void 0!==t.thumbnailHeight&&(b["thumbnail-height"]=String(t.thumbnailHeight));try{T=await g.upload({url:C,method:"POST",headers:{"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${s.token}`,[_]:h()},source:{sourceType:"web-file",file:n,name:p,mimeType:m,size:f},fields:b,fileFieldName:"file",timeoutMs:K,onProgress:e=>t.callbacks?.onFileUploadProgress?.(e)})}catch(A){const s=It(A),n=s.details&&"object"==typeof s.details?s.details:void 0,r=new k(s.message,{code:s.code,details:{...n,url:C,...s.code===e.UPLOAD_TIMEOUT?{timeout:K}:{}}});throw E?.finish({code:r.code,success:!1,description:r.message}),r.code===e.UPLOAD_ABORTED?(a.warn("Upload request aborted",{operation:"upload.simple"}),t.callbacks?.onFileUploadCanceled?.()):r.code===e.UPLOAD_TIMEOUT?a.warn("Upload request timeout",{operation:"upload.simple",timeout:K}):a.warn("Upload request failed",{operation:"upload.simple"}),r}try{const n=JSON.parse(T.body),r=Date.now()-S;if(T.status>=400)throw a.warn("Upload response error",{operation:"upload.simple",status:T.status,duration:r}),new k("Upload failed",{code:e.UPLOAD_REQUEST_FAILED,details:{status:T.status,response:n}});a.debug("Upload response success",{operation:"upload.simple",status:T.status,duration:r});const i=q({response:n,restBaseUrl:s.restBaseUrl,orgName:y,appName:I,fileType:m,fileName:p,fallbackSize:f,messageType:o,imageType:c,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(i),E?.finish({code:T.status||200,success:!0}),i}catch(A){throw E?.finish({code:A instanceof k?A.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:A instanceof Error?A.message:String(A)}),A instanceof Error?A:new Error(String(A))}},Fc=Vr(),Bc=e=>Object.prototype.toString.call(e),qc=e=>{const t=e&&"object"==typeof e?e:null,s="string"==typeof t?.path?t.path:void 0,n="string"==typeof t?.uri?t.uri:void 0,r="string"==typeof t?.name?t.name:void 0,i="string"==typeof t?.type?t.type:void 0,o="number"==typeof t?.size?t.size:void 0;return{kind:Bc(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof s&&s.length>0,pathPrefix:s?s.slice(0,48):void 0,hasUri:"string"==typeof n&&n.length>0,uriPrefix:n?n.slice(0,48):void 0,name:r,type:i,size:o}},Kc=e=>({sourceType:e.source.sourceType,fileName:e.fileName,fileType:e.fileType,fileSize:e.fileSize,hasWebFile:Boolean(e.webFile),sourceName:e.source.name,sourceMimeType:e.source.mimeType,sourceSize:e.source.size}),Gc=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Vc=e=>"object"==typeof e&&null!==e,Hc=(e,t)=>{const s=Vc(t)?t:void 0,n=s?.code===r.MISSING_CAPABILITY&&s.stage===i.RUNTIME;return"miniapp-path"===e&&(e=>{if(!Vc(e))return!1;const t=Vc(e.details)?e.details:void 0;return e.code===r.MISSING_CAPABILITY&&e.stage===i.RUNTIME&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&n};class zc{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(t,s){if(!Gc(t.type))return t;const n=t.body;if(this.hasUploadedRemoteResource(t.type,n))return t;const r=this.resolveUploadUrl(t.type,n),i=Qe.get(t.msgLocalId),o=Boolean(i);if(a.warn("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:t.msgLocalId,messageType:t.type,conversationType:t.conversationType,hasFile:o,uploadUrl:r,cachedFile:qc(i),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!H(r,o))return t;if(!i)throw new k("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:t.msgLocalId,url:r}});if(!this.config?.restBaseUrl)throw new k("REST base url is required for upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let c,d,l;try{c=await this.prepareAttachmentUpload(t,n,i),c.precheck?.hit||(l=E({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:t.msgLocalId,messageType:t.type})),d=c.precheck?.hit?this.buildPrecheckedUploadResult(t,c,s):await this.uploadAttachment(t,c,s,l),l?.finish({code:0,success:!0})}catch(u){const t=It(u);throw l?.finish({code:t.code,success:!1,description:t.message}),t.code===e.UPLOAD_ABORTED&&s?.onFileUploadCanceled?.(),s?.onFileUploadError?.(t),t}return this.buildPreparedMessage(t,c,d)}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&z(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&z(t.url)}async prepareAttachmentUpload(e,t,s){const n=j(s,t);if(a.warn("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Kc(n)}),"image"!==e.type){return{body:t,fileInfo:n,md5FileInfo:n,precheck:await this.maybePrecheck(e,n,n,void 0)}}const r=t,i=await this.resolveImageCandidate(r,n),o={...r,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===l},c=await this.maybePrecheck(e,i.fileInfo,n,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:n,imageType:i.imagePolicy.resolvedImageType,precheck:c,originalWidth:r.width,originalHeight:r.height}}async resolveImageCandidate(e,t){const s=W(e);if(a.warn("Image send policy resolved",{operation:"upload.image.policy",reason:s.reason,imageType:s.resolvedImageType,isGif:e.isGif,source:Kc(t)}),s.resolvedImageType===l){let n=e.width,r=e.height;if(!n||!r){const e=this.resolveImageProcessor(t.source.sourceType);a.warn("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Kc(t)});const s=await e.getImageInfo(t.source);n=s.width,r=s.height}return{imagePolicy:s,sourceKind:"origin",fileInfo:t,width:n,height:r}}try{const e=this.resolveImageProcessor(t.source.sourceType);a.warn("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Kc(t)});const n=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:s,sourceKind:"big",fileInfo:{source:n.source,fileName:n.fileName??t.fileName,fileType:n.fileType??t.fileType,fileSize:n.fileSize??t.fileSize,webFile:n.webFile},width:n.width,height:n.height}}catch(n){return a.warn("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:s.reason,error:n instanceof Error?n.message:String(n),source:Kc(t)}),{imagePolicy:{resolvedImageType:l,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,s,n){if(!Gc(e.type))return;if(!0!==this.config?.enableMd5Check)return void a.debug("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:n,fileSize:t.fileSize});const r=Q({messageType:e.type,fileSize:t.fileSize,imageType:n});if(!r.shouldPrecheck)return void a.debug("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:n,fileSize:t.fileSize,thresholdBytes:r.thresholdBytes});let i;try{i=await this.computeMd5(s)}catch(c){if(Hc(s.source.sourceType,c))return void a.warn("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:n,thresholdType:r.thresholdType,source:Kc(s),error:c instanceof Error?c.message:String(c)});throw c}const o=await this.requestPrecheck(e,r.thresholdType,i,n);return a.debug(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:n,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return a.warn("Attachment md5 compute start",{operation:"upload.md5.start",source:Kc(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return a.warn("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return a.warn("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Fc;throw a.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),n("Image processor capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(t,s,n,r){if(!this.config)throw new k("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:o}=P(this.config.appKey),c=F(`${this.config.restBaseUrl}/${i}/${o}/chatfiles/exists`,{md5:n,..."image"===t.type?{imageType:B(r)}:{}}),d=await this.requestJson({url:c,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(e=>{a.warn("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:t.type,imageType:r,thresholdType:s,md5:n,error:e instanceof Error?e.message:String(e)})});return d?$(d):{exists:!1,hit:!1}}async requestJson(e){return this.requestByAdapter(N(this.config?.requestAdapter),e)}async requestByAdapter(t,s){const n=await t.request({url:s.url,method:s.method,headers:s.headers,responseType:"json",timeoutMs:K});if(n.status>=400)throw new k("Upload precheck request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:n.status,operation:s.operation}});return"string"==typeof n.data?JSON.parse(n.data):n.data}buildPrecheckedUploadResult(t,s,n){if(!this.config||!s.precheck)throw new k("Precheck result is required",{code:e.UPLOAD_REQUEST_FAILED});if(!s.precheck.uuid)throw new k("Precheck hit missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{precheck:s.precheck}});if(!Gc(t.type))throw new k("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const{orgName:r,appName:i}=P(this.config.appKey),o="image"===t.type?s.precheck.existsType??s.imageType:void 0,a="image"===t.type&&o===l?s.md5FileInfo:s.fileInfo,c="image"===t.type&&o===l?s.originalWidth:"image"===t.type?s.body.width:void 0,d="image"===t.type&&o===l?s.originalHeight:"image"===t.type?s.body.height:void 0,u={entities:[{uuid:s.precheck.uuid,...s.precheck.shareSecret?{"share-secret":s.precheck.shareSecret}:{}}]},h=q({response:u,restBaseUrl:this.config.restBaseUrl,orgName:r,appName:i,fileType:a.fileType,fileName:a.fileName,fallbackSize:a.fileSize,messageType:t.type,imageType:o,width:c,height:d,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(h),h}async uploadAttachment(t,s,n,r){if(!this.config)throw new k("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});if(!Gc(t.type))throw new k("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const i=t.type,o=await this.resolveUploadMetadata(i,s);if(!s.fileInfo.webFile){if(this.config.uploadAdapter)return this.uploadByAdapter(this.config.uploadAdapter,t,s,o,n);throw new k("Upload adapter is required for non-web file source",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:s.fileInfo.source.sourceType}})}const c={message:t,file:s.fileInfo.webFile,conversationId:t.conversationId,conversationType:t.conversationType,messageType:i,imageType:s.imageType,md5:o.md5,width:o.width,height:o.height,fileName:s.fileInfo.fileName,fileType:s.fileInfo.fileType,fileSize:s.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(i,s.body),thumbnailHeight:this.resolveThumbnailHeight(i,s.body),callbacks:n,config:this.config,dataReportOperation:r},d=!1!==this.config?.enableMultipartUpload,l=d&&s.fileInfo.fileSize>O;if(a.warn("Attachment web upload selected",{operation:"upload.web.selected",messageType:i,source:Kc(s.fileInfo),multipartEnabled:d,uploadMode:l?"multipart":"simple"}),l)try{return await Pc(c)}catch(u){const e=u instanceof k?u.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return xc(c);throw u}return this.config.uploadAdapter?(a.warn("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:i,source:Kc(s.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,t,s,o,n)):xc(c)}async uploadByAdapter(t,s,n,r,i){if(!this.config)throw new k("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:o,appName:c}=P(this.config.appKey),d=V(s.conversationType);if(!Gc(s.type))throw new k("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:s.type}});const l=s.type,u=F(`${this.config.restBaseUrl}/${o}/${c}/chatfiles`,{"chat-type":d,"chat-target":s.conversationId,md5:r.md5,..."image"===l?{imageType:B(n.imageType),width:r.width,height:r.height}:{}}),p={},m={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[_]:h()},f=this.resolveThumbnailWidth(l,n.body),g=this.resolveThumbnailHeight(l,n.body);void 0!==f&&(p["thumbnail-width"]=String(f)),void 0!==g&&(p["thumbnail-height"]=String(g)),a.warn("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:l,source:Kc(n.fileInfo),uploadUrl:u,fields:p});const y=await t.upload({url:u,headers:m,source:n.fileInfo.source,fields:p,onProgress:e=>{i?.onFileUploadProgress?.(e)}});if(y.status>=400){const t=y.body??"",s=413===y.status?e.FILE_TOO_LARGE:"string"==typeof t&&t.includes("content improper")?e.FILE_CONTENT_IMPROPER:e.UPLOAD_REQUEST_FAILED;throw new k("Upload failed",{code:s,details:{status:y.status,response:y.body}})}let I;try{I=JSON.parse(y.body)}catch(C){throw new k("Upload response parse failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:y.body,cause:C instanceof Error?C.message:String(C)}})}const v=q({response:I,restBaseUrl:this.config.restBaseUrl,orgName:o,appName:c,fileType:n.fileInfo.fileType,fileName:n.fileInfo.fileName,fallbackSize:n.fileInfo.fileSize,messageType:l,imageType:n.imageType,width:r.width,height:r.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return i?.onFileUploadComplete?.(v),v}buildPreparedMessage(e,t,s){if("image"===e.type){const n=t.body,r={...e,body:{...n,isOriginalImage:s.isOriginalImage??n.isOriginalImage,originalImageUrl:s.originalImageUrl??n.originalImageUrl,bigImageUrl:s.bigImageUrl??n.bigImageUrl,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename,thumbnailUrl:s.thumbnailUrl??n.thumbnailUrl,width:s.width??n.width,height:s.height??n.height}};return Fo(e,r),$e(e,r),r}if("video"===e.type){const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename,thumbnailUrl:s.thumbnailUrl??n.thumbnailUrl}};return Fo(e,r),r}if("voice"===e.type){const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename}};return Fo(e,r),r}if("combine"===e.type){const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename}};return Fo(e,r),r}const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename}};return Fo(e,r),r}resolveThumbnailWidth(e,t){if("video"===e){const e="width"in t?t.width:void 0;return"number"==typeof e&&e>0?e:void 0}}resolveThumbnailHeight(e,t){if("video"===e){const e="height"in t?t.height:void 0;return"number"==typeof e&&e>0?e:void 0}}async resolveUploadMetadata(e,t){let s=t.precheck?.md5??"";if(!t.precheck)try{s=await this.computeMd5(t.md5FileInfo)}catch(r){if(!Hc(t.md5FileInfo.source.sourceType,r))throw r;a.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Kc(t.md5FileInfo),error:r instanceof Error?r.message:String(r)})}const n=t.body;return{md5:s,width:"image"===e&&"number"==typeof n.width&&n.width>0?n.width:void 0,height:"image"===e&&"number"==typeof n.height&&n.height>0?n.height:void 0}}}class jc{constructor(e,t){this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null,this.runtime=e,this.handlers=t}start(){this.unsubscribeNetwork||this.unsubscribeVisibility||(this.unsubscribeNetwork=this.runtime.onNetworkChange(e=>{this.handleNetworkChange(e)}),this.unsubscribeVisibility=this.runtime.onAppVisibilityChange(e=>{this.handleVisibilityChange(e)}))}stop(){this.unsubscribeNetwork?.(),this.unsubscribeVisibility?.(),this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null}handleNetworkChange(e){this.lastOnline!==e&&(this.lastOnline=e,e?this.handlers.onOnline():this.handlers.onOffline())}handleVisibilityChange(e){this.lastForeground!==e&&(this.lastForeground=e,e?this.handlers.onForeground():this.handlers.onBackground())}}const Wc="__internal:core";class Qc{constructor(e,t){this.runtimeEventBridge=null,this.handleOnline=()=>{this.connectionManager.handleOnline()},this.handleOffline=()=>{this.connectionManager.handleOffline()},this.handleForegroundChange=e=>{e&&this.connectionManager.handleForeground()},this.eventHub=t,this.connectionManager=new ac({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),n=e.restBaseUrl?new zc({restBaseUrl:e.restBaseUrl,token:e.token,appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,enableMultipartUpload:e.enableMultipartUpload,requestAdapter:e.platformAdapter?.request,uploadAdapter:e.platformAdapter?.upload,imageProcessor:e.platformAdapter?.imageProcessor}):void 0;this.messageSender=new Ec(s,null,this.eventHub,n),this.messageReceiver=new Nc(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Rc(e.platformAdapter?.request),this.attachmentDownloader=new Uc(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Wc,{[qe.CONNECTED]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[qe.DISCONNECTED]:e=>{this.messageSender.setWebSocket(null)},[qe.RECONNECT_FAILED]:e=>{this.messageSender.setWebSocket(null)},[Ge.MESSAGE_SENT]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new jc(e,{onOnline:this.handleOnline,onOffline:this.handleOffline,onForeground:()=>{this.handleForegroundChange(!0)},onBackground:()=>{this.handleForegroundChange(!1)}}),this.runtimeEventBridge.start()}unregisterNetworkListeners(){this.runtimeEventBridge?.stop(),this.runtimeEventBridge=null}resolveRuntimeAdapter(){return this.platformAdapter?this.platformAdapter.runtime:this.createBrowserRuntimeAdapter()}createBrowserRuntimeAdapter(){return{getPlatform:()=>"web",onNetworkChange(e){if("undefined"==typeof window)return()=>{};const t=()=>{e(!0)},s=()=>{e(!1)};return window.addEventListener("online",t),window.addEventListener("offline",s),"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine&&e(navigator.onLine),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}},onAppVisibilityChange(e){if("undefined"==typeof document)return()=>{};const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),t(),()=>{document.removeEventListener("visibilitychange",t)}}}}async connect(e){return this.connectionManager.connect(e)}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}recoverConnectionForSend(){return this.connectionManager.recoverConnectionForSend()}getClientResource(){return this.connectionManager.getClientResource()}renewToken(e,t){const s=this.connectionManager.renewToken(e,t);return this.messageSender.updateAuthToken(e),s}async sendMessage(e,t){return this.messageSender.sendMessage(e,t)}async sendMessageAction(e,t){return this.messageSender.sendAction(e,t)}async sendChatRoomOperation(e,t){return this.messageSender.sendChatRoomOperation(e,t)}async downloadAndParseCombineMessage(e){return this.combineMessageDownloader.downloadAndParse(e)}async downloadAttachment(e,t){return this.attachmentDownloader.download(e,t)}decodeServerMessageMeta(e){return this.connectionManager.getMsyncCodec().decodeServerMessageMeta(e)}destroy(){this.unregisterNetworkListeners(),this.connectionManager.destroy(),this.messageSender.destroy(),this.messageReceiver.destroy(),this.eventHub.removeEventHandler(Wc),Qe.clear()}}const $c=e=>{if("singleChat"!==e.conversationType)return e.conversationId;const t=e.to||("SEND"===e.direct?e.conversationId:"RECEIVE"===e.direct?e.currentUserId:e.from?e.from===e.currentUserId?e.conversationId:e.currentUserId:""),s=t.indexOf("/");return s<0?t:t.slice(0,s)},Yc=e=>{if(e.length>=1048576){const t=[],s=32768;for(let n=0;n<e.length;n+=s)t.push(String.fromCharCode(...e.subarray(n,n+s)));return btoa(t.join(""))}let t="";for(let s=0;s<e.length;s+=1){const n=e[s];void 0!==n&&(t+=String.fromCharCode(n))}return btoa(t)},Jc=e=>{const t=new Uint8Array(ot.util.base64.length(e));return ot.util.base64.decode(e,t,0),t};class Xc{getCrypto(){return t().crypto}constructor(e,n){if(this.enabled=(()=>{const e=t();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const n=Jn(e);if("web"!==n.framework&&"worker"!==n.framework&&n.platform!==s.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const t=`${e}:${n}`;this.keyPromise=this.deriveKey(t)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,s=new TextEncoder,n=this.getCrypto().getRandomValues(new Uint8Array(12)),r=s.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:n},t,r),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:Yc(n),ct:Yc(new Uint8Array(i))};return JSON.stringify(o)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,s=Jc(t.iv),n=Jc(t.ct),r=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:s},e,n);return(new TextDecoder).decode(r)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),s=this.getCrypto(),n=await s.subtle.digest("SHA-256",t);return s.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const Zc="conversationMap",ed="userInfoMap",td="groupNamecardMap",sd="contactRelationMap",nd="contactVersion",rd="contactMeta",id="sessionListMap",od="sessionListCheckpoint",ad="joinedGroupPreview",cd="metadata",dd=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class ld{constructor(e,t,s){this.store=e,this.key=t,this.schemaVersion=s}async load(){const e={schemaVersion:this.schemaVersion,lastFlush:0},t=await this.store.readAsync(this.key,e);return t.schemaVersion!==this.schemaVersion?e:t}async save(e){await this.store.writeAsync(this.key,e)}async touchLastFlush(){const e={schemaVersion:this.schemaVersion,lastFlush:Date.now()};return await this.save(e),e}}const ud=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const s=t().localStorage;return s&&"function"==typeof s.getItem?s:null};class hd{constructor(e,t){this.storage=t??hd.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!hd.checkAvailable())return null;const e=ud();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,s)=>(e.setItem(t,s),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=ud();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const s=await this.storage.getItem(e);if(!s)return t;let n=s;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(s);if(null===e)return t;n=e}return Tt(n,t)}catch(s){return a.warn("CacheStore read failed",s),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,s){if(!this.storage)return;const n=At(t);if(null!==n)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(n):n;await this.storage.setItem(e,t)}catch(r){if(ti(r))throw r;if(s)throw r;a.warn("CacheStore write failed",r)}else if(s)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){a.warn("CacheStore remove failed",t)}}}const pd={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},md={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class fd{constructor(){this.items=/* @__PURE__ */new Map,this.versionState=pd,this.meta=md}load(e,t,s){this.items.clear();for(const n of e){const e=this.normalizeRecord(n);e&&this.items.set(e.userId,e)}this.versionState=this.normalizeVersionState(t),this.meta=this.normalizeMeta(s)}getAll(){return Array.from(this.items.values()).sort((e,t)=>e.addTs!==t.addTs?e.addTs-t.addTs:e.userId.localeCompare(t.userId))}getVersionState(){return this.versionState}getMeta(){return this.meta}getUserIds(){return Array.from(this.items.keys())}replaceAll(e){this.items.clear(),this.upsert(e)}upsert(e){for(const t of e){const e=this.normalizeRecord(t);e&&this.items.set(e.userId,e)}}addByNotice(e,t){const s=e.trim();return!!s&&(!this.items.has(s)&&(this.items.set(s,{userId:s,remark:"",sign:"",addTs:t,updatedAt:t,metadataUpdatedAt:t}),!0))}remove(e){return this.items.delete(e)}updateRemark(e,t,s){const n=this.items.get(e);return!(!n||n.remark===t)&&(this.items.set(e,{...n,remark:t,updatedAt:s}),!0)}setVersionState(e){this.versionState=this.normalizeVersionState(e)}updateVersionFromNotice(e,t){const s=e.trim();return!!s&&((this.versionState.version!==s||"roster_notice"!==this.versionState.lastVersionSource)&&(this.versionState={version:s,lastVersionCheckAt:t,lastVersionSource:"roster_notice"},!0))}setMeta(e){this.meta=this.normalizeMeta(e)}updateMeta(e){this.meta={cacheIntegrity:e.cacheIntegrity,reason:"complete"===e.cacheIntegrity?void 0:e.reason,lastSyncTs:e.lastSyncTs??this.meta.lastSyncTs,lastSuccessfulVersion:e.lastSuccessfulVersion??this.meta.lastSuccessfulVersion,lastSyncMode:e.lastSyncMode??this.meta.lastSyncMode}}computeIntegrity(e){if(0===this.items.size&&!this.meta.lastSuccessfulVersion)return{...this.meta,cacheIntegrity:"incomplete",reason:"first_sync_pending"};const t=new Set(e.map(e=>e.userId));return this.getUserIds().some(e=>!t.has(e))?{...this.meta,cacheIntegrity:"incomplete",reason:"user_info_missing"}:{...this.meta,cacheIntegrity:"complete",reason:void 0}}buildSnapshot(e,t){const s=new Map(e.map(e=>[e.userId,e])),n=this.getAll().map(e=>{const t=s.get(e.userId);return{userId:e.userId,userInfo:{userId:e.userId,nickname:t?.nickname,avatarUrl:t?.avatarUrl,sign:t?.sign??e.sign,ext:t?.ext},remark:e.remark,addTs:e.addTs}}),r="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:n,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:r}}normalizeRecord(e){if(!wt(e))return null;const t="string"==typeof e.userId?e.userId:"";return t?{userId:t,remark:"string"==typeof e.remark?e.remark:"",sign:"string"==typeof e.sign?e.sign:"",addTs:"number"==typeof e.addTs?e.addTs:0,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:0,metadataUpdatedAt:"number"==typeof e.metadataUpdatedAt?e.metadataUpdatedAt:0}:null}normalizeVersionState(e){return wt(e)?{version:"string"==typeof e.version?e.version:"",lastVersionCheckAt:"number"==typeof e.lastVersionCheckAt?e.lastVersionCheckAt:0,lastVersionSource:"metadata"===e.lastVersionSource||"sync_page"===e.lastVersionSource||"roster_notice"===e.lastVersionSource?e.lastVersionSource:"metadata"}:pd}normalizeMeta(e){return wt(e)?{cacheIntegrity:"complete"===e.cacheIntegrity?"complete":"incomplete",reason:"quota_exceeded"===e.reason||"user_info_missing"===e.reason||"corrupted"===e.reason||"manual_reset"===e.reason||"first_sync_pending"===e.reason?e.reason:void 0,lastSyncTs:"number"==typeof e.lastSyncTs?e.lastSyncTs:0,lastSuccessfulVersion:"string"==typeof e.lastSuccessfulVersion?e.lastSuccessfulVersion:"",lastSyncMode:"full"===e.lastSyncMode||"incremental"===e.lastSyncMode||"skipped"===e.lastSyncMode?e.lastSyncMode:"skipped"}:md}}const gd=(e,t,s)=>{if(t<=0)return{kept:e,removed:[]};const n=[],r=[];for(const i of e)s-i.lastUpdate>t?r.push(i):n.push(i);return{kept:n,removed:r}},yd=(e,t)=>{if(t<=0||0===e.length)return{kept:e,removed:[]};const s=[...e].sort((e,t)=>e.lastAccess-t.lastAccess).slice(0,t),n=new Set(s);return{kept:e.filter(e=>!n.has(e)),removed:s}},Id=e=>{if(!Array.isArray(e))return[];const t=/* @__PURE__ */new Set,s=[],n=e;for(const r of n){const e="string"==typeof r&&r.startsWith("mark_")?r.slice(5):r,n="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(n)||n<0||n>19)continue;const i=n;t.has(i)||(t.add(i),s.push(i))}return s};class vd{constructor(){this.items=[]}load(e,t){const s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s}getAll(){return this.items}setAll(e){this.items=[...e]}updateLastAccess(e,t){if(0===e.length)return!1;let s=!1;for(const n of e){const e=this.findIndex(n.conversationId,n.type);if(e<0)continue;const r=this.items[e];r&&(r.lastAccess!==t&&(this.items[e]={...r,lastAccess:t},s=!0))}return s}removeExpired(e,t){const s=gd(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=yd(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),s=Math.max(this.items.length-e,0),n=t.slice(0,s),r=new Set(n);return this.items=this.items.filter(e=>!r.has(e)),n.length>0}findIndex(e,t){return this.items.findIndex(s=>s.conversationId===e&&s.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const s=e;if("string"!=typeof s.conversationId||0===s.conversationId.length)return null;const n="single"===(r=s.type)||"chat"===r||"singleChat"===r?"singleChat":"group"===r||"groupchat"===r||"groupChat"===r?"groupChat":"room"===r||"chatroom"===r||"chatRoom"===r?"chatRoom":null;var r;if(!n)return null;const i=this.normalizeMessage(s.lastMessage);return{conversationId:s.conversationId,type:n,lastMessage:i,unreadCount:"number"==typeof s.unreadCount?s.unreadCount:0,isPinned:"boolean"==typeof s.isPinned?s.isPinned:void 0,pinnedTime:"number"==typeof s.pinnedTime?s.pinnedTime:void 0,marks:Id(s.marks),lastAccess:"number"==typeof s.lastAccess?s.lastAccess:0,lastUpdate:"number"==typeof s.lastUpdate?s.lastUpdate:t}}normalizeMessage(e){if(!e||"object"!=typeof e)return null;if(!wt(e))return null;const t="string"==typeof e.msgId?e.msgId:"",s="string"==typeof e.type?e.type:"",n="number"==typeof e.timestamp?e.timestamp:0,r=wt(e.body)?e.body:{};return t?{...Ct(e),msgId:t,from:"string"==typeof e.from?e.from:void 0,to:"string"==typeof e.to?e.to:void 0,sender:wt(e.sender)&&"string"==typeof e.sender.userId?{userId:e.sender.userId,nickname:"string"==typeof e.sender.nickname?e.sender.nickname:void 0,avatarUrl:"string"==typeof e.sender.avatarUrl?e.sender.avatarUrl:void 0}:void 0,type:s,body:vt(r),ext:wt(e.ext)?e.ext:void 0,timestamp:n}:null}}const Cd=(e,t)=>`${e}:${t}`;class Sd{constructor(){this.items=/* @__PURE__ */new Map}load(e,t){this.items.clear();for(const s of e){const e=this.normalizeItem(s,t);e&&this.items.set(Cd(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,n){const r=Cd(e,t),i=this.items.get(r);return i?(n&&this.items.set(r,{...i,lastAccess:s}),i):null}getByGroupId(e,t,s){const n=[];for(const r of this.items.values())r.groupId===e&&(n.push(r),s&&this.items.set(Cd(r.groupId,r.userId),{...r,lastAccess:t}));return n}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const n=Cd(e.groupId,e.userId),r=this.items.get(n);this.items.set(n,{...e,lastAccess:r?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(Cd(t.groupId,t.userId))}removeExpired(e,t,s=/* @__PURE__ */new Set){const n=Array.from(this.items.values()),r=n.filter(e=>!s.has(e.userId)),i=gd(r,e,t),o=new Set(i.removed.map(e=>Cd(e.groupId,e.userId)));this.items.clear();for(const a of n)o.has(Cd(a.groupId,a.userId))||this.items.set(Cd(a.groupId,a.userId),a);return i.removed.length>0}evictByLru(e,t=/* @__PURE__ */new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!t.has(e.userId)),r=yd(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>Cd(e.groupId,e.userId)));this.items.clear();for(const o of s)i.has(Cd(o.groupId,o.userId))||this.items.set(Cd(o.groupId,o.userId),o);return r.removed.length>0}trimMax(e,t=/* @__PURE__ */new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!wt(e))return null;const s="string"==typeof e.groupId?e.groupId:"",n="string"==typeof e.userId?e.userId:"";if(!s||!n)return null;return{groupId:s,userId:n,namecard:"string"==typeof e.namecard?e.namecard:"",namecardUpdateTime:"number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Ed=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,bd=e=>{if(!wt(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!wt(e.body))return null;const s=((e,t)=>{if(wt(e)&&"string"==typeof e.userId){const t={userId:e.userId};return"string"==typeof e.nickname&&(t.nickname=e.nickname),"string"==typeof e.avatarUrl&&(t.avatarUrl=e.avatarUrl),t}return t?{userId:t}:null})(e.sender,e.from);if(!s)return null;const n=Ed(e.conversationType);return{...Ct({...e,sendStatus:e.sendStatus??e.status}),msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:s,body:vt(e.body),ext:wt(e.ext)?e.ext:{},timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...n?{conversationType:n}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{}}},Td=e=>{if(!Array.isArray(e))return[];const t=/* @__PURE__ */new Set,s=[],n=e;for(const r of n){const e="string"==typeof r&&r.startsWith("mark_")?r.slice(5):r,n="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(n)||n<0||n>19)continue;const i=n;t.has(i)||(t.add(i),s.push(i))}return s},Ad=(e,t)=>{const s="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,n="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(s!==n)return n-s;const r=e.lastMessageAt??e.updatedAt,i=t.lastMessageAt??t.updatedAt;return r!==i?i-r:e.conversationId.localeCompare(t.conversationId)};class wd{constructor(){this.items=[]}load(e,t){const s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s.sort(Ad)}getAll(){return this.items}setAll(e){const t=Date.now(),s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s.sort(Ad)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!wt(e))return null;const s=e,n="string"==typeof s.conversationId?s.conversationId:"";if(!n)return null;const r=Ed(s.conversationType);if(!r)return null;const i="string"==typeof s.conversationName&&s.conversationName.length>0?s.conversationName:n,o="string"==typeof s.conversationAvatar?s.conversationAvatar:void 0;return{conversationId:n,conversationType:r,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:bd(e.lastMessage),lastMessageAt:"number"==typeof e.lastMessageAt?e.lastMessageAt:void 0,isPinned:"boolean"==typeof e.isPinned?e.isPinned:void 0,pinnedTimestamp:"number"==typeof s.pinnedTimestamp?s.pinnedTimestamp:void 0,marks:Td(e.marks),readAt:"number"==typeof s.readAt?s.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class Nd{constructor(){this.items=/* @__PURE__ */new Map}load(e,t){this.items.clear();for(const s of e){const e=this.normalizeItem(s,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,s){const n=[];for(const r of e){const e=this.items.get(r);e&&(n.push(e),s&&this.items.set(r,{...e,lastAccess:t}))}return n}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const n=this.items.get(e.userId),r=n?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:r,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,s=/* @__PURE__ */new Set){const n=Array.from(this.items.values()),r=n.filter(e=>!s.has(e.userId)),i=gd(r,e,t),o=new Set(i.removed.map(e=>e.userId));this.items.clear();for(const a of n)o.has(a.userId)||this.items.set(a.userId,a);return i.removed.length>0}evictByLru(e,t=/* @__PURE__ */new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!t.has(e.userId)),r=yd(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>e.userId));this.items.clear();for(const o of s)i.has(o.userId)||this.items.set(o.userId,o);return r.removed.length>0}trimMax(e,t=/* @__PURE__ */new Set){if(e<=0||this.items.size<=e)return!1;const s=Array.from(this.items.values()),n=Math.max(s.length-e,0);return this.evictByLru(n,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!wt(e))return null;const s="string"==typeof e.userId?e.userId:"";if(!s)return null;return{userId:s,nickname:"string"==typeof e.nickname?e.nickname:void 0,avatarUrl:"string"==typeof e.avatarUrl?e.avatarUrl:void 0,sign:"string"==typeof e.sign?e.sign:void 0,ext:"string"==typeof e.ext?e.ext:void 0,userInfoUpdateTime:"number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Md=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Rd=e=>e.lastMessageAt??e.updatedAt,_d=e=>[...e].sort((e,t)=>{const s=Md(t)-Md(e);if(0!==s)return s;const n=Rd(t)-Rd(e);return 0!==n?n:e.conversationId.localeCompare(t.conversationId)}),Dd=e=>`${e.conversationType}:${e.conversationId}`,Ud=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Ld=(e,t)=>((e,t)=>Rd(t)>Rd(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Ud(e,t),lastMessageAt:Math.max(e.lastMessageAt??0,t.lastMessageAt??0),isPinned:t.isPinned??e.isPinned,pinnedTimestamp:"number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:e.pinnedTimestamp,marks:t.marks.length>0?t.marks:e.marks,readAt:t.readAt??e.readAt,remindType:t.remindType??e.remindType,conversationName:t.conversationName===t.conversationId?e.conversationName:t.conversationName,conversationAvatar:t.conversationAvatar??e.conversationAvatar,updatedAt:Math.max(e.updatedAt,t.updatedAt)}:e,Od=e=>{const t=/* @__PURE__ */new Map,s=/* @__PURE__ */new Set;for(const i of e.snapshot)s.add(Dd(i));for(const i of e.existing)t.set(Dd(i),i);const n=e.snapshot.map(e=>{const s=t.get(Dd(e));return s?Ld(e,s):e}),r=e.existing.filter(t=>!s.has(Dd(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return _d([...n,...r])},kd=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Pd=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),xd=e=>({userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,lastAccess:e.lastAccess,lastUpdate:e.lastModified});class Fd{constructor(){this.records=/* @__PURE__ */new Map}clear(){this.records.clear()}get(e,t=!1,s=Date.now()){const n=this.records.get(e)??null;if(!n||!t)return n;const r={...n,lastAccess:s};return this.records.set(e,r),r}setAll(e,t=Date.now()){for(const s of e){const e=s.lastModified??t,n=this.records.get(s.profile.userId),r=n?.lastAccess??t;this.records.set(s.profile.userId,{profile:s.profile,lastModified:e,lastAccess:r,source:s.source})}}applyPatch(e,t,s=Date.now()){const n=this.records.get(e.userId),r={userId:e.userId,...t??{},...n?.profile??{}};if(n&&e.lastModified<n.lastModified)return{applied:!1,reason:"stale",record:n};const i={...r,...e.attributes,userId:e.userId};if(n&&e.lastModified===n.lastModified&&(o=n.profile,a=i,kd.every(e=>o[e]===a[e])))return{applied:!1,reason:"duplicate",record:n};var o,a;const c={profile:i,lastModified:e.lastModified,lastAccess:n?.lastAccess??s,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const Bd=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class qd{constructor(e){this.conversationDeletionTimestamps=/* @__PURE__ */new Map,this.currentConversation=null,this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.flushTimer=null,this.flushIdleHandle=null,this.activeFlushPromise=null,this.sessionListCommitInProgress=!1,this.mutationRevision=0,this.domainRevisions=/* @__PURE__ */new Map,this.pendingDirtyRevisions=/* @__PURE__ */new Map,this.userId=e.userId,this.config={schemaVersion:1,ttlSeconds:86400,flushIntervalMs:1e3,maxUserInfoCount:1e3,maxGroupNamecardCount:1e3,maxConversations:e.config?.maxConversations,...e.config};const t="off"===e.cacheEncryptionMode?null:new Xc(e.appKey,e.userId);this.store=new hd(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=dd(s,Zc),this.userInfoKey=dd(s,ed),this.groupNamecardKey=dd(s,td),this.sessionListKey=dd(s,id),this.sessionListCheckpointKey=dd(s,od),this.joinedGroupPreviewKey=dd(s,ad),this.contactRelationKey=dd(s,sd),this.contactVersionKey=dd(s,nd),this.contactMetaKey=dd(s,rd),this.metadataKey=dd(s,cd),this.metadataStore=new ld(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new vd,this.userInfoCache=new Nd,this.groupNamecardCache=new Sd,this.sessionListCache=new wd,this.joinedGroupPreviewCache=new mt,this.contactCache=new fd,this.userInfoRuntimeStore=new Fd,this.loadPromise=this.loadFromStorage()}getConfig(){return this.config}async prepare(){await this.loadPromise}loadConversationSummaries(){return this.conversationCache.getAll()}loadSessionList(){return this.sessionListCache.exportItems()}loadJoinedGroupPreviewSnapshot(){return this.joinedGroupPreviewCache.getSnapshot()}applyJoinedGroupPreviewSnapshot(e){this.joinedGroupPreviewCache.setSnapshot(e),this.scheduleFlush(["joinedGroupPreview"])}async commitJoinedGroupPreviewSnapshot(e){this.activeFlushPromise&&await this.activeFlushPromise;const t=this.getDomainRevision("joinedGroupPreview"),s=new mt;if(s.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,s.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const n=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==n&&n<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),s=t.items.filter(t=>t.groupId!==e);return s.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:s,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let s=!1,n=!1;const r=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:(s=!0,0===r.unreadCount?r:(n=!0,{...r,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(n=>n.conversationId!==e.conversationId||n.conversationType!==e.type?n:(s=!0,0===n.unreadCount&&n.readAt===t?n:(i=!0,{...n,unreadCount:0,readAt:t,updatedAt:t})));return n||i?(n&&this.conversationCache.setAll(r),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:s}):{items:this.sessionListCache.exportItems(),changed:!1,matched:s}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),s=this.conversationCache.getAll(),n=s.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),r=this.sessionListCache.getAll(),i=r.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(s,n),a=!this.isSessionListEqual(r,i);return o||a?(o&&this.conversationCache.setAll(n),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),s=this.conversationCache.getAll(),n=this.conversationCache.getAll().map(s=>s.conversationId!==e.conversationId||s.type!==e.type?s:{...s,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),r=this.sessionListCache.getAll(),i=r.map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:{...s,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(s,n),a=!this.isSessionListEqual(r,i);return o||a?(o&&this.conversationCache.setAll(n),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),s=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,s,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),s=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(s,e.deletedAt))}const n=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),r=s.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=n.length!==t.length,o=r.length!==s.length;return i||o?(i&&this.conversationCache.setAll(n),o&&this.sessionListCache.setAll(r),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),r=this.conversationCache.getAll(),i=r.map(e=>{const r=`${e.type}:${e.conversationId}`;if(!t.has(r))return e;const i=n(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:s}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const r=`${e.conversationType}:${e.conversationId}`;if(!t.has(r))return e;const i=n(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:s}}),c=!this.isConversationListEqual(r,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,s){const n=Date.now(),r=e.map(e=>({...e,updatedAt:e.lastMessageAt??n})),i=Od({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:s?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(i,n)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],s=this.getDomainRevision("sessionList");try{let n=!1;for(;!n;){const r=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),s=this.getDomainRevision("sessionList"),s===r&&(n=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const r=this.pendingDirtyRevisions.get("sessionList");return void 0!==r&&r<=s&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],s=t?Pd(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([xd(t)])}getUserInfoSummaries(e,t){const s=Date.now(),n=this.userInfoCache.getByIds(e,s,t);return t&&this.scheduleFlush(["userInfo"]),n}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,s){const n=this.groupNamecardCache.get(e,t,Date.now(),s);return s&&n&&this.scheduleFlush(["groupNamecard"]),n}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),s=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:s,lastUpdate:s})),s),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:s,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const n=this.loadContactSnapshot("sync");return{snapshot:n,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(n)}}refreshSessionListDisplayFromUserInfos(e){const t=/* @__PURE__ */new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.loadContactSnapshot("cache").items,r=new Map(n.map(e=>[e.userId,e])),i=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),o=this.sessionListCache.getAll().map(e=>{let n=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,i)){const t=r.get(e.conversationId),o=this.resolveSessionDisplayUserInfo(e.conversationId,i),a=this.buildSingleSessionDisplayFields(e.conversationId,t,o,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(n={...n,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:s})}const o=n.lastMessage;if(o&&!this.shouldSkipSessionUserDisplayRefresh(o.sender.userId,t,i)){const e=r.get(o.sender.userId),t=this.resolveSessionDisplayUserInfo(o.sender.userId,i),a=this.buildSessionMessageSender(o.sender.userId,o.sender,e,t);this.isSenderEqual(o.sender,a)||(n={...n,lastMessage:{...o,sender:a},updatedAt:s})}return n}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,o);return c&&(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const s=/* @__PURE__ */new Map;for(const a of e){const e=a.groupId.trim();e&&s.set(e,a)}if(0===s.size)return{items:this.sessionListCache.exportItems(),changed:!1};const n=Date.now(),r=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const r=s.get(e.conversationId);if(!r)return e;const i=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&i)return e;const o=r.name?.trim(),a=o||e.conversationName,c=r.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(r.remindType),l=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||l?{...e,conversationName:a,conversationAvatar:c,remindType:l?d:e.remindType,updatedAt:n}:e}),i=this.sessionListCache.getAll(),o=!this.isSessionListEqual(i,r);return o&&(this.sessionListCache.setAll(r),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:o}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),s=Date.now(),n="add"===e.action?this.contactCache.addByNotice(e.userId,s):this.contactCache.remove(e.userId),r="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,s);(n||r)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const i=this.loadContactSnapshot("cache");return{snapshot:i,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(i)}}updateConversationsFromServer(e,t){const s=Date.now(),n=this.conversationCache.getAll(),r=this.mergeConversationLists(n,e,s,t?.syncStartedAt),i=!this.isConversationListEqual(n,r);return this.conversationCache.setAll(r),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:r,changed:i}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const s=Date.now(),n=this.conversationCache.getAll(),r=n.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),i=r>=0?n[r]:void 0,o=this.buildConversationFromMessage(e,i,s);if(!o)return{items:n,changed:!1};const a=[o,...n.filter((e,t)=>t!==r)];return this.isConversationListEqual(n,a)?{items:n,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}patchConversationLastMessage(e){const t=this.patchConversationLastMessages([e]);return{items:this.loadSessionList(),changed:t}}patchConversationLastMessages(e){const t=(e,t,s)=>JSON.stringify([t,e,s]),s=/* @__PURE__ */new Map;for(const h of e){if(!h.messageId||!h.patch)continue;const e=t(h.conversationId,h.conversationType,h.messageId),n=s.get(e)??[];n.push(h.patch),s.set(e,n)}if(!s.size)return!1;const n=/* @__PURE__ */new Map,r=e=>{const t=n.get(e);if(t)return t;const r=s.get(e);if(!r)return;const i=r.map(e=>({...Ct(e),...e.type?{type:e.type}:{},...e.body?{body:vt(e.body)}:{},...e.ext?{ext:e.ext}:{},...Object.prototype.hasOwnProperty.call(e,"chatThreadOverview")&&void 0===e.chatThreadOverview?{chatThreadOverview:void 0}:{}}));return n.set(e,i),i},i=(e,t)=>{let s=e;for(const n of t)n.modifiedInfo&&s.modifiedInfo&&n.modifiedInfo.operationCount<s.modifiedInfo.operationCount||(s={...s,...n,...void 0!==n.groupReadCount?{groupReadCount:Math.max(s.groupReadCount??0,n.groupReadCount)}:{}});return St(e)===St(s)?e:s},o=this.conversationCache.getAll();let a=!1;const c=o.map(e=>{if(!e.lastMessage)return e;const s=r(t(e.conversationId,e.type,e.lastMessage.msgId));if(!s)return e;const n=i(e.lastMessage,s);return n===e.lastMessage?e:(a=!0,{...e,lastMessage:n})}),d=this.sessionListCache.getAll();let l=!1;const u=d.map(e=>{if(!e.lastMessage)return e;const s=r(t(e.conversationId,e.conversationType,e.lastMessage.msgServerId));if(!s)return e;const n=i(e.lastMessage,s);return n===e.lastMessage?e:(l=!0,{...e,lastMessage:n})});return a&&(this.conversationCache.setAll(c),this.scheduleFlush(["conversation"])),l&&(this.sessionListCache.setAll(u),this.scheduleFlush(["sessionList"])),a||l}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const s=this.sessionListCache.getAll(),n=s.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),r=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!r)return{items:this.sessionListCache.exportItems(),changed:!1};const i=(e=>{const t=Dd(e.nextRecord),s=e.existing.filter(e=>Dd(e)!==t);return _d([e.nextRecord,...s])})({existing:s,nextRecord:this.buildSessionListRecordFromConversation(r,e,n,Date.now())});return this.isSessionListEqual(s,i)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const s=await this.readDump(this.userInfoKey);this.userInfoCache.load(s,e);const n=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(n,e);const r=await this.readValue(this.sessionListKey,null),i=r&&wt(r)&&Array.isArray(r.items)?r.items:[];this.sessionListCache.load(i,e);const o=(r&&wt(r)&&wt(r.checkpoint)?r.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(o);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),l=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,l),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&wt(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&wt(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=/* @__PURE__ */new Map,e}restoreDirtyBatch(e){for(const[t,s]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(s,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(/* @__PURE__ */new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const n=6;for(let r=0;r<=n;r+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!ti(t))return this.restoreDirtyBatch(e),void a.warn("Cache flush failed",t);const n=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,n),"none"===n)return void a.warn("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(n)}catch(s){if(!ti(s))return this.restoreDirtyBatch(e),void a.warn("Cache quota cleanup persistence failed",s)}}a.warn("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of Bd)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,s=!1){const n={items:e,checkpoint:t};s?await this.store.writeStrictAsync(this.sessionListKey,n):await this.store.writeAsync(this.sessionListKey,n),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),s=/* @__PURE__ */new Map;for(const r of t)s.set(`${r.conversationType}:${r.conversationId}`,r);const n=Date.now();return(e=>{const t=e.incoming.filter(e=>Md(e)>0),s=/* @__PURE__ */new Map;for(const r of e.incoming)s.set(Dd(r),r);const n=t.length>0?e.existing.filter(e=>!s.has(Dd(e))&&0===Md(e)):e.existing.filter(e=>!s.has(Dd(e)));return _d([...n,...e.incoming])})({existing:t,incoming:this.filterItemsAgainstConversationDeletions(e).map(e=>{const t=`${e.conversationType}:${e.conversationId}`;return{...e,updatedAt:e.lastMessageAt??s.get(t)?.updatedAt??n}})})}buildSessionListSyncCandidate(e){const t=Date.now();if("incremental"===e.mode)return this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e.items),t);const s=this.filterItemsAgainstConversationDeletions(e.items).map(e=>({...e,updatedAt:e.lastMessageAt??t}));return this.hydrateSessionListRecordsFromLocalProfiles(Od({snapshot:s,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),s=this.conversationDeletionTimestamps.get(t);if(void 0===s)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>s})}getConversationLatestUpdate(e,t,s,n){const r=e.find(e=>e.conversationId===s&&e.type===n),i=t.find(e=>e.conversationId===s&&e.conversationType===n);return Math.max(r?.lastUpdate??0,r?.lastMessage?.timestamp??0,i?.updatedAt??0,i?.lastMessageAt??0,i?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const s=this.groupNamecardCache.getAll().length;if(s>0){const e=this.calculateEvictCount(s,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const n=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),n}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,s=this.calculateEvictCount(t,.05);return s>0?(this.conversationCache.evictByLru(s),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const s=Math.floor(e*t);return Math.max(s,1)}mergeConversationLists(e,t,s,n){const r=/* @__PURE__ */new Map,i=/* @__PURE__ */new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);r.set(e,d.lastAccess),i.set(e,d)}const o=[],a=/* @__PURE__ */new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=r.get(e)??s;o.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:s})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof n&&e.lastUpdate>n)});return[...o,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const n=e[s],r=t[s];if(!n||!r)return!1;if(this.buildConversationSignature(n)!==this.buildConversationSignature(r))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,s=St(t),n=e.isPinned?"1":"0",r="number"==typeof e.pinnedTime?e.pinnedTime:0,i=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${n}:${r}:${i}:${s}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,s)=>e===t[s])}buildConversationFromMessage(e,t,s=Date.now()){const n=this.resolveConversationFromMessage(e);if(!n)return null;const r=e.msgServerId||e.msgLocalId,i=t?.lastMessage?.msgId!==r&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,o="SEND"===e.direct?s:t?.lastAccess??s;return{conversationId:n.conversationId,type:n.type,lastMessage:this.buildMessageSnippet(e),unreadCount:i,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:o,lastUpdate:s}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,s="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return s?{conversationId:s,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=xo(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{...Ct(e),msgId:e.msgServerId||e.msgLocalId,from:e.sender.userId||e.from,to:$c({conversationId:e.conversationId,conversationType:e.conversationType,currentUserId:this.userId,from:e.sender.userId||e.from,to:e.to,direct:e.direct}),sender:{...e.sender},direct:e.direct,type:e.type,body:this.normalizeMessageBody(e.body),ext:e.ext,timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return vt(e)}buildSessionListRecordFromConversation(e,t,s,n=Date.now()){const r=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),i=r.get(e.conversationId),o=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],n,!1)[0],c=o??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,l=s?.conversationName,u=s?.conversationAvatar,h="string"==typeof t.sender.userId?t.sender.userId:"",p=this.resolveSessionDisplayUserInfo(h),m=this.buildSessionMessageSender(h,t.sender,r.get(h),p),f=$c({conversationId:e.conversationId,conversationType:e.type,currentUserId:this.userId,from:h,to:t.to,direct:t.direct}),g="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,i,c,l,u):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,l,u):this.buildGroupSessionDisplayFields(e.conversationId,l,u);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,s),lastMessage:d?{...Ct(d),msgServerId:d.msgId,from:h,to:f,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body,ext:d.ext??{}}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:s?.readAt,remindType:s?.remindType??"DEFAULT",conversationName:g.conversationName,conversationAvatar:g.conversationAvatar,updatedAt:n}}resolveSessionListUnreadCount(e,t,s){const n=s?.unreadCount,r=t.msgServerId||t.msgLocalId;return s?.lastMessage?.msgServerId!==r&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof n?Math.max(e.unreadCount,n+1):e.unreadCount:"number"==typeof n?Math.max(e.unreadCount,n):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,s,n,r){const i=t?.remark?.trim(),o=t?.userInfo.avatarUrl??s?.avatarUrl??r;if(i)return{conversationName:i,conversationAvatar:o};const a=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return a?{conversationName:a,conversationAvatar:o}:n?{conversationName:n,conversationAvatar:o}:{conversationName:e,conversationAvatar:o}}shouldSkipSessionUserDisplayRefresh(e,t,s){if(!t.has(e))return!0;const n=t.get(e),r=s.get(e);return"number"==typeof n&&"number"==typeof r?.lastUpdate&&r.lastUpdate>n}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),r=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const s=e.lastMessage;if(!s)return e;const i=s.sender.userId,o=n.get(i),a=this.resolveSessionDisplayUserInfo(i,r),c="singleChat"===e.conversationType&&i===e.conversationId?this.buildSingleChatPeerMessageSender(i,s.sender,o,a):this.buildSessionMessageSender(i,s.sender,o,a);return this.isSenderEqual(s.sender,c)?e:{...e,lastMessage:{...s,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const s=this.userInfoRuntimeStore.get(e,!1)?.profile;if(s)return s;const n=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return n?Pd(n):null}buildSessionMessageSender(e,t,s,n){const r=s?.remark?.trim();return{userId:e,nickname:r||s?.userInfo.nickname?.trim()||n?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:s?.userInfo.avatarUrl??n?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,s,n){const r=this.buildSessionMessageSender(e,void 0,s,n);return{userId:e,nickname:t?.nickname?.trim()||r.nickname,avatarUrl:t?.avatarUrl||r.avatarUrl}}isSenderEqual(e,t){return e.userId===t.userId&&e.nickname===t.nickname&&e.avatarUrl===t.avatarUrl}buildGroupSessionDisplayFields(e,t,s){return t?{conversationName:t,conversationAvatar:s}:{conversationName:e}}mapJoinedGroupRemindTypeToSession(e){if("DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e)return e}buildChatRoomSessionDisplayFields(e,t,s){return t?{conversationName:t,conversationAvatar:s}:{conversationName:e}}isSessionListEqual(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const n=e[s],r=t[s];if(!n||!r)return!1;if(this.buildSessionListSignature(n)!==this.buildSessionListSignature(r))return!1}return!0}buildSessionListSignature(e){const t=e.lastMessage,s=St(t),n=`${e.conversationName}:${e.conversationAvatar??""}`;return[e.conversationType,e.conversationId,e.unreadCount,e.isPinned?"1":"0",e.pinnedTimestamp??0,e.marks.join(","),e.readAt??0,e.remindType,e.lastMessageAt??0,n,s].join(":")}refreshContactCacheIntegrity(e=!0){const t=this.contactCache.computeIntegrity(this.userInfoCache.getAll());this.contactCache.setMeta(t),e&&this.scheduleFlush(["contactMeta"])}buildContactSnapshotSignature(e){const t=e.items.map(e=>`${e.userId}:${e.userInfo.nickname??""}:${e.userInfo.avatarUrl??""}:${e.userInfo.sign??""}:${e.userInfo.ext??""}:${e.remark}:${e.addTs}`).join("|");return`${e.version}:${e.complete?"1":"0"}:${t}`}applyContactLocalPatch(e){const t=this.loadContactSnapshot("cache"),s=e();return s&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactMeta"])),{snapshot:this.loadContactSnapshot("cache"),changed:s&&this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(this.loadContactSnapshot("cache"))}}}class Kd{constructor(){this.handlers=/* @__PURE__ */new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const s=[],n=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?s.push(i):n.push(i)}const r=this.dispatchToHandlers(e,t,s);r?r.then(()=>{this.dispatchToHandlers(e,t,n)}):this.dispatchToHandlers(e,t,n)}dispatchToHandlers(e,t,s){let n=null;for(const[,r]of s){const s=r[e];s&&(n=n?n.then(async()=>{await this.invokeHandler(e,t,s)}):this.invokeHandler(e,t,s))}return n}invokeHandler(e,t,s){try{const n=s(t);return this.isPromiseLike(n)?Promise.resolve(n).then(()=>{}).catch(t=>{this.reportHandlerError(e,t)}):null}catch(n){return this.reportHandlerError(e,n),null}}reportHandlerError(e,t){e!==ut.LOG&&a.error(`Event handler error for ${e}`,t)}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const Gd={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Vd(e,t){const s=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),n=Math.min(s,t.maxDelay);if(t.jitter){const e=.2*n,t=(2*Math.random()-1)*e;return Math.max(0,n+t)}return n}function Hd(e){return new Promise(t=>setTimeout(t,e))}const zd=(e,t)=>JSON.stringify([t,e]),jd=(e,t,s)=>{const n=e.lastMessage;if(!n)return null;const r=((e,t,s)=>{const n=e.lastMessage,r=s.get(zd(e.conversationId,e.type)),i=n?.msgId&&r?.msgServerId===n.msgId?r:void 0,o=n?.sender?.userId||n?.from||i?.sender?.userId||i?.from||"",a=t.getCurrentUserId?.()??"",c=(i?.sender?.userId||i?.from)===o?i:void 0,d=n?.sender?.userId===o?n.sender:c?.sender,l=n?.direct??c?.direct,u=$c({conversationId:e.conversationId,conversationType:e.type,currentUserId:a,from:o,to:n?.to||c?.to,direct:l});return{...Ct(i),...Ct(n),from:o,to:u,sender:{...d,userId:o},direct:l,ext:n?.ext??i?.ext??{}}})(e,t,s);return{...Ct(r),msgServerId:n.msgId,from:r.from,to:r.to,sender:r.sender,direct:r.direct,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof n.type&&n.type.length>0?n.type:"text",timestamp:n.timestamp,body:vt(n.body),ext:r.ext}},Wd=async(e,t)=>{const s=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!s)/* @__PURE__ */
|
|
1
|
+
import{E as e,g as t,u as s,v as n,P as r,a as i,w as o,x as a,l as c,y as d,q as l,z as u,B as h,H as p,D as m,F as f,G as g,I as y,r as I,J as v,K as C,M as E,L as S,k as A,O as T,Q as b,T as w,W as N,X as M,V as R,j as _,o as D,A as O,s as U,S as L,Y as k,U as P,p as x,Z as F,_ as B,$ as q,a0 as K,a1 as G,a2 as V,a3 as H,a4 as z,a5 as j,a6 as W,a7 as Q,a8 as $,a9 as Y,aa as J,ab as X,ac as Z,ad as ee,ae as te,af as se,ag as ne,ah as re,R as ie,t as oe,ai as ae,aj as ce,ak as de,al as le,am as ue,an as he,ao as pe,ap as me,aq as fe,ar as ge,as as ye,at as Ie,au as ve,av as Ce,aw as Ee,ax as Se,ay as Ae,az as Te,aA as be,aB as we,aC as Ne,aD as Me,aE as Re,m as _e,C as De,aF as Oe,aG as Ue,aH as Le,aI as ke,aJ as Pe}from"./chunks/common-gbNWJrBc.js";import{i as xe,aK as Fe}from"./chunks/common-gbNWJrBc.js";import{P as Be,d as qe,b as Ke,C as Ge,E as Ve,M as He,a as ze,N as je,l as We,c as Qe,e as $e,t as Ye,f as Je,g as Xe,h as Ze,i as et,R as tt,j as st,r as nt,k as rt,S as it}from"./chunks/index-Dknccp9Q.js";import{m as ot,n as at,I as ct}from"./chunks/index-Dknccp9Q.js";import{a as dt,b as lt,g as ut,I as ht,c as pt,d as mt,v as ft,e as gt,f as yt,h as It,i as vt,M as Ct,j as Et,k as St,V as At,p as Tt,l as bt,r as wt}from"./chunks/chat-manager-BB7wYWYG.js";import{C as Nt}from"./chunks/chat-manager-BB7wYWYG.js";import{L as Mt}from"./chunks/index-CsqE2tfH.js";import{l as Rt}from"./chunks/light-DImBnNes.js";import{i as _t,a as Dt,e as Ot,b as Ut}from"./chunks/reflection-proto-codec-B1apL0ws.js";import{G as Lt,C as kt,a as Pt,b as xt,L as Ft}from"./chunks/event-system-DguqwFpc.js";import{P as Bt}from"./chunks/event-system-DguqwFpc.js";import{n as qt,J as Kt}from"./chunks/index-BxMCMoWN.js";import{G as Gt,a as Vt}from"./chunks/index-BxMCMoWN.js";import{k as Ht,r as zt,c as jt,b as Wt,d as Qt,e as $t}from"./chunks/multibody-content-BHb-Au8Q.js";import{n as Yt}from"./chunks/profile-version-DLMz8lqW.js";import{m as Jt}from"./chunks/group-user-info-resolver-rs5Fnr0l.js";import{p as Xt,a as Zt,m as es,b as ts,c as ss,t as ns}from"./chunks/session-list-query-Inseic9m.js";import{s as rs,a as is,i as os}from"./chunks/cache-utils-B99glc0H.js";import{z as as}from"zod";import{c as cs}from"./chunks/query-params-Bu3Xq4b6.js";import{r as ds,R as ls}from"./chunks/index-C_EMU0-3.js";import{C as us}from"./chunks/index-C_EMU0-3.js";import{ChatRoom as hs,ChatRoomManager as ps}from"./managers/chatroom/index.js";import{PresenceManager as ms}from"./managers/presence/index.js";import{P as fs}from"./chunks/push-manager-BO3xq-7O.js";import{UserInfoManager as gs}from"./managers/user-info/index.js";const ys="onChatRoomDestroyed",Is="onMembersJoined",vs="onMembersExited",Cs="onRemovedFromChatRoom",Es="onMuteListAdded",Ss="onMuteListRemoved",As="onAllowListAdded",Ts="onAllowListRemoved",bs="onAllMemberMuteStateChanged",ws="onAdminAdded",Ns="onAdminRemoved",Ms="onOwnerChanged",Rs="onAnnouncementChanged",_s="onChatRoomInfoChanged",Ds="onAttributesUpdate",Os="onAttributesRemoved",Us="Sorry, user register limit",Ls="Sorry, user register rate limit",ks="Sorry, token expired",Ps="Sorry, token or password does not match login info",xs="Sorry, user not found",Fs="Sorry, the app month live count limit",Bs="Sorry, the app day live count limit",qs="Sorry, the app online count limit",Ks={[Be.FAIL]:e.AUTH_UNAUTHORIZED,[Be.UNAUTHORIZED]:e.AUTH_UNAUTHORIZED,[Be.MISSING_PARAMETER]:e.VALIDATION_REQUIRED,[Be.WRONG_PARAMETER]:e.VALIDATION_INVALID_FORMAT,[Be.REDIRECT]:e.CONNECTION_WEBSOCKET_ERROR,[Be.TOKEN_EXPIRED]:e.AUTH_TOKEN_EXPIRED,[Be.PERMISSION_DENIED]:e.AUTH_FORBIDDEN,[Be.PERMISSION_DENIED_EXTERNAL]:e.AUTH_FORBIDDEN,[Be.NO_ROUTE]:e.CONNECTION_WEBSOCKET_ERROR,[Be.UNKNOWN_COMMAND]:e.UNKNOWN,[Be.PB_PARSER_ERROR]:e.UNKNOWN,[Be.BIND_ANOTHER_DEVICE]:e.AUTH_BIND_ANOTHER_DEVICE,[Be.IM_FORBIDDEN]:e.AUTH_FORBIDDEN,[Be.TOO_MANY_DEVICES]:e.AUTH_LOGIN_TOO_MANY_DEVICES,[Be.PLATFORM_LIMIT]:e.SERVICE_LIMIT_EXCEEDED,[Be.USER_MUTED]:e.AUTH_USER_MUTED,[Be.ENCRYPT_DISABLE]:e.UNKNOWN,[Be.ENCRYPT_ENABLE]:e.UNKNOWN,[Be.DECRYPT_FAILURE]:e.MESSAGE_DECODE_FAILED,[Be.RESOURCE_CHANGED]:e.USER_DEVICE_CHANGED},Gs=/* @__PURE__ */new Set([Be.FAIL,Be.UNAUTHORIZED,Be.MISSING_PARAMETER,Be.WRONG_PARAMETER,Be.TOKEN_EXPIRED,Be.PERMISSION_DENIED,Be.PERMISSION_DENIED_EXTERNAL,Be.UNKNOWN_COMMAND,Be.PB_PARSER_ERROR,Be.BIND_ANOTHER_DEVICE,Be.IM_FORBIDDEN,Be.TOO_MANY_DEVICES,Be.PLATFORM_LIMIT,Be.USER_MUTED,Be.ENCRYPT_DISABLE,Be.ENCRYPT_ENABLE,Be.DECRYPT_FAILURE,Be.RESOURCE_CHANGED]),Vs={[Us]:e.SERVICE_LIMIT_EXCEEDED,[Ls]:e.SERVICE_LIMIT_EXCEEDED,[ks]:e.AUTH_TOKEN_EXPIRED,[Ps]:e.AUTH_UNAUTHORIZED,[xs]:e.AUTH_UNAUTHORIZED,blocked:e.MESSAGE_BLOCKED_BY_RECIPIENT,"group not found":e.GROUP_NOT_EXIST,"illegal chatroom tag":e.VALIDATION_REQUIRED,"not in group or chatroom":e.GROUP_NOT_JOINED,"exceed recall time limit":e.MESSAGE_RECALL_TIME_LIMIT,"message recall disabled":e.SERVICE_NOT_ENABLED,"group ack not open":e.SERVICE_NOT_ENABLED,"group ack msg permission denied":e.GROUP_PERMISSION_DENIED,"the message has expired":e.MESSAGE_EXPIRED,"limit send group ack msg":e.SERVICE_LIMIT_EXCEEDED,"not in group or chatroom white list":e.MESSAGE_ILLEGAL_WHITELIST,nonroster:e.USER_NOT_ON_ROSTER,"group is disabled":e.GROUP_DISABLED,"roaming is not open":e.SERVICE_NOT_ENABLED,"Sorry, message does not exist":e.VALIDATION_REQUIRED,"Sorry, edit limit reached":e.SERVICE_LIMIT_EXCEEDED,"Sorry, You do not have permission":e.AUTH_FORBIDDEN,"Sorry, format is incorrect":e.VALIDATION_REQUIRED,"Sorry, edit is not available":e.SERVER_SERVING_DISABLED,"Sorry, edit fail":e.MESSAGE_EDIT_FAILED},Hs=[["limit directed users",e.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.AUTH_FORBIDDEN]],zs={[Fs]:e.SERVICE_LIMIT_EXCEEDED,[Bs]:e.SERVICE_LIMIT_EXCEEDED,[qs]:e.SERVICE_LIMIT_EXCEEDED,"sensitive words":e.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"blocked by mod_antispam":e.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"user is mute":e.USER_MUTED_BY_ADMIN,"traffic limit":e.MESSAGE_CURRENT_LIMITING,"Sorry, data is too large":e.MESSAGE_SIZE_LIMIT},js=(t,s)=>{if("number"!=typeof t)return{code:e.UNKNOWN,retryable:!0};const n=((t,s)=>{if(s){if(t===Be.FAIL){const t=Vs[s];if(void 0!==t)return t;for(const[e,n]of Hs)if(s.includes(e))return n;try{const t=JSON.parse(s);if("moderation"===t.error_type)return e.THIRD_MODERATION_FAILED;if("string"==typeof t.error_type)return e.THIRD_DEFAULT_FAILED}catch{}return}return t===Be.PERMISSION_DENIED?zs[s]:t===Be.PERMISSION_DENIED_EXTERNAL?e.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===Be.USER_MUTED?e.AUTH_USER_MUTED:void 0}})(t,s),r=Ks[t]??e.UNKNOWN;return{code:n??r,retryable:!Gs.has(t)}},Ws={[e.SERVICE_LIMIT_EXCEEDED]:"Message operation exceeded a service limit",[e.AUTH_TOKEN_EXPIRED]:"Message cannot be sent because the authentication token expired",[e.VALIDATION_REQUIRED]:"Message cannot be sent because the request is invalid",[e.AUTH_UNAUTHORIZED]:"Message cannot be sent because authentication failed",[e.AUTH_FORBIDDEN]:"Message operation is forbidden",[e.AUTH_BIND_ANOTHER_DEVICE]:"Message cannot be sent because the account is bound to another device",[e.AUTH_LOGIN_TOO_MANY_DEVICES]:"Message cannot be sent because the account is logged in on too many devices",[e.AUTH_USER_MUTED]:"Message cannot be sent because the user is muted in the group or chat room",[e.MESSAGE_BLOCKED_BY_RECIPIENT]:"Message cannot be sent because you are blocked by the recipient",[e.USER_MUTED_BY_ADMIN]:"Message cannot be sent because the user is globally muted",[e.USER_DEVICE_CHANGED]:"Message cannot be sent because the current device has changed",[e.USER_NOT_ON_ROSTER]:"Message cannot be sent because the recipient is not in your contact list",[e.CONNECTION_WEBSOCKET_ERROR]:"Message cannot be sent because the server is unreachable",[e.SERVER_SERVING_DISABLED]:"Message editing is not available",[e.MESSAGE_DECODE_FAILED]:"Message processing failed",[e.MESSAGE_INCLUDE_ILLEGAL_CONTENT]:"Message contains prohibited content",[e.MESSAGE_SEND_TRAFFIC_LIMIT]:"Message sending traffic limit exceeded",[e.MESSAGE_RECALL_TIME_LIMIT]:"The message recall time limit has been exceeded",[e.SERVICE_NOT_ENABLED]:"The required messaging service is not enabled",[e.MESSAGE_EXPIRED]:"The message has expired",[e.MESSAGE_ILLEGAL_WHITELIST]:"The user is not in the group or chat room allowlist",[e.MESSAGE_EXTERNAL_LOGIC_BLOCKED]:"The message was blocked by external logic",[e.MESSAGE_CURRENT_LIMITING]:"Message sending rate limit exceeded",[e.MESSAGE_SIZE_LIMIT]:"Message size exceeds the limit",[e.MESSAGE_EDIT_FAILED]:"Message editing failed",[e.GROUP_NOT_JOINED]:"The user is not in the group or chat room",[e.GROUP_PERMISSION_DENIED]:"The user does not have permission to perform this group message operation",[e.GROUP_NOT_EXIST]:"The group does not exist",[e.GROUP_DISABLED]:"The group is disabled",[e.THIRD_MODERATION_FAILED]:"The message was rejected by content moderation",[e.THIRD_DEFAULT_FAILED]:"The message was rejected by a third-party service"};class Qs{constructor(){this.lastEventKey=null}normalize(e,t){const s=(e=>{switch(e){case dt.CONNECTING:case dt.RECONNECTING:return lt.CONNECTING;case dt.CONNECTED:return lt.CONNECTED;case dt.DISCONNECTED:return lt.DISCONNECTED;case dt.RECONNECT_FAILED:return lt.RECONNECT_FAILED;default:return null}})(e);if(!s)return null;const n=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(s,t);return this.lastEventKey===n?null:(this.lastEventKey=n,{eventName:s,payload:t})}reset(){this.lastEventKey=null}}const $s={web:s.WEB,"mp-weixin":s.WECHAT_MINIAPP,"mp-alipay":s.ALIPAY_MINIAPP,"mp-baidu":s.BAIDU_MINIAPP,"mp-toutiao":s.TOUTIAO_MINIAPP,"mp-lark":s.LARK_MINIAPP,"mp-qq":s.QQ_MINIAPP,"mp-kuaishou":s.KUAISHOU_MINIAPP,"mp-jd":s.JD_MINIAPP,"mp-360":s.MINIAPP_360,"mp-harmony":s.HARMONY_MINIAPP,"quickapp-webview":s.QUICKAPP,"quickapp-webview-union":s.QUICKAPP,"quickapp-webview-huawei":s.QUICKAPP},Ys=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Js=e=>(e=>Ys(e,"canIUse")&&Ys(e,"getSystemInfo"))(e)||(e=>Ys(e,"request")&&Ys(e,"connectSocket"))(e),Xs=e=>Ys(e,"request")&&Ys(e,"connectSocket")&&Ys(e,"uploadFile"),Zs=(e,t)=>t===s.WECHAT_MINIAPP?e.wx:t===s.QQ_MINIAPP?e.qq:t===s.TOUTIAO_MINIAPP?e.tt:t===s.BAIDU_MINIAPP?e.swan:t===s.ALIPAY_MINIAPP?e.my:t===s.DINGTALK_MINIAPP?e.dd:t===s.JD_MINIAPP?e.jd:t===s.KUAISHOU_MINIAPP?e.ks:t===s.UNIAPP?e.uni:void 0,en=e=>{const t=e?.miniGlobal;return Js(t)?t:e},tn=e=>{const t=en(e);return Xs(t)?t:void 0},sn=e=>void 0!==e.window&&void 0!==e.document,nn=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),rn=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(Js(t))return!0;try{if(!Ys(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},on=e=>Xs(e.wx)?s.WECHAT_MINIAPP:Xs(e.my)?s.ALIPAY_MINIAPP:Xs(e.dd)?s.DINGTALK_MINIAPP:Xs(e.swan)?s.BAIDU_MINIAPP:Xs(e.tt)?s.TOUTIAO_MINIAPP:Xs(e.qq)?s.QQ_MINIAPP:Xs(e.jd)?s.JD_MINIAPP:Xs(e.ks)?s.KUAISHOU_MINIAPP:void 0,an=e=>void 0!==on(e),cn=e=>{const t=on(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),n=t?.uniPlatform;if("string"==typeof n)return $s[n]??s.UNIAPP}catch{return s.UNIAPP}return sn(e)?s.WEB:s.UNIAPP},dn=(e,t)=>{const s=tn(Zs(e,t));if(s)return s;const n=tn(e.uni);return n||(e.uni??e)},ln=(e,n)=>{const r=e??t();if(n){const e=n===s.UNIAPP||rn(r),t=e?cn(r):n;return{platform:n,hostPlatform:t,framework:e?"uniapp":sn(r)?"web":"native",global:e?dn(r,t):en(Zs(r,n))??r}}if(rn(r)){const e=cn(r);return{platform:s.UNIAPP,hostPlatform:e,framework:"uniapp",global:dn(r,e)}}return Js(r.swan)?{platform:s.BAIDU_MINIAPP,hostPlatform:s.BAIDU_MINIAPP,framework:"native",global:en(r.swan)??r.swan}:Js(r.tt)?{platform:s.TOUTIAO_MINIAPP,hostPlatform:s.TOUTIAO_MINIAPP,framework:"native",global:en(r.tt)??r.tt}:Js(r.dd)?{platform:s.DINGTALK_MINIAPP,hostPlatform:s.DINGTALK_MINIAPP,framework:"native",global:en(r.dd)??r.dd}:Js(r.my)?{platform:s.ALIPAY_MINIAPP,hostPlatform:s.ALIPAY_MINIAPP,framework:"native",global:en(r.my)??r.my}:Js(r.wx)?{platform:s.WECHAT_MINIAPP,hostPlatform:s.WECHAT_MINIAPP,framework:"native",global:en(r.wx)??r.wx}:Js(r.qq)?{platform:s.QQ_MINIAPP,hostPlatform:s.QQ_MINIAPP,framework:"native",global:en(r.qq)??r.qq}:Js(r.jd)?{platform:s.JD_MINIAPP,hostPlatform:s.JD_MINIAPP,framework:"native",global:en(r.jd)??r.jd}:Js(r.ks)?{platform:s.KUAISHOU_MINIAPP,hostPlatform:s.KUAISHOU_MINIAPP,framework:"native",global:en(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:s.REACT_NATIVE,hostPlatform:s.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:sn(r)?s.ELECTRON_RENDERER:s.ELECTRON_MAIN,hostPlatform:sn(r)?s.ELECTRON_RENDERER:s.ELECTRON_MAIN,framework:"electron",global:r}:nn(r)||sn(r)?{platform:s.WEB,hostPlatform:s.WEB,framework:nn(r)?"worker":"web",global:r}:{platform:s.UNKNOWN,hostPlatform:s.UNKNOWN,framework:"native",global:r}},un=e=>e===s.WECHAT_MINIAPP||e===s.QQ_MINIAPP||e===s.TOUTIAO_MINIAPP||e===s.BAIDU_MINIAPP||e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP||e===s.LARK_MINIAPP||e===s.KUAISHOU_MINIAPP||e===s.JD_MINIAPP||e===s.MINIAPP_360||e===s.HARMONY_MINIAPP||e===s.QUICKAPP||e===s.UNIAPP,hn=["request","upload","socket","proto"],pn=(e,t=hn)=>{const s=((e,t=hn)=>t.filter(t=>!e[t]))(e,t);if(0!==s.length)throw n("Platform missing required capabilities.",{code:r.MISSING_CAPABILITY,stage:i.INIT,retryable:!1,details:{required:[...t],missing:s}})},mn={nested:{easemob:{nested:{pb:{nested:{MessageBody:{fields:{type:{type:"Type",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},contents:{rule:"repeated",type:"Content",id:4},ext:{rule:"repeated",type:"KeyValue",id:5},ackMessageId:{type:"uint64",id:6},msgConfig:{type:"MessageConfig",id:7},ackContent:{type:"string",id:8},meta:{type:"string",id:9},editMessageId:{type:"uint64",id:11},editScope:{type:"EditScope",id:12},stream:{type:"Stream",id:13},userInfoUpdateTime:{type:"int32",id:14},namecardUpdateTime:{type:"int32",id:15},sendToPeer:{type:"bool",id:16},ackMessageIds:{rule:"repeated",type:"uint64",id:17},clearAllUnreadMessageCount:{type:"bool",id:18}},nested:{Content:{fields:{type:{type:"Type",id:1},text:{type:"string",id:2},latitude:{type:"double",id:3},longitude:{type:"double",id:4},address:{type:"string",id:5},displayName:{type:"string",id:6},remotePath:{type:"string",id:7},secretKey:{type:"string",id:8},fileLength:{type:"int32",id:9},action:{type:"string",id:10},params:{rule:"repeated",type:"KeyValue",id:11},duration:{type:"int32",id:12},size:{type:"Size",id:13},thumbnailRemotePath:{type:"string",id:14},thumbnailSecretKey:{type:"string",id:15},thumbnailDisplayName:{type:"string",id:16},thumbnailFileLength:{type:"int32",id:17},thumbnailSize:{type:"Size",id:18},customEvent:{type:"string",id:19},customExts:{rule:"repeated",type:"KeyValue",id:20},buildingName:{type:"string",id:21},subType:{type:"SubType",id:22},title:{type:"string",id:23},summary:{type:"string",id:24},combineLevel:{type:"int32",id:25},imageType:{type:"int32",id:26}},nested:{Type:{values:{TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8}},Size:{fields:{width:{type:"double",id:1},height:{type:"double",id:2}}},SubType:{values:{COMBINE:0,GIF:1,SUB_STREAM:10}}}},Type:{values:{NORMAL:0,CHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8}},EditScope:{values:{BODY:1,BODY_AND_EXT:2}},MessageConfig:{fields:{allowGroupAck:{type:"bool",id:1}}},Stream:{fields:{streamType:{type:"string",id:1},streamSeq:{type:"uint64",id:2},streamStatus:{type:"StreamStatus",id:3},streamError:{type:"uint32",id:4},streamFinishReason:{type:"int32",id:5}},nested:{StreamStatus:{values:{STREAM_START:0,STREAM_START_COMPLETED:1,STREAM_IN_PROGRESS:2,STREAM_COMPLETED:3,STREAM_FULL:4}}}}}},KeyValue:{oneofs:{value:{oneof:["varintValue","floatValue","doubleValue","stringValue"]}},fields:{key:{type:"string",id:1},type:{type:"ValueType",id:2},varintValue:{type:"int64",id:3},floatValue:{type:"float",id:4},doubleValue:{type:"double",id:5},stringValue:{type:"string",id:6}},nested:{ValueType:{values:{BOOL:1,INT:2,UINT:3,LLINT:4,FLOAT:5,DOUBLE:6,STRING:7,JSON_STRING:8}}}},JID:{fields:{appKey:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},clientResource:{type:"string",id:4}}},ConferenceBody:{fields:{sessionId:{type:"string",id:1},operation:{type:"Operation",id:2},conferenceId:{type:"string",id:3},type:{type:"Type",id:4},content:{type:"string",id:5},network:{type:"string",id:6},version:{type:"string",id:7},identity:{type:"Identity",id:8},duration:{type:"string",id:9},peerName:{type:"string",id:10},endReason:{type:"EndReason",id:11},status:{type:"Status",id:12},isDirect:{type:"bool",id:13},controlType:{type:"StreamControlType",id:14},routeFlag:{type:"int32",id:15},routeKey:{type:"string",id:16}},nested:{Status:{fields:{errorCode:{type:"int32",id:1}}},Operation:{values:{JOIN:0,INITIATE:1,ACCEPT_INITIATE:2,ANSWER:3,TERMINATE:4,REMOVE:5,STREAM_CONTROL:6,MEDIA_REQUEST:7}},Type:{values:{VOICE:0,VIDEO:1}},Identity:{values:{CALLER:0,CALLEE:1}},EndReason:{values:{HANGUP:0,NORESPONSE:1,REJECT:2,BUSY:3,FAIL:4,UNSUPPORTED:5,OFFLINE:6}},StreamControlType:{values:{PAUSE_VOICE:0,RESUME_VOICE:1,PAUSE_VIDEO:2,RESUME_VIDEO:3}}}},MSync:{fields:{version:{type:"Version",id:1,options:{default:"MSYNC_V1"}},guid:{type:"JID",id:2},auth:{type:"string",id:3},compressAlgorimth:{type:"uint32",id:4},crypto:{type:"uint32",id:5},userAgent:{type:"string",id:6},pov:{type:"uint64",id:7},command:{type:"Command",id:8},deviceId:{type:"uint32",id:10},encryptType:{rule:"repeated",type:"EncryptType",id:11,options:{packed:!1}},encryptKey:{type:"string",id:12},payload:{type:"bytes",id:9},traceId:{type:"uint64",id:20}},nested:{Version:{values:{MSYNC_V1:0,MSYNC_V2:1}},Command:{values:{SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4}}}},EncryptType:{values:{ENCRYPT_NONE:0,ENCRYPT_AES_128_CBC:1,ENCRYPT_AES_256_CBC:2}},CommSyncUL:{fields:{meta:{type:"Meta",id:1},key:{type:"uint64",id:2},queue:{type:"JID",id:3},isRoam:{type:"bool",id:4},lastFullRoamKey:{type:"uint64",id:5}}},CommSyncDL:{fields:{status:{type:"Status",id:1},metaId:{type:"uint64",id:2},serverId:{type:"uint64",id:3},metas:{rule:"repeated",type:"Meta",id:4},nextKey:{type:"uint64",id:5},queue:{type:"JID",id:6},isLast:{type:"bool",id:7},timestamp:{type:"uint64",id:8},isRoam:{type:"bool",id:9}}},CommNotice:{fields:{queue:{type:"JID",id:1}}},CommUnreadUL:{fields:{}},CommUnreadDL:{fields:{status:{type:"Status",id:1},unread:{rule:"repeated",type:"MetaQueue",id:2},timestamp:{type:"uint64",id:3}}},MetaQueue:{fields:{queue:{type:"JID",id:1},n:{type:"uint32",id:2}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},timestamp:{type:"uint64",id:4},ns:{type:"NameSpace",id:5},payload:{type:"bytes",id:6},routetype:{type:"RouteType",id:7},ext:{rule:"repeated",type:"KeyValue",id:8},meta:{type:"bytes",id:9},directedUsers:{rule:"repeated",type:"string",id:10},env:{type:"string",id:13}},nested:{NameSpace:{values:{STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,CONFERENCE:4,NOTIFY:5,QUERY:6}},RouteType:{values:{ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},reason:{type:"string",id:2},redirectInfo:{rule:"repeated",type:"RedirectInfo",id:3}},nested:{ErrorCode:{values:{OK:0,FAIL:1,UNAUTHORIZED:2,MISSING_PARAMETER:3,WRONG_PARAMETER:4,REDIRECT:5,TOKEN_EXPIRED:6,PERMISSION_DENIED:7,NO_ROUTE:8,UNKNOWN_COMMAND:9,PB_PARSER_ERROR:10,BIND_ANOTHER_DEVICE:11,IM_FORBIDDEN:12,TOO_MANY_DEVICES:13,PLATFORM_LIMIT:14,USER_MUTED:15,ENCRYPT_DISABLE:16,ENCRYPT_ENABLE:17,DECRYPT_FAILURE:18,PERMISSION_DENIED_EXTERNAL:19}}}},RedirectInfo:{fields:{host:{type:"string",id:1},port:{type:"uint32",id:2}}},Provision:{fields:{osType:{type:"OsType",id:1},version:{type:"string",id:2},networkType:{type:"NetworkType",id:3},appSign:{type:"string",id:4},compressType:{rule:"repeated",type:"CompressType",id:5,options:{packed:!1}},encryptType:{rule:"repeated",type:"EncryptType",id:6,options:{packed:!1}},encryptKey:{type:"string",id:7},status:{type:"Status",id:8},deviceUuid:{type:"string",id:9},isManualLogin:{type:"bool",id:10},password:{type:"string",id:11},deviceName:{type:"string",id:12},resource:{type:"string",id:13},auth:{type:"string",id:14},serviceId:{type:"string",id:16},actionVersion:{type:"string",id:17},authToken:{type:"string",id:18},osCustomValue:{type:"uint32",id:19},sessionId:{type:"string",id:20},reason:{type:"string",id:21},protocolCompressType:{rule:"repeated",type:"CompressType",id:22},protocolCompressDirection:{type:"CompressDirection",id:23}},nested:{OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}},CompressType:{values:{COMPRESS_NONE:0,COMPRESS_ZLIB:1,COMPRESS_LZ4:2}},CompressDirection:{values:{ONLY_UP:0,ONLY_DOWN:1,BI:2}}}},Logout:{fields:{sessionId:{type:"string",id:1},reason:{type:"string",id:2},status:{type:"Status",id:3}}},MUCBody:{fields:{mucId:{type:"JID",id:1},operation:{type:"Operation",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},setting:{type:"Setting",id:5},reason:{type:"string",id:6},isChatroom:{type:"bool",id:7},status:{type:"Status",id:8},isThread:{type:"bool",id:9},mucParentId:{type:"JID",id:10},mucName:{type:"string",id:11},eventInfo:{type:"EventInfo",id:12},mucMemberCount:{type:"int32",id:13},ext:{type:"string",id:14},leaveOtherRooms:{type:"bool",id:15},members:{rule:"repeated",type:"string",id:16}},nested:{Operation:{values:{CREATE:0,DESTROY:1,JOIN:2,LEAVE:3,APPLY:4,APPLY_ACCEPT:5,APPLY_DECLINE:6,INVITE:7,INVITE_ACCEPT:8,INVITE_DECLINE:9,KICK:10,GET_BLACKLIST:11,BAN:12,ALLOW:13,UPDATE:14,BLOCK:15,UNBLOCK:16,PRESENCE:17,ABSENCE:18,DIRECT_JOINED:19,ASSIGN_OWNER:20,ADD_ADMIN:21,REMOVE_ADMIN:22,ADD_MUTE:23,REMOVE_MUTE:24,UPDATE_ANNOUNCEMENT:25,DELETE_ANNOUNCEMENT:26,UPLOAD_FILE:27,DELETE_FILE:28,ADD_USER_WHITE_LIST:29,REMOVE_USER_WHITE_LIST:30,BAN_GROUP:31,REMOVE_BAN_GROUP:32,THREAD_CREATE:33,THREAD_DESTROY:34,THREAD_JOIN:35,THREAD_LEAVE:36,THREAD_KICK:37,THREAD_UPDATE:38,THREAD_PRESENCE:39,THREAD_ABSENCE:40,DISABLE_GROUP:41,ABLE_GROUP:42,SET_METADATA:43,DELETE_METADATA:44,GROUP_MEMBER_METADATA_UPDATE:45}},Setting:{fields:{name:{type:"string",id:1},desc:{type:"string",id:2},type:{type:"Type",id:3},maxUsers:{type:"int32",id:4},owner:{type:"string",id:5}},nested:{Type:{values:{PRIVATE_OWNER_INVITE:0,PRIVATE_MEMBER_INVITE:1,PUBLIC_JOIN_APPROVAL:2,PUBLIC_JOIN_OPEN:3,PUBLIC_ANONYMOUS:4}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2},chatroomInfo:{type:"string",id:3}},nested:{ErrorCode:{values:{OK:0,PERMISSION_DENIED:1,WRONG_PARAMETER:2,MUC_NOT_EXIST:3,USER_NOT_EXIST:4,UNKNOWN:5}}}},EventInfo:{fields:{eventType:{type:"EventType",id:1,options:{default:"EVENT_NONE"}},ext:{type:"string",id:2}},nested:{EventType:{values:{EVENT_NONE:0,CIRCLE_CHANNEL:1}}}}}},RosterBody:{fields:{operation:{type:"Operation",id:1},status:{type:"Status",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},reason:{type:"string",id:5},rosterVer:{type:"string",id:6},biDirection:{type:"bool",id:7}},nested:{Operation:{values:{GET_ROSTER:0,GET_BLACKLIST:1,ADD:2,REMOVE:3,ACCEPT:4,DECLINE:5,BAN:6,ALLOW:7,REMOTE_ACCEPT:8,REMOTE_DECLINE:9}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2}},nested:{ErrorCode:{values:{OK:0,USER_NOT_EXIST:1,USER_ALREADY_FRIEND:2,USER_ALREADY_BLACKLIST:3}}}}}},StatisticsBody:{fields:{operation:{type:"Operation",id:1},os:{type:"OsType",id:2},version:{type:"string",id:3},network:{type:"NetworkType",id:4},imTime:{type:"uint32",id:5},chatTime:{type:"uint32",id:6},location:{type:"string",id:7},reason:{type:"string",id:10}},nested:{Operation:{values:{INFORMATION:0,USER_REMOVED:1,USER_LOGIN_ANOTHER_DEVICE:2,USER_KICKED_BY_CHANGE_PASSWORD:3,USER_KICKED_BY_OTHER_DEVICE:4}},OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}}}}}}}}}},fn=e=>{if(!e||0===e.trim().length)throw n("Proto type name is required.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e}})};class gn{constructor(){this.codecMap=/* @__PURE__ */new Map}register(e,t){fn(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:s=>{const o=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw n("Proto payload must be an object.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(s,e),a=t.fromObject(o);return t.encode(a).finish()},decode:e=>{const s=t.decode(e);return t.toObject(s,{longs:String,enums:Number,defaults:!1})}})}get(e){return fn(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw n("Proto codec not found.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e}})}}let yn=!1,In=null,vn=null,Cn=null;const En=e=>e.startsWith(".")?e.slice(1):e,Sn=e=>e instanceof Rt.Namespace,An=e=>e instanceof Rt.Type,Tn=e=>{for(const t of e.nestedArray)An(t)?_t(t):Sn(t)&&Tn(t)},bn=()=>{yn||(Rt.util.Long=Mt,Rt.configure(),yn=!0),Dt();const e=Rt.Root.fromJSON(mn);return Tn(e),e},wn=(e,t)=>{const s=e.nestedArray;for(const n of s){if(An(n)){const e=En(n.fullName);_t(n),t.registerType(e,n);continue}Sn(n)&&wn(n,t)}},Nn=(e,t,s)=>{const o=t instanceof Error?t.message:String(t);return n(`Static proto ${s} failed.`,{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e,operation:s,cause:o}})},Mn=()=>In||(In=bn(),In),Rn=()=>{if(Cn)return Cn;const e=(()=>{if(vn)return vn;const e=new gn,t=Mn();return wn(t,e),vn=e,e})();return Cn={encode(t,s){try{return e.getOrThrow(En(t)).encode(s)}catch(n){throw Nn(t,n,"encode")}},decode(t,s){try{return e.getOrThrow(En(t)).decode(s)}catch(n){throw Nn(t,n,"decode")}}},Cn},_n=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Dn=e=>"function"==typeof e.on&&"function"==typeof e.off,On=(e,t,s)=>{if(_n(e))return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)};if(Dn(e)){const n=e;return n.on(t,s),()=>{n.off(t,s)}}throw n("Socket event listener API is unsupported.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!1,details:{event:t}})},Un=(e,t,s)=>{if(_n(e)){const n=(...r)=>{e.removeEventListener(t,n),s(...r)};return e.addEventListener(t,n),()=>{e.removeEventListener(t,n)}}if(Dn(e)){const n=e;if("function"==typeof n.once)return n.once?.(t,s),()=>{n.off(t,s)};let r=()=>{};return r=On(e,t,(...e)=>{r(),s(...e)}),r}throw n("Socket one-time listener API is unsupported.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!1,details:{event:t}})},Ln=e=>{return"string"==typeof e||(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))||"undefined"!=typeof Blob&&e instanceof Blob?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e&&"object"==typeof e&&"data"in e?Ln(e.data):null;var t},kn=e=>{const t=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set,a=/* @__PURE__ */new Set,c=/* @__PURE__ */new Set;return On(e,"open",()=>{t.forEach(e=>{e()})}),On(e,"message",(...e)=>{const t=Ln(e[0]);null!==t&&s.forEach(e=>{e(t)})}),On(e,"error",(...e)=>{const t=e[0];a.forEach(e=>{e(t)})}),On(e,"close",(...e)=>{const t=(e=>{const[t,s]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof s?s:ArrayBuffer.isView(s)?(new TextDecoder).decode(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)):void 0}})(e);c.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==o.OPEN)throw n("Socket is not open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,s){e.close(t,s)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(s.add(e),()=>{s.delete(e)}),onError:e=>(a.add(e),()=>{a.delete(e)}),onClose:e=>(c.add(e),()=>{c.delete(e)})}},Pn=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((s,o)=>{let a;try{a=new t(e.url,e.protocols);try{a.binaryType="arraybuffer"}catch{}}catch(m){return void o(n("Socket creation failed.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{cause:m instanceof Error?m.message:String(m)}}))}let c,d=()=>{},l=()=>{},u=!1;const h=()=>{void 0!==c&&(clearTimeout(c),c=void 0)},p=()=>{u||(u=!0,d(),l(),h(),a.close(),o(n("Socket connection timed out.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{url:e.url,reason:"timeout"}})))};d=Un(a,"open",()=>{u||(u=!0,d(),l(),h(),s(kn(a)))}),l=Un(a,"error",e=>{if(u)return;u=!0,d(),l(),h();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;o(n("Socket connection failed before open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(c=setTimeout(p,e.timeoutMs))})}},xn=(e,t)=>{throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:"abort"!==e,details:{reason:e,url:t.url}})},Fn=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,s])=>{t.append(e,s)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw n("Web upload adapter only supports web-file source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const s=t.source.file;if(!s)throw n("Upload source file is required for web-file uploads.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const o="undefined"!=typeof Blob&&s instanceof Blob,a=t.source.name??"upload.bin",c=t.fileFieldName??"file";o?e.append(c,s,a):e.append(c,s)})(t,e),t},Bn=(e,t,s)=>new Promise((o,a)=>{const c=e(),d=s.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const s=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:s})})})(c,s),c.addEventListener("abort",()=>{try{xn("abort",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("timeout",()=>{try{xn("timeout",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("error",()=>{try{xn("network",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("load",()=>{o({status:c.status,body:c.responseText})});try{const e=Fn(s);c.timeout=d,c.open(s.method??"POST",s.url),((e,t)=>{Object.entries(t??{}).forEach(([t,s])=>{e.setRequestHeader(t,s)})})(c,s.headers),c.send(e)}catch(l){a(n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:s.url,reason:"invalid-config",cause:l instanceof Error?l.message:String(l)}}))}}),qn=(e,t)=>e?"timeout":"abort",Kn=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,s=e?.fetchImpl;if("function"==typeof t||"function"==typeof s)return{upload(o){if("function"==typeof t)return Bn(t,e,o);if("function"==typeof s)return(async(e,t,s)=>{const o=s.timeoutMs??t?.timeoutMs??3e4;let a=!1;const c="undefined"!=typeof AbortController?new AbortController:void 0,d=c&&Number.isFinite(o)?setTimeout(()=>{a=!0,c.abort()},o):void 0,l=((e,t)=>e??t?.signal)(s.signal,c);try{const t=Fn(s),n=await e(s.url,{method:s.method??"POST",headers:s.headers,body:t,signal:l}),r=await n.text(),i=s.source.size;return"number"==typeof i&&s.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:n.status,body:r}}catch(u){const e=u instanceof Error&&"AbortError"===u.name;throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!e,details:{reason:e?qn(a):"network",url:s.url,cause:u instanceof Error?u.message:String(u)}})}finally{d&&clearTimeout(d)}})(s,e,o);throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{reason:"missing-upload-runtime",url:o.url}})}}},Gn=(e,t)=>{const s=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{s.append(e,t)}),s.append(t.fileFieldName??"file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw n("React Native upload adapter only supports rn-uri source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),s},Vn=e=>{const t=e?.fetchImpl,s=e?.formDataCtor;if("function"==typeof t&&"function"==typeof s)return{async upload(o){const a=o.timeoutMs??e?.timeoutMs??3e4,c="function"==typeof AbortController?new AbortController:void 0;let d=!1;const l=c&&Number.isFinite(a)?setTimeout(()=>{d=!0,c.abort()},a):void 0;try{const e=Gn(s,o),n=await t(o.url,{method:o.method??"POST",headers:o.headers,body:e,signal:o.signal??c?.signal}),r=await n.text(),i=o.source.size;return"number"==typeof i&&o.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:n.status,body:r}}catch(u){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===r.UPLOAD_FAILED&&t.stage===i.UPLOAD})(u))throw u;const e=u instanceof Error&&"AbortError"===u.name;throw n("React Native upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!e||d,details:{url:o.url,reason:e?d?"timeout":"abort":"network",cause:u instanceof Error?u.message:String(u)}})}finally{void 0!==l&&clearTimeout(l)}}}},Hn=(e,t)=>e+t&4294967295,zn=(e,t,s,n,r,i)=>{return Hn((o=Hn(Hn(t,e),Hn(n,i)))<<(a=r)|o>>>32-a,s);var o,a},jn=(e,t,s,n,r,i,o)=>zn(t&s|~t&n,e,t,r,i,o),Wn=(e,t,s,n,r,i,o)=>zn(t&n|s&~n,e,t,r,i,o),Qn=(e,t,s,n,r,i,o)=>zn(t^s^n,e,t,r,i,o),$n=(e,t,s,n,r,i,o)=>zn(s^(t|~n),e,t,r,i,o),Yn=(e,t)=>{let[s,n,r,i]=e;s=jn(s,n,r,i,t[0]??0,7,-680876936),i=jn(i,s,n,r,t[1]??0,12,-389564586),r=jn(r,i,s,n,t[2]??0,17,606105819),n=jn(n,r,i,s,t[3]??0,22,-1044525330),s=jn(s,n,r,i,t[4]??0,7,-176418897),i=jn(i,s,n,r,t[5]??0,12,1200080426),r=jn(r,i,s,n,t[6]??0,17,-1473231341),n=jn(n,r,i,s,t[7]??0,22,-45705983),s=jn(s,n,r,i,t[8]??0,7,1770035416),i=jn(i,s,n,r,t[9]??0,12,-1958414417),r=jn(r,i,s,n,t[10]??0,17,-42063),n=jn(n,r,i,s,t[11]??0,22,-1990404162),s=jn(s,n,r,i,t[12]??0,7,1804603682),i=jn(i,s,n,r,t[13]??0,12,-40341101),r=jn(r,i,s,n,t[14]??0,17,-1502002290),n=jn(n,r,i,s,t[15]??0,22,1236535329),s=Wn(s,n,r,i,t[1]??0,5,-165796510),i=Wn(i,s,n,r,t[6]??0,9,-1069501632),r=Wn(r,i,s,n,t[11]??0,14,643717713),n=Wn(n,r,i,s,t[0]??0,20,-373897302),s=Wn(s,n,r,i,t[5]??0,5,-701558691),i=Wn(i,s,n,r,t[10]??0,9,38016083),r=Wn(r,i,s,n,t[15]??0,14,-660478335),n=Wn(n,r,i,s,t[4]??0,20,-405537848),s=Wn(s,n,r,i,t[9]??0,5,568446438),i=Wn(i,s,n,r,t[14]??0,9,-1019803690),r=Wn(r,i,s,n,t[3]??0,14,-187363961),n=Wn(n,r,i,s,t[8]??0,20,1163531501),s=Wn(s,n,r,i,t[13]??0,5,-1444681467),i=Wn(i,s,n,r,t[2]??0,9,-51403784),r=Wn(r,i,s,n,t[7]??0,14,1735328473),n=Wn(n,r,i,s,t[12]??0,20,-1926607734),s=Qn(s,n,r,i,t[5]??0,4,-378558),i=Qn(i,s,n,r,t[8]??0,11,-2022574463),r=Qn(r,i,s,n,t[11]??0,16,1839030562),n=Qn(n,r,i,s,t[14]??0,23,-35309556),s=Qn(s,n,r,i,t[1]??0,4,-1530992060),i=Qn(i,s,n,r,t[4]??0,11,1272893353),r=Qn(r,i,s,n,t[7]??0,16,-155497632),n=Qn(n,r,i,s,t[10]??0,23,-1094730640),s=Qn(s,n,r,i,t[13]??0,4,681279174),i=Qn(i,s,n,r,t[0]??0,11,-358537222),r=Qn(r,i,s,n,t[3]??0,16,-722521979),n=Qn(n,r,i,s,t[6]??0,23,76029189),s=Qn(s,n,r,i,t[9]??0,4,-640364487),i=Qn(i,s,n,r,t[12]??0,11,-421815835),r=Qn(r,i,s,n,t[15]??0,16,530742520),n=Qn(n,r,i,s,t[2]??0,23,-995338651),s=$n(s,n,r,i,t[0]??0,6,-198630844),i=$n(i,s,n,r,t[7]??0,10,1126891415),r=$n(r,i,s,n,t[14]??0,15,-1416354905),n=$n(n,r,i,s,t[5]??0,21,-57434055),s=$n(s,n,r,i,t[12]??0,6,1700485571),i=$n(i,s,n,r,t[3]??0,10,-1894986606),r=$n(r,i,s,n,t[10]??0,15,-1051523),n=$n(n,r,i,s,t[1]??0,21,-2054922799),s=$n(s,n,r,i,t[8]??0,6,1873313359),i=$n(i,s,n,r,t[15]??0,10,-30611744),r=$n(r,i,s,n,t[6]??0,15,-1560198380),n=$n(n,r,i,s,t[13]??0,21,1309151649),s=$n(s,n,r,i,t[4]??0,6,-145523070),i=$n(i,s,n,r,t[11]??0,10,-1120210379),r=$n(r,i,s,n,t[2]??0,15,718787259),n=$n(n,r,i,s,t[9]??0,21,-343485551),e[0]=Hn(s,e[0]),e[1]=Hn(n,e[1]),e[2]=Hn(r,e[2]),e[3]=Hn(i,e[3])},Jn=(e,t)=>{const s=new Array(16).fill(0);for(let n=0;n<16;n+=1){const r=t+4*n;s[n]=(e[r]??0)|(e[r+1]??0)<<8|(e[r+2]??0)<<16|(e[r+3]??0)<<24}return s},Xn=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},Zn=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)Yn(t,Jn(e,s));const n=new Array(16).fill(0);let r=0;for(;s<e.length;s+=1){const t=r>>2;n[t]=(n[t]??0)|(e[s]??0)<<r%4*8,r+=1}const i=r>>2;n[i]=(n[i]??0)|128<<r%4*8,r>55&&(Yn(t,n),n.fill(0));const o=8*e.length;return n[14]=4294967295&o,n[15]=Math.floor(o/4294967296),Yn(t,n),t.map(Xn).join("")},er=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw n("Image decode capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,s)=>{const o=new Image;o.onload=()=>{e({image:o,width:o.naturalWidth||o.width,height:o.naturalHeight||o.height,cleanup:()=>{URL.revokeObjectURL(t)}})},o.onerror=()=>{URL.revokeObjectURL(t),s(n("Image decode failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{reason:"image load error"}}))},o.src=t})},tr=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw n("Web image processor only supports web file source",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.file},sr=()=>({async getImageInfo(e){const t=tr(e),s=await er(t);try{return{width:s.width,height:s.height,mimeType:e.mimeType,fileSize:e.size,isGif:"image/gif"===e.mimeType}}finally{s.cleanup()}},async generateBigImage(e,t){const s=tr(e),o=await er(s);try{const s=((e,t,s)=>{const n=Math.min(e,t);if(n<=s)return{width:e,height:t};const r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}})(o.width,o.height,t.maxShortEdge),c=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const s=document.createElement("canvas");return s.width=e,s.height=t,s}throw n("Canvas capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(s.width,s.height),d=c.getContext("2d");if(!d)throw n("Canvas 2d context is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1});d.drawImage(o.image,0,0,s.width,s.height);const l="image/png"===(a=e.mimeType)||"image/webp"===a?a:"image/jpeg",u=await(async(e,t,s)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:s});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((o,a)=>{e.toBlob(e=>{e?o(e):a(n("Image encode failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,s)});throw n("Canvas encode capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas encode unavailable"}})})(c,l,t.quality),h=(e=>e.name??"image")(e),p="undefined"!=typeof File?new File([u],h,{type:l,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:p??u,name:h,mimeType:l,size:p?.size??u.size},width:s.width,height:s.height,fileName:h,fileType:l,fileSize:p?.size??u.size,webFile:p}}finally{o.cleanup()}var a},async computeMd5(e){const t=tr(e),s=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw n("Binary read capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,s)=>{const o=new FileReader;o.onerror=()=>{s(n("Binary read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1}))},o.onload=()=>{o.result instanceof ArrayBuffer?t(o.result):s(n("Binary read returned invalid result",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1}))},o.readAsArrayBuffer(e)})})(t);return Zn(new Uint8Array(s))}}),nr=e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"errMsg"in e){const t=e.errMsg;if("string"==typeof t)return t}return String(e)},rr=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw n("Miniapp image processor only supports miniapp path source",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.path},ir=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw n("Miniapp file system capability is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"getFileSystemManager"}})},or=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},ar=async(e,t)=>new Promise((s,n)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{n(e instanceof Error?e:new Error(nr(e)))}})}).catch(e=>{throw n("Miniapp image info read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{src:t,cause:nr(e)}})}),cr=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,dr=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await ar(e,t);return cr(t,s)},lr=async(e,t,s)=>{if("function"==typeof e.getFileInfo)try{const n=await new Promise((n,r)=>{const i=setTimeout(()=>r(new Error("File digest timed out")),s),o=e=>{clearTimeout(i),e()};try{e.getFileInfo?.({filePath:t,digestAlgorithm:"md5",success:e=>o(()=>n(e)),fail:e=>o(()=>r(new Error(nr(e))))})}catch(a){o(()=>r(new Error(nr(a))))}});return"string"==typeof n.digest&&/^[a-f\d]{32}$/i.test(n.digest)?n.digest.toLowerCase():void 0}catch(o){throw n("Miniapp file digest failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{filePath:t,cause:nr(o)}})}},ur=e=>({async getImageInfo(t){const s=rr(t),n=await ar(e,s),r=or(n.type)??t.mimeType;return{width:n.width,height:n.height,mimeType:r,fileSize:t.size,isGif:"image/gif"===r}},async generateBigImage(t,s){const o=rr(t);if("function"!=typeof e.compressImage)throw n("Miniapp image compress capability is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"compressImage"}});const a=await ar(e,o),c=cr(o,a),d=((e,t,s)=>{const n=Math.min(e,t);if(n<=s)return{width:e,height:t};const r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}})(a.width,a.height,s.maxShortEdge),l=await new Promise((t,n)=>{e.compressImage?.({src:c,quality:Math.max(0,Math.min(100,Math.round(100*s.quality))),compressedWidth:d.width,compressedHeight:d.height,success:e=>{e.tempFilePath?t(e.tempFilePath):n(new Error("compressImage missing tempFilePath"))},fail:e=>{n(e instanceof Error?e:new Error(nr(e)))}})}).catch(e=>{throw n("Miniapp image compress failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{src:c,cause:nr(e)}})}),u=await dr(e,l),h=await ar(e,u),p=or(h.type)??t.mimeType,m=await(async(e,t,s)=>{const o=ir(e);return o.getFileInfo?new Promise((e,s)=>{o.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{s(e instanceof Error?e:new Error(nr(e)))}})}).catch(e=>{throw n("Miniapp file info read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{filePath:t,cause:nr(e)}})}):s})(e,u,t.size);return{source:{sourceType:"miniapp-path",path:u,name:t.name,mimeType:p,size:m},width:h.width,height:h.height,fileName:t.name,fileType:p,fileSize:m}},async computeMd5(t){const s=rr(t),o=await dr(e,s),c=e.getFileSystemManager?.(),d=Date.now()+a;let l;for(const n of[c,e]){if(!n)continue;const e=d-Date.now();if(e<=0)break;try{const t=await lr(n,o,e);if(t)return t}catch(h){l=h instanceof Error?h:new Error(nr(h))}}if(l&&"function"!=typeof c?.readFile)throw l;const u=await(async(e,t)=>{const s=ir(e);if("function"!=typeof s.readFile)throw n("Miniapp file read capability is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"FileSystemManager.readFile"}});const o=await new Promise((e,n)=>{s.readFile?.({filePath:t,success:t=>{e(t.data)},fail:e=>{n(e instanceof Error?e:new Error(nr(e)))}})}).catch(e=>{throw n("Miniapp file read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{filePath:t,cause:nr(e)}})});return o instanceof ArrayBuffer?new Uint8Array(o):"function"==typeof TextEncoder?(new TextEncoder).encode(o):Uint8Array.from(Array.from(o).map(e=>255&e.charCodeAt(0)))})(e,o);return Zn(u)}}),hr=/* @__PURE__ */new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),pr=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],mr=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},fr=e=>{if(!e)return!1;const t=mr(e,"name");if(t&&hr.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,mr(e,"message"),mr(e,"errMsg")].some(e=>null!==e&&pr.some(t=>t.test(e)))},gr=e=>{if(e instanceof Error)return e;const t=mr(e,"message")??mr(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},yr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ir=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),vr=e=>e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP,Cr=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),s=t.endsWith("==")?2:t.endsWith("=")?1:0,n=Math.max(0,Math.floor(3*t.length/4)-s),r=new Uint8Array(n);let i=0;for(let o=0;o<t.length;o+=4){const e=yr.indexOf(t[o]??""),s=yr.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:yr.indexOf(a),l="="===c?0:yr.indexOf(c);if(e<0||s<0||d<0||l<0)return new ArrayBuffer(0);const u=e<<18|s<<12|d<<6|l;for(const t of[16,8,0])i<n&&(r[i]=u>>t&255,i+=1)}return r.buffer},Er=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Sr=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Ar=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Er(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?Ar(s.data,t+1):e},Tr=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Sr(e);if(Er(e))try{return Sr(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Sr(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e))return e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)?Uint8Array.from(e):void 0;if("object"!=typeof e)return;const s=e;if("data"in s&&s.data!==e){const e=Tr(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=Tr(s.buffer,t+1);if(!e)return;const n="number"==typeof s.byteOffset&&Number.isInteger(s.byteOffset)?s.byteOffset:0,r="number"==typeof s.byteLength&&Number.isInteger(s.byteLength)?s.byteLength:e.byteLength-n;if(n<0||r<0||n+r>e.byteLength)return;return e.slice(n,n+r)}},br=(e,t)=>{if("string"==typeof e)return e;const s=e instanceof Uint8Array?e:new Uint8Array(e);if(vr(t)){const n=(e=>{let t="";for(let s=0;s<e.length;s+=3){const n=e[s]??0,r=e[s+1],i=e[s+2],o=n<<16|(r??0)<<8|(i??0);t+=yr[o>>18&63],t+=yr[o>>12&63],t+=void 0===r?"=":yr[o>>6&63],t+=void 0===i?"=":yr[63&o]}return t})(s);return c.warn("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:s.byteLength,encodedCharacters:n.length,sourcePrefixHex:Ir(s.subarray(0,8))}),n}const n=new ArrayBuffer(s.byteLength);return new Uint8Array(n).set(s),n},wr=(e,t)=>"string"!=typeof e&&vr(t),Nr=(e,t)=>{const s=Ar(e.data);if("string"==typeof s){if(!vr(t))return s;const n=Cr(s),r=new Uint8Array(n);return c.warn("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:s===e.data?"string":"wrapped-string",sourceCharacters:s.length,decodedBytes:n.byteLength,decodedPrefixHex:Ir(r.subarray(0,8)),decodedSuffixHex:Ir(r.subarray(Math.max(0,r.length-8)))}),n}const n=Tr(s);if(!n){const n="object"==typeof e.data&&null!==e.data?e.data:void 0;return void c.warn("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof s,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:n?Object.keys(n).slice(0,10):[],isBuffer:e.isBuffer})}if(!vr(t))return n.buffer;const r=(e=>{let t="";for(const n of e){if(9!==n&&10!==n&&13!==n&&32!==n&&!(n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||43===n||45===n||47===n||61===n||95===n))return;t+=String.fromCharCode(n)}const s=t.replace(/\s/g,"");if(0!==s.length&&s.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(s))return s})(n);if(!r)return c.warn("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(s),sourceBytes:n.byteLength,sourcePrefixHex:Ir(n.subarray(0,8))}),n.buffer;const i=Cr(r),o=new Uint8Array(i);return c.warn("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(s),sourceBytes:n.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:Ir(o.subarray(0,8)),decodedSuffixHex:Ir(o.subarray(Math.max(0,o.length-8)))}),i},Mr=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Rr=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],_r=e=>e instanceof Error?e.message:Mr(e)&&"string"==typeof e.errMsg?e.errMsg:Mr(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),Dr=e=>e?{...e}:{},Or=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,Ur=e=>Or(e.statusCode)?e.statusCode:Or(e.status)?e.status:void 0,Lr=e=>{if(!Mr(e))return{};const t={};return Object.entries(e).forEach(([e,s])=>{"string"==typeof s&&(t[e]=s)}),t},kr=e=>({...Lr(e.headers),...Lr(e.header)}),Pr=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},xr=e=>{try{e.close()}catch{}},Fr=(e,t)=>new Promise((s,o)=>{let a=!1,d=()=>{};const l=(e,s,c)=>{a||(a=!0,d(),o(n(e,{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:c,details:{url:t.url,method:"GET",cause:_r(s)}})))},u=e.downloadFile?.({url:t.url,header:Dr(t.headers),timeout:t.timeoutMs??15e3,success:n=>{const r=n.tempFilePath??n.apFilePath;r?((e,t)=>new Promise((s,n)=>{const r=e.getFileSystemManager?.();r?r.readFile({filePath:t,success:e=>{const t=Tr(e.data);t?s(t.buffer):n(new Error("downloaded file response is not binary"))},fail:n}):n(new Error("getFileSystemManager returned no file system manager"))}))(e,r).then(e=>{a||(a=!0,d(),c.warn("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:n.apFilePath?"apFilePath":"tempFilePath",status:n.statusCode??200,bytes:e.byteLength}),s({status:n.statusCode??200,headers:n.header??{},data:e}))}).catch(e=>{l("Mini program downloaded file read failed.",e,!1)}):l("Mini program download did not return a file path.",n,!1)},fail:e=>{l("Mini program file download failed.",e,!0)}});d=Pr(t.signal,()=>{u?.abort(),l("Mini program file download aborted.","abort",!1)})}),Br=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((s,o)=>{let a=()=>{};const c=e.request({url:t.url,method:t.method??"GET",header:Dr(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{a();const c=Ur(e);void 0!==c?s({status:c,headers:kr(e),data:e.data}):o(n("Mini program request response status is invalid.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{a(),o(n("Mini program request failed.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:_r(e)}}))}});a=Pr(t.signal,()=>{c.abort(),o(n("Mini program request aborted.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Fr(e,t)}),qr=(e,t)=>({connect:a=>new Promise((c,d)=>{let l,u,h=!1;const p=()=>{void 0!==u&&(clearTimeout(u),u=void 0)},m=(e,t,s)=>{h||(h=!0,p(),l&&xr(l),d(n(t,{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:s,details:{url:a.url,cause:_r(e)}})))},f=e=>{if(!(Rr(s=e,"send")&&Rr(s,"close")&&Rr(s,"onOpen")&&Rr(s,"onMessage")&&Rr(s,"onError")&&Rr(s,"onClose")))return void m(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var s;const a=e;if(h)return void xr(a);l=a;const d=()=>{a.offOpen?.(u),a.offError?.(f)},u=()=>{h?xr(a):(h=!0,p(),d(),c(((e,t,s=o.CONNECTING)=>{const a=/* @__PURE__ */new Set,c=/* @__PURE__ */new Set,d=/* @__PURE__ */new Set,l=/* @__PURE__ */new Set;let u=s;return e.onOpen(()=>{u=o.OPEN,a.forEach(e=>{e()})}),e.onMessage(e=>{const s=Nr(e,t);void 0!==s&&c.forEach(e=>{e(s)})}),e.onError(e=>{d.forEach(t=>{t(e)})}),e.onClose(e=>{u=o.CLOSED,l.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return u},send(s){if(u!==o.OPEN)throw n("Mini program socket is not open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{readyState:u}});return new Promise((o,a)=>{e.send({data:br(s,t),...wr(s,t)?{isBuffer:!0}:{},success:o,fail:e=>{a(n("Mini program socket send failed.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{cause:_r(e)}}))}})})},close(t,s){u=o.CLOSING,e.close({code:t,reason:s})},onOpen:e=>(a.add(e),()=>{a.delete(e)}),onMessage:e=>(c.add(e),()=>{c.delete(e)}),onError:e=>(d.add(e),()=>{d.delete(e)}),onClose:e=>(l.add(e),()=>{l.delete(e)})}})(a,t,o.OPEN)))},f=e=>{d(),m(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};a.onOpen(u),a.onError(f)};let g;"number"==typeof a.timeoutMs&&a.timeoutMs>0&&(u=setTimeout(()=>{m("timeout","Mini program socket connection timed out.",!0)},a.timeoutMs));try{g=e.connectSocket({url:a.url,...t===s.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(a.protocols)?[...a.protocols]:"string"==typeof a.protocols?[a.protocols]:void 0,fail:e=>{m(e,"Mini program socket connect failed.",!0)}})}catch(I){return void m(I,"Mini program socket creation failed.",!0)}var y;"object"!=typeof(y=g)||null===y||"function"!=typeof y.then?f(g):Promise.resolve(g).then(e=>f(e),e=>m(e,"Mini program socket connect failed.",!0))})}),Kr=e=>({upload(t){const s=t.method??"POST";return"POST"!==s?Promise.reject(n("Mini program upload only supports POST.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,method:s,reason:"unsupported-method"}})):new Promise((s,o)=>{const a=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw n("Mini program upload only supports miniapp-path source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let c=()=>{};const d=e.uploadFile({url:t.url,filePath:a.path,name:t.fileFieldName??"file",header:Dr(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{c();const d=Ur(e);void 0!==d?s({status:d,body:e.data}):o(n("Mini program upload response status is invalid.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,path:a.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{c(),o(n("Mini program upload failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!0,details:{url:t.url,path:a.path,cause:_r(e)}}))}});d.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),c=Pr(t.signal,()=>{d.abort(),o(n("Mini program upload aborted.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,path:a.path,reason:"abort"}}))})})}}),Gr=(e,t)=>{const n=(e=>e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP)(t);return{async getItem(t){if(Rr(e,"getStorageSync"))try{const s=(e=>Mr(e)&&"data"in e?e.data:e)(e.getStorageSync(n?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return Rr(e,"getStorage")?new Promise(s=>{e.getStorage({key:t,success:e=>{s("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{s(null)}})}):null},async setItem(t,s){if(Rr(e,"setStorageSync"))try{n?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(r){if(fr(r))throw gr(r)}else if(Rr(e,"setStorage"))return new Promise((n,i)=>{try{e.setStorage({key:t,data:s,success:n,fail:e=>{fr(e)?i(gr(e)):n()}})}catch(r){if(fr(r))return void i(gr(r));n()}})},async removeItem(t){if(Rr(e,"removeStorageSync"))try{e.removeStorageSync(n?{key:t}:t)}catch{}else if(Rr(e,"removeStorage"))return new Promise(s=>{try{e.removeStorage({key:t,success:s,fail:()=>{s()}})}catch{s()}})}}},Vr=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>Rr(e,"getNetworkType")?new Promise(t=>{e.getNetworkType?.({success:e=>{t(e.networkType??"unknown")},fail:()=>{t("unknown")}})}):Promise.resolve("unknown"),onNetworkChange(t){const s=e=>{t(e.isConnected)};return Rr(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),Rr(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{Rr(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},n=()=>{t(!1)};return Rr(e,"onAppShow")&&e.onAppShow(s),Rr(e,"onAppHide")&&e.onAppHide(n),t(!0),()=>{Rr(e,"offAppShow")&&e.offAppShow(s),Rr(e,"offAppHide")&&e.offAppHide(n)}}}),Hr=(e,t=s.WECHAT_MINIAPP,o=t)=>{const a=(e=>{if(Rr(e,"request")&&Rr(e,"connectSocket")&&Rr(e,"uploadFile"))return e;throw n("Mini program platform capability is missing.",{code:r.MISSING_CAPABILITY,stage:i.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),c="function"==typeof a.getImageInfo?ur(a):void 0;return{request:Br(a),socket:qr(a,o),upload:Kr(a),runtime:Vr(a,t),storage:Gr(a,o),imageProcessor:c}},zr=["request","upload","socket"],jr={request:"request",upload:"upload",socket:"connect"},Wr=[s.WEB,s.ELECTRON_RENDERER,s.REACT_NATIVE],Qr=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},$r=e=>Wr.includes(e),Yr=(e,t)=>e!==s.UNIAPP?$r(e):!an(t)&&!Xr(t)&&sn(t),Jr=e=>Qr(e,"getImageInfo")&&(Qr(e,"getFileSystemManager")||Qr(e,"getFileInfo")),Xr=e=>!an(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),Zr=(e,t)=>{if($r(e)&&e!==s.REACT_NATIVE)return sr();if(un(e)&&Jr(t))return ur(t);if(e===s.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(sn(e))return sr();if(Jr(e.uni))return ur(e.uni);if(Jr(e.wx))return ur(e.wx)}},ei=e=>{const t=e.localStorage;if(t)return{getItem:e=>Promise.resolve(t.getItem(e)),setItem:(e,s)=>(t.setItem(e,s),Promise.resolve()),removeItem:e=>(t.removeItem(e),Promise.resolve())};const s=/* @__PURE__ */new Map;return{getItem(e){const t=s.has(e)?s.get(e)??null:null;return Promise.resolve(t)},setItem:(e,t)=>(s.set(e,t),Promise.resolve()),removeItem:e=>(s.delete(e),Promise.resolve())}},ti=(e,t,n,r)=>{if(e===s.UNIAPP&&Xr(n)&&void 0!==n.uni&&Js(n.uni))return{...Hr(n.uni,e,t),proto:Rn()};if(((e,t)=>!Yr(e,t)&&un(e))(e,n)&&Js(r))return{...Hr(r,e,t),proto:Rn()};const i=n.XMLHttpRequest,o=Yr(e,n),a=o?d({fetchImpl:n.fetch}):void 0,c=o?Pn({webSocketCtor:n.WebSocket}):void 0,l=e===s.REACT_NATIVE?Vn({fetchImpl:n.fetch,formDataCtor:n.FormData}):o?Kn({xhrFactory:"function"==typeof i?()=>new i:void 0,fetchImpl:n.fetch}):void 0,u=o&&e!==s.REACT_NATIVE?(h={platform:e,windowRef:n.window,documentRef:n.document,navigatorRef:n.navigator},{getPlatform:()=>h.platform,getNetworkType:()=>!1===h.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(h.navigatorRef?.connection?.type??h.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=h.windowRef;if(!t)return()=>{};const s=()=>{e(!0)},n=()=>{e(!1)};return t.addEventListener("online",s),t.addEventListener("offline",n),"boolean"==typeof h.navigatorRef?.onLine&&e(h.navigatorRef.onLine),()=>{t.removeEventListener("online",s),t.removeEventListener("offline",n)}},onAppVisibilityChange(e){const t=h.documentRef;if(!t)return()=>{};const s=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",s),s(),()=>{t.removeEventListener("visibilitychange",s)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var h;return{request:a,upload:l,socket:c,runtime:u,proto:Rn(),storage:ei(n),imageProcessor:o&&e!==s.REACT_NATIVE?sr():Zr(e,r)}},si=(e,t,s)=>{if(!t)return{...e,...s};const o=zr.filter(e=>void 0!==s[e]);if(o.length>0)throw n("Transport adapter conflicts with network overrides.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{conflictingCapabilities:o}});const a=(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(s);return{...e,request:t.request,upload:t.upload,socket:t.socket,...a}},ni=(e,t)=>{if(void 0!==e)return e;throw n("Platform adapter initialization failed.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{capability:t}})},ri=(e,t)=>ln(t,e).platform,ii=e=>{(e=>{if(!e)return;const t=zr.flatMap(t=>{const s=jr[t];return Qr(e[t],s)?[]:[`${t}.${s}`]});if(0!==t.length)throw n("Transport adapter has invalid capabilities.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{source:"transportAdapter",invalidCapabilities:t}})})(e?.transportAdapter);const s=t(e?.runtimeInput),o=ln(s,e?.prefer),a=o.platform,c=ti(a,o.hostPlatform,s,o.global),d=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,c),l=si(c,e?.transportAdapter,d),u=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(l);pn(u);return{platform:a,platformId:a,capability:u,request:ni(l.request,"request"),upload:ni(l.upload,"upload"),socket:ni(l.socket,"socket"),runtime:ni(l.runtime,"runtime"),proto:ni(l.proto,"proto"),storage:ni(l.storage,"storage"),imageProcessor:l.imageProcessor}},oi=e=>{if(e)return e;const s=t(),o=Pn({webSocketCtor:s.WebSocket});if(o)return o;throw n("Socket capability is missing for current platform.",{code:r.MISSING_CAPABILITY,stage:i.SOCKET,retryable:!1,details:{capability:"socket"}})},ai={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class ci{constructor(e={}){this.attemptCount=0,this.config={...ai,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),s=Math.min(t,this.config.maxDelay);return s/2+s/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return c.debug(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const di={interval:3e4,timeout:6e4},li="function"==typeof TextDecoder?new TextDecoder:null;class ui{constructor(e={}){this.websocket=null,this.heartbeatTimer=null,this.timeoutTimer=null,this.lastPongTime=0,this.onTimeoutCallback=null,this.sendPing=null,this.probeResolvers=[],this.messageDisposer=null,this.handlePong=e=>{const t=this.extractMessageText(e);if(!t)return;const s=this.parseJson(t);if(!ui.isRecord(s))return;"pong"===ui.readString(s.type)&&(this.markAlive(),c.debug("Pong received"))},this.config={...di,...e}}start(e,t,s){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=s??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),c.debug("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),c.debug("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===o.OPEN)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{c.error("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),c.debug("Ping sent")}catch(e){c.error("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?li?.decode(t)??qe(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{c.warn("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==o.OPEN)return!1;this.attachWebSocket(e);const s=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},s);this.probeResolvers.push(s=>{clearTimeout(t),e(s)}),this.sendPingInternal()})}catch(s){return c.warn("Heartbeat probe failed",s),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const s of t)s(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}let hi=null;function pi(){return hi||(hi=Mn()),hi}const mi=(e,t)=>{for(const s of[e,t])if(s&&"object"==typeof s&&"name"in s&&"string"==typeof s.name&&s.name.length>0)return s.name;return""},fi=/* @__PURE__ */new Set(["mute"]),gi={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},yi=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Ii=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},vi=(e,t)=>{const s=e?.map(e=>yi(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Ci=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=Ii(t);if(!n)return;const r=n.muteExpire??n.mute_expire??n.expire??n.expired??n.expireAt??n.expiredAt,i=Number(r);return Number.isFinite(i)&&i>0?i:void 0},Ei=e=>{const t=Ii(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=gi[n];if(!e)continue;let t=r;if(fi.has(n))t=!0===r||"true"===r;else if("max_users"===n){const e=Number(r);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},Si=e=>{const t=Ii(e);if(!t)return{attributes:{},keyList:[]};const s=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},n=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},r=Array.isArray(s.successKeys)?s.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(r.map(e=>[e,n[e]]).filter(e=>"string"==typeof e[1])),keyList:r,from:yi(t.operator)??yi(t.username)}},Ai=(e,t)=>({eventName:e,payload:t}),Ti=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=yi(e.from?.name),n=(r=e.to,yi(r?.[0]?.name));var r;switch(e.operation){case 1:return Ai(ys,t);case 10:return Ai(Cs,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:n??s});case 17:return Ai(Is,{...t,memberIds:vi(e.members,s),ext:e.ext??e.eventExt});case 18:return Ai(vs,{...t,memberIds:vi(e.members,s)});case 20:return Ai(Ms,{...t,oldOwnerId:s,newOwnerId:n});case 21:return Ai(ws,{...t,adminId:n??s});case 22:return Ai(Ns,{...t,adminId:n??s});case 23:{const s=(e=>{const t=Ii(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const n={};for(const[r,i]of Object.entries(s)){const e=Number(i);r&&Number.isFinite(e)&&(n[r]=e)}return Object.keys(n).length>0?n:null})(e.ext??e.eventExt),r=s?Object.keys(s):vi(e.members,n),i=46388736e5;return Ai(Es,{...t,userIds:r,muteMembers:s??Object.fromEntries(r.map(e=>[e,i])),muteExpire:Ci(e.reason,e.eventExt)??i})}case 24:return Ai(Ss,{...t,userIds:vi(e.members,n)});case 25:return Ai(Rs,{...t,announcement:e.reason??""});case 26:return Ai(Rs,{...t,announcement:""});case 29:return Ai(As,{...t,userIds:vi(e.members,n)});case 30:return Ai(Ts,{...t,userIds:vi(e.members,n)});case 31:return Ai(bs,{...t,isMuted:!0});case 32:return Ai(bs,{...t,isMuted:!1});case 14:return Ai(_s,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Ei(e.eventExt)});case 43:{const n=Si(e.eventExt);return Ai(Ds,{...t,attributes:n.attributes,from:n.from??s})}case 44:{const n=Si(e.eventExt);return Ai(Os,{...t,keyList:n.keyList,from:n.from??s})}default:return null}},bi=/* @__PURE__ */new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),wi={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Ni=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Mi=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Ri=(e,t)=>{const s=e?.map(e=>Ni(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},_i=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=Mi(t);if(!n)return;const r=n.muteExpire??n.mute_expire??n.expire??n.expired??n.expireAt??n.expiredAt,i=Number(r);return Number.isFinite(i)&&i>0?i:void 0},Di=e=>{const t=Mi(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=wi[n];if(!e)continue;let t=r;if(bi.has(n))t=!0===r||"true"===r;else if("max_users"===n){const e=Number(r);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},Oi=(e,t)=>{const s=Mi(t)??Mi(e);return qt(s??void 0)??void 0},Ui=(e,t)=>{const s=Mi(t)??Mi(e);return Ni(s?.fileId)??Ni(s?.file_id)??Ni(e)??""},Li=(e,t)=>({eventName:e,payload:t}),ki=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=Ni(e.from?.name),n=(r=e.to,Ni(r?.[0]?.name));var r;switch(e.operation){case 4:return Li(Lt.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return Li(Lt.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return Li(Lt.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:n,reason:e.reason});case 7:return Li(Lt.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return Li(Lt.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return Li(Lt.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return Li(Lt.USER_REMOVED,t);case 1:return Li(Lt.GROUP_DESTROYED,t);case 19:return Li(Lt.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=Mi(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const n={};for(const[r,i]of Object.entries(s)){const e=Ni(r),t=Number(i);e&&Number.isFinite(t)&&t>0&&(n[e]=t)}return Object.keys(n).length>0?n:null})(e.ext),r=s?Object.keys(s):Ri(e.members,n);return Li(Lt.MUTE_LIST_ADDED,{...t,userIds:r,muteExpire:r.map(e=>s?.[e]).find(e=>void 0!==e)??_i(e.reason,e.eventExt)})}case 24:return Li(Lt.MUTE_LIST_REMOVED,{...t,userIds:Ri(e.members,n)});case 29:return Li(Lt.ALLOW_LIST_ADDED,{...t,userIds:Ri(e.members,n)});case 30:return Li(Lt.ALLOW_LIST_REMOVED,{...t,userIds:Ri(e.members,n)});case 31:return Li(Lt.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return Li(Lt.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return Li(Lt.ADMIN_ADDED,{...t,administratorId:n??s});case 22:return Li(Lt.ADMIN_REMOVED,{...t,administratorId:n??s});case 20:return Li(Lt.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:n});case 17:{const n=Ri(e.members,s);return Li(Lt.MEMBERS_JOINED,{...t,memberIds:n})}case 18:{const n=Ri(e.members,s);return Li(Lt.MEMBERS_EXITED,{...t,memberIds:n})}case 25:return Li(Lt.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return Li(Lt.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return Li(Lt.SHARED_FILE_ADDED,{...t,sharedFile:Oi(e.reason,e.eventExt)});case 28:return Li(Lt.SHARED_FILE_DELETED,{...t,fileId:Ui(e.reason,e.eventExt)});case 14:return Li(Lt.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:Di(e.eventExt)});case 41:return Li(Lt.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Li(Lt.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const n=(e=>{const t=Mi(e);if(!t)return{attribute:{}};const s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Object.fromEntries(Object.entries(s).filter(e=>"string"==typeof e[1]));return{userId:Ni(t.username),attribute:n}})(e.eventExt);return Li(Lt.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:n.userId,attribute:n.attribute,from:s,source:e.source??"direct"})}default:return null}},Pi=/* @__PURE__ */new WeakMap,xi=(e,t)=>{Pi.set(e,t)},Fi=e=>Pi.get(e)??null,Bi=(e,t)=>{const s=Fi(e);s&&xi(t,s)},qi=/* @__PURE__ */new WeakMap,Ki=e=>qi.get(e),Gi="singleChat",Vi="groupChat",Hi={MARK_0:0,MARK_1:1,MARK_2:2,MARK_3:3,MARK_4:4,MARK_5:5,MARK_6:6,MARK_7:7,MARK_8:8,MARK_9:9,MARK_10:10,MARK_11:11,MARK_12:12,MARK_13:13,MARK_14:14,MARK_15:15,MARK_16:16,MARK_17:17,MARK_18:18,MARK_19:19},zi=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ji=e=>{if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&e.trim().length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},Wi=e=>{if(!Array.isArray(e))return;const t=e.map(e=>zi(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},Qi=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),$i=(...e)=>{for(const t of e){const e=zi(t);if(e)return e}},Yi=(e,t)=>Boolean(e&&t&&e===t),Ji=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),Xi=(e,t,s)=>{const n=Wi(e);if(n&&n.length>0)return n;const r=(t??[]).map(e=>zi(e.name)).filter(e=>"string"==typeof e);if(r.length>0)return r;const i=zi(s?.name);return i?[i]:[]},Zi=e=>{const t=ji(e);if(void 0!==t)return t;if("string"==typeof e){const t=e.match(/(\d+)/);if(t){const e=Number(t[1]);return Number.isFinite(e)?e:void 0}}},eo=(e,t)=>{const s=$i(e.to?.[0]?.clientResource);if(1!==e.to?.length||zi(e.to[0]?.name)!==t.userId||!Ji(t.userId,s,t))return null;const n=(r=e.from,zi(r?.name)??"");var r;if(!n)return c.warn("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return c.warn("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:n,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:s,timestamp:e.timestamp,raw:e.raw}},to=(e,t)=>{if(!e.groupId)return c.warn("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const s=$i(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Ji(zi(e.from?.name),s,t))return null;const n=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return c.warn("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===n)return null;const r=Xi(e.members,e.to,e.from);return{category:"group",operation:n,groupId:e.groupId,userIds:r.length>0?r:void 0,operatorId:zi(e.from?.name),groupName:e.groupName,deviceId:s,timestamp:e.timestamp,raw:e.raw}},so=(e,t)=>{if(!e.threadId)return c.warn("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const s=$i(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Ji(zi(e.from?.name),s,t))return null;const n=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return c.warn("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===n)return null;const r=Xi(e.members,e.to,e.from);return{category:"thread",operation:n,threadId:e.threadId,parentId:e.parentId,userIds:r.length>0?r:void 0,operatorId:zi(e.from?.name),threadName:e.threadName,deviceId:s,timestamp:e.timestamp,raw:e.raw}},no=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const s=$i(e.res,e.raw?.resource,e.raw?.clientResource);if(Yi(s,t.clientResource))return c.debug("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const n="chat"===(r=e.type)||"singleChat"===r?Gi:Vi;var r;const i=zi(e.id)??(n===Gi?zi(e.from):void 0);if(!i)return c.warn("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return c.warn("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:n,mark:"mark"===e.operation||"mark_delete"===e.operation?Zi(e.ext):void 0,operatorId:zi(e.from),deviceId:s,timestamp:ji(e.ts),raw:e.raw}},ro=(e,t)=>{const s=$i(e.resource,e.raw?.resource,e.raw?.clientResource);if(Yi(s,t.clientResource))return c.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const n=zi(e.to);if(!n)return c.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const r=zi(e.lastMsgId),i=Wi(e.msgIdList)??(r?[r]:void 0),o=ji(e.deleteTime);if(!i&&void 0===o)return c.warn("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:n}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(c.warn("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===a?null:{category:"messageRemoved",operation:a,conversationId:n,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?Vi:Gi,messageIds:i,beforeTimestamp:o,deviceId:s,raw:e.raw}},io=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var oo=4096,ao=65547,co=15,lo=2113929216,uo=65536,ho=65536,po=10485760,mo={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},fo={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function go(e){if(!(e>0))return ho;if(e<=ho)return ho;if(e>1073741823)return e;for(var t=ho;t<e;)t*=2;return t}var yo={byU16:0,byU32:1},Io=0,vo=1,Co=2,Eo=0,So=1;function Ao(e,t){return e[t]|e[t+1]<<8}function To(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function bo(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var wo="fast";function No(e){return 2654435761*(e>>>0)>>>20&4095}function Mo(e){return 2654435761*(e>>>0)>>>19&8191}function Ro(e,t,s){if("fast"===wo){var n=To(e,t);return s===yo.byU16?Mo(n):No(n)}throw new Error("Unsupported hash strategy: "+wo)}function _o(e,t,s,n,r){s[t]=e-r}function Do(e,t,s,n,r){_o(t,Ro(e,t,n),s,0,r)}function Oo(e,t,s,n){return t[e]+n}function Uo(e,t,s,n,r){return Oo(Ro(e,t,n),s,0,r)}function Lo(e,t,s,n){for(var r=t;t<n-3;){if(To(e,t)!==To(e,s)){for(;t<n&&e[t]===e[s];)t++,s++;return t-r}t+=4,s+=4}for(;t<n&&e[t]===e[s];)t++,s++;return t-r}function ko(e,t,s,n,r,i,o,a,c,d){var l,u,h,p=e.hashTable,m=n,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,I=y+e.dictSize,v=e.dictSize>0?I-n:0,C=n,E=n+r,S=E-12,A=E-5,T=0,b=i>0?i:s.length,w=0;if(r>lo)return 0;switch(c){case Io:default:l=n,u=n;break;case vo:l=n-e.currentOffset,u=n-e.dictSize;break;case Co:l=n-e.currentOffset,u=n}if(a===yo.byU16&&r>=ao)return 0;if(r<13)return Fo(t,s,C,E,T,b,o);Do(t,m,p,a,l),h=Ro(t,++m,a);e:for(;;){var N,M,R=m,_=1,D=64;do{var O=h;if(m=R,R+=_,_=D++>>>6,R>S)return Fo(t,s,C,E,T,b,o);N=Oo(O,p,0,l),c===Co&&(N<n?(w=v,u=y):(w=0,u=n)),h=Ro(t,R,a),_o(m,O,p,0,l)}while(d===So&&N<f||a!==yo.byU16&&N+65535<m||!Po(t,g,m,N,w,c,n));for(;m>C&&N+w>u;){var U=N+w-1;if(t[m-1]!==(c===Co&&N<n?g[U-y+e.dictionaryStart]:t[U]))break;m--,N--}var L=m-C;if(M=T++,o&&T+L+8+Math.floor(L/255)>b)return 0;if(L>=co){var k=L-co;for(s[M]=240;k>=255;)s[T++]=255,k-=255;s[T++]=k}else s[M]=L<<4;if(L>=16&&s.set&&t.subarray)s.set(t.subarray(C,C+L),T),T+=L;else for(var P=0;P<L;P++)s[T++]=t[C+P];t:for(;;){var x;if(bo(s,T,m-N),T+=2,c===Co&&N<n){var F=m+(I-(N+w));if(F>A&&(F=A),(m+=4+(x=xo(t,g,m+4,N+w+4-y+e.dictionaryStart,F,I-y)))===F&&F<A){var B=Lo(t,m,n,A);x+=B,m+=B}}else m+=4+(x=Lo(t,m+4,N+4,A));if(o&&T+6+(x>>>8)>b)return 0;if(x>=15){for(s[M]+=15,x-=15;x>=510;)s[T++]=255,s[T++]=255,x-=510;x>=255&&(x-=255,s[T++]=255),s[T++]=x}else s[M]+=x;if(C=m,m>S)break e;if(Do(t,m-2,p,a,l),N=Uo(t,m,p,a,l),c===Co&&(N<n?(w=v,u=y):(w=0,u=n)),Do(t,m,p,a,l),!((d!==So||N>=f)&&N+65535>=m&&Po(t,g,m,N,w,c,n)))break t;s[M=T++]=0}h=Ro(t,++m,a)}return Fo(t,s,C,E,T,b,o)}function Po(e,t,s,n,r,i,o){var a,c=To(e,s);i===Co&&n+r<o?a=To(t,n+r):a=To(e,n+r);return c===a}function xo(e,t,s,n,r,i,o){for(var a=s;n<i&&s<r&&t[n]===e[s];)n++,s++;return s-a}function Fo(e,t,s,n,r,i,o){var a=n-s;if(o&&r+a+1+Math.floor((a+255-co)/255)>i)return 0;if(a>=co){for(t[r++]=240,a-=co;a>=255;)t[r++]=255,a-=255;t[r++]=a}else t[r++]=a<<4;var c=s,d=n,l=d-c;if(l>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),r),r+=l;else for(var u=c;u<d;u++)t[r++]=e[u];return r}function Bo(e,t,s,n){var r,i=0;if(n&&t.ip>=s)return-1;do{if(i+=r=e[t.ip++],t.ip>s)return-1;if(i>2147483647)return-1}while(255===r);return i}function qo(e,t,s,n,r,i,o,a,c,d,l,u,h){if(null==e)return-1;if(i<0)return-1;var p=s,m=s+n,f=r,g=r+i,y=l-h,I=u+h,v=h<65536;if(0===i)return 1===n&&0===e[p]?0:-1;if(0===n)return-1;for(;;){var C,E,S,A;if(p>=m)return-(p-s)-1;if((E=(C=e[p++])>>>4)===co){var T=Bo(e,N={ip:p},m-co,!0);if(p=N.ip,-1===T)return-(p-s)-1;if(f+(E+=T)<f)return-(p-s)-1;if(p+E<p)return-(p-s)-1}if(S=f+E,o&&(S>g-12||p+E>m-8)||!o&&S>g-8){if(!o&&S!==g)return-(p-s)-1;if(o&&(p+E!==m||S>g))return-(p-s)-1;if(E>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+E),f);else for(var b=0;b<E;b++)t[f+b]=e[p+b];p+=E,f+=E;break}if(E>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+E),f);else for(b=0;b<E;b++)t[f+b]=e[p+b];if(f=S,(p+=E)+2>m)return-(p-s)-1;var w=Ao(e,p);if(p+=2,A=S-w,v&&A+h<l)return-(p-s)-1;if(0===w)return-(p-s)-1;if(15===(E=15&C)){var N;T=Bo(e,N={ip:p},m-5+1,!1);if(p=N.ip,-1===T)return-(p-s)-1;if(f+(E+=T)<f)return-(p-s)-1}if(E+=4,d===Co&&A<l){if(f+E>g-5)return-(p-s)-1;if(E<=l-A){var M=I-(l-A);for(b=0;b<E;b++)t[f+b]=t[M+b];f+=E}else{var R=l-A;for(M=I-R,b=0;b<R;b++)t[f+b]=t[M+b];var _=E-R;if(_>(f+=R)-l)for(var D=l,O=f+_;f<O;)t[f++]=t[D++];else{for(b=0;b<_;b++)t[f+b]=t[l+b];f+=_}}}else{if(A<y)return-(p-s)-1;if(S=f+E,f-A<8)for(t[f]=t[A],t[f+1]=t[A+1],t[f+2]=t[A+2],t[f+3]=t[A+3],f+=4,A+=4;f<S;)t[f++]=t[A++];else for(;f<S;)t[f++]=t[A++]}}return o?f-r:p-s}function Ko(){return{hashTable:new Uint32Array(oo),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function Go(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function Vo(e,t,s,n,r,i,o,a){n=n||0;var c=e.dictionaryStart+e.dictSize,d=n;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,s=e.dictionaryStart+e.dictSize,n=0;n<e.hashTable.length;n++)e.hashTable[n]<t?e.hashTable[n]=0:e.hashTable[n]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=s-e.dictSize}}(e);var l,u=n+r;e.dictionary&&u>e.dictionaryStart&&u<c&&(e.dictSize=c-u,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var h=e.dictSize<65536&&e.dictSize<e.currentOffset?So:Eo;return e.dictionary&&c===n?(l=ko(e,t,s,n,r,o||0,a||!1,yo.byU32,vo,h),e.dictSize+=r,e.currentOffset+=r,l):(l=ko(e,t,s,n,r,o||0,a||!1,yo.byU32,Co,h),e.dictionary=t,e.dictionaryStart=n,e.dictSize=r,e.currentOffset+=r,l)}function Ho(e,t,s,n){var r=e.dictionaryStart+e.dictSize;n>65536&&(n=65536),n>e.dictSize&&(n=e.dictSize);var i=r-n;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(i,i+n),s);else for(var o=0;o<n;o++)t[s+o]=e.dictionary[i+o];return e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,n}function zo(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function jo(e,t,s,n){return e.prefixSize=n,e.prefixEnd=s+n,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function Wo(e,t,s,n,r,i,o){var a;if(e.prefixEnd===i){if((a=qo(t,s,n,r,i,o,!0,0,0,Co,e.prefixEnd-e.prefixSize,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize+=a,e.prefixEnd+=a}else{if(e.extDictSize=e.prefixSize,e.extDictStart=e.prefixEnd-e.extDictSize,(a=qo(t,s,n,r,i,o,!0,0,0,Co,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function Qo(e){var t=(e=e||{}).minWorkArea||ho,s=e.maxWorkArea||po,n=e.shrinkThreshold||t;t<ho&&(t=ho),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=uo+t,this.maxBufferSize=uo+s,this.shrinkThreshold=uo+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:mo.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=Ko()}function $o(e){var t=(e=e||{}).minWorkArea||ho,s=e.maxWorkArea||po,n=e.shrinkThreshold||t;t<ho&&(t=ho),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=uo+t,this.maxBufferSize=uo+s,this.shrinkThreshold=uo+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:mo.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Qo.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<uo?this.offset:uo,r=this.offset>uo?this.offset-uo:0;t.set(this.ringBuffer.subarray(r,r+n),0),Ho(this.stream,t,0,n),s=n}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Qo.prototype.compress=function(e,t){var s=e.length;if(s<=0)return fo.PARAM_ERROR;if(s>this.maxBufferSize-uo)return fo.PARAM_ERROR;if(s>this.ringBufferSize-uo){var n=go(s),r=uo+n;if(r>this.maxBufferSize&&(r=this.maxBufferSize),!this._resizeBuffer(r))return fo.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(Ho(this.stream,this.ringBuffer,0,uo),this.offset=uo);var i=this.offset;this.ringBuffer.set(e,i);var o=Vo(this.stream,this.ringBuffer,t,i,s,0,t.length,!0);return o<=0?fo.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),o)},Qo.prototype.reset=function(){this.offset=0,Go(this.stream)},Qo.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Qo.prototype._tryAutoShrink=function(){this.shrinkMode!==mo.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===mo.AUTO_IMMEDIATE||this.shrinkMode===mo.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Qo.prototype.getWorkArea=function(){return this.ringBufferSize-uo},Qo.prototype.getRingBufferSize=function(){return this.ringBufferSize},Qo.prototype.getBaseBufferSize=function(){return this.minBufferSize},Qo.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Qo.prototype.getCurrentOffset=function(){return this.offset},Qo.prototype.getShrinkMode=function(){return this.shrinkMode},Qo.prototype.setShrinkMode=function(e){this.shrinkMode=e},Qo.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Qo.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-uo,s=this.maxBufferSize-uo;if(e<t||e>s)return fo.PARAM_ERROR;this.shrinkThreshold=uo+e},$o.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<uo?this.offset:uo,r=this.offset>uo?this.offset-uo:0;t.set(this.ringBuffer.subarray(r,r+n),0),s=n,jo(this.streamDecode,0,0,n)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},$o.prototype.decompress=function(e,t,s){var n=e.length;if(n<=0||s<=0)return fo.PARAM_ERROR;if(s>this.maxBufferSize-uo)return fo.PARAM_ERROR;if(s>this.ringBufferSize-uo){var r=go(s),i=uo+r;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return fo.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var o=this.offset-uo;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+uo),0),jo(this.streamDecode,this.ringBuffer,0,uo),this.offset=uo}var a=Wo(this.streamDecode,e,this.ringBuffer,0,n,this.offset,s);return a<=0?fo.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},$o.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},$o.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},$o.prototype._tryAutoShrink=function(){this.shrinkMode!==mo.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===mo.AUTO_IMMEDIATE||this.shrinkMode===mo.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},$o.prototype.getWorkArea=function(){return this.ringBufferSize-uo},$o.prototype.getRingBufferSize=function(){return this.ringBufferSize},$o.prototype.getBaseBufferSize=function(){return this.minBufferSize},$o.prototype.getMaxBufferSize=function(){return this.maxBufferSize},$o.prototype.getCurrentOffset=function(){return this.offset},$o.prototype.getShrinkMode=function(){return this.shrinkMode},$o.prototype.setShrinkMode=function(e){this.shrinkMode=e},$o.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},$o.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-uo,s=this.maxBufferSize-uo;if(e<t||e>s)return fo.PARAM_ERROR;this.shrinkThreshold=uo+e};const Yo={LZ4_MAX_INPUT_SIZE:lo,BLOCK_MAX_SIZE:65536,DICT_SIZE:uo,DEFAULT_WORK_AREA:ho,DEFAULT_MAX_WORK:po,SHRINK_MODE:mo,LZ4_ERROR:fo,alignToPowerOf2:go,calcDefaultBufferSize:function(){return 131072},calcDefaultMaxBufferSize:function(){return 10551296},setHashStrategy:function(e){if("fast"!==e&&"compatible"!==e)throw new Error("Invalid hash strategy: "+e+'. Use "fast" or "compatible".');wo=e},getHashStrategy:function(){return wo},compress:function(e,t,s,n,r){if(null==e)return 0;if(null==t)return 0;if(s=s||0,n=void 0===n?e.length:n,r=r||0,s<0||r<0)return 0;if(n<0)return 0;if(s+n>e.length)return 0;if(n>lo)return 0;if(0===n)return t.length>r?(t[r]=0,1):0;var i=n<ao?yo.byU16:yo.byU32;return ko({hashTable:new Uint32Array(i===yo.byU16?8192:oo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,0,!1,i,Io,Eo)},compressLimited:function(e,t,s,n,r,i){if(null==e)return 0;if(null==t)return 0;if(s=s||0,n=void 0===n?e.length:n,r=r||0,s<0||r<0)return 0;if(n<0||i<0)return 0;if(s+n>e.length)return 0;if(n>lo)return 0;if(i<1)return 0;if(0===n)return t[r]=0,1;var o=n<ao?yo.byU16:yo.byU32;return ko({hashTable:new Uint32Array(o===yo.byU16?8192:oo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,i,!0,o,Io,Eo)},compressBound:function(e){return e<0||e>lo?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,s,n,r,i){return null==e||null==t?-1:(r=r||0,(s=s||0)<0||r<0||n<0||i<0||s+n>e.length||r+i>t.length?-1:qo(e,t,s,n,r,i,!0,0,0,Io,r,null,0))},decompressFast:function(e,t,s,n,r){return qo(e,t,s=s||0,0,n=n||0,r,!1,0,0,vo,n-65536,0,65536)},createStream:Ko,resetStream:Go,loadDict:function(e,t,s,n){if(e.initCheck&&Go(e),n<4)return e.dictionary=null,e.dictSize=0,0;n>65536&&(s=s+n-65536,n=65536);var r=s-e.currentOffset;e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n;for(var i=s,o=s+n;i<=o-4;)Do(t,i,e.hashTable,yo.byU32,r),i+=3;return n},compressContinue:Vo,saveDict:Ho,createStreamDecode:zo,setStreamDecode:jo,decompressSafeContinue:Wo,RingBufferEncoder:Qo,RingBufferDecoder:$o,_hashU16:Mo,_hashU32:No,_TABLE_TYPE:yo},Jo=268435455,Xo=new Uint32Array(256);let Zo=!1;function ea(e){!function(){if(!Zo){for(let e=0;e<256;e+=1){let t=e;for(let e=0;e<8;e+=1)t=1&t?3988292384^t>>>1:t>>>1;Xo[e]=t>>>0}Zo=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const n=e[s]??0;t=t>>>8^(Xo[255&(t^255&n)]??0)}return(4294967295^t)>>>0}var ta=/* @__PURE__ */(e=>(e[e.NONE=-1]="NONE",e[e.UPLINK_ONLY=0]="UPLINK_ONLY",e[e.DOWNLINK_ONLY=1]="DOWNLINK_ONLY",e[e.BIDIRECTIONAL=2]="BIDIRECTIONAL",e))(ta||{});const sa=268435455;class na{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Yo.DEFAULT_WORK_AREA,maxWorkArea:Yo.DEFAULT_MAX_WORK,shrinkMode:Yo.SHRINK_MODE.MANUAL};this.encoder=new Yo.RingBufferEncoder(e),this.decoder=new Yo.RingBufferDecoder(e)}compress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length>sa)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=Yo.compressBound(t.length),n=new Uint8Array(s),r=this.encoder.compress(t,n);if(r<0)throw new Error(`LZ4 compression failed with error code: ${r}`);const i=n.subarray(0,r),o=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>Jo)throw new Error("encodeLength: Length exceeds maximum: 268435455");if(0===e)return new Uint8Array([0]);const t=[];let s=e;for(;s>0;){let e=127&s;s>>>=7,s>0&&(e|=128),t.push(e)}return new Uint8Array(t)}(t.length),a=ea(t),c=new Uint8Array(o.length+4+r);let d=0;c.set(o,d),d+=o.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(i,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const s={offset:0},n=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let s=0,n=0;for(;t.offset<e.length;){const r=e[t.offset]??0;if(t.offset+=1,s|=(127&r)<<n,!(128&r))return s>>>0;if(n+=7,n>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,s);if(n>sa)throw new Error(`Original size exceeds maximum allowed: ${n}`);if(t.length<s.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const r=new DataView(t.buffer,t.byteOffset+s.offset,4).getUint32(0,!1);s.offset+=4;const i=t.subarray(s.offset),o=new Uint8Array(n),a=this.decoder.decompress(i,o,n);if(a<0||a!==n)throw new Error(`LZ4 decompression failed: expected ${n}, got ${a}`);const c=ea(o);if(c!==r)throw new Error(`CRC32 checksum mismatch: expected ${r}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const ra=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ia=(e,t)=>Ot(e,t).finish();class oa{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Ke({useFixedDeviceId:e.useFixedDeviceId??!0,deviceId:e.deviceId??"webim",customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform}),s=`${Date.now()}:`;return{appKey:e.appKey,userId:e.userId,token:e.token,domain:e.domain??"easemob.com",version:e.version??"4.11.0",uiKitVersion:e.uiKitVersion,osType:void 0!==e.customOSPlatform?5:e.osType??16,deviceId:t.deviceId,deviceName:t.deviceName,deviceUuid:t.deviceUuid,clientResource:t.deviceId,customOSPlatform:e.customOSPlatform,loginExtensionInfo:e.loginExtensionInfo,encryptType:[Ve.ENCRYPT_NONE],compressType:[Ge.COMPRESS_NONE],sessionId:s,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.payloadDecoder=new He(this.context.userId,e.useCustomAttachmentUpload??!1)}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=pi(),t=e.lookupType("easemob.pb.Provision"),s=e.lookupType("easemob.pb.MSync"),n={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Ge.COMPRESS_NONE],encryptType:[Ve.ENCRYPT_NONE],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},r=ia(t,n),i={version:0,guid:ze({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:st.PROVISION,deviceId:0,encryptType:[Ve.ENCRYPT_NONE],payload:r,traceId:l()};return ia(s,i)}encodeHeartbeat(){const e=pi(),t=e.lookupType("easemob.pb.CommUnreadUL"),s=e.lookupType("easemob.pb.MSync"),n=ia(t,{}),r={version:0,encryptType:[Ve.ENCRYPT_NONE],command:st.UNREAD,payload:n,traceId:l()};return ia(s,r)}encodeStatisticRebuild(){const e=pi(),t=e.lookupType("easemob.pb.StatisticsBody"),s=e.lookupType("easemob.pb.Meta"),n=e.lookupType("easemob.pb.CommSyncUL"),r=e.lookupType("easemob.pb.MSync"),i=ia(t,{operation:0}),o=s.decode(new Uint8Array);o.id=Date.now(),o.ns=je.STATISTIC,o.payload=i;const a=n.decode(new Uint8Array);a.meta=o;const c=ia(n,a);return ia(r,{version:0,encryptType:[Ve.ENCRYPT_NONE],command:st.SYNC,payload:c,traceId:l()})}decodeProvision(e){const t=pi().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},n="number"==typeof s.errorCode?s.errorCode:Be.FAIL,r="string"==typeof s.reason?s.reason:void 0,i="string"==typeof t.resource?t.resource:void 0,o="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:n===Be.OK,statusCode:n,reason:r,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=pi().lookupType("easemob.pb.Logout").decode(e),s=t.status&&"object"==typeof t.status?t.status:void 0;return{sessionId:"string"==typeof t.sessionId?t.sessionId:void 0,reason:"string"==typeof t.reason?t.reason:void 0,statusCode:"number"==typeof s?.errorCode?s.errorCode:void 0}}decodeSyncStatisticOperations(e){const t=pi().lookupType("easemob.pb.CommSyncDL").decode(e),s=Array.isArray(t.metas)?t.metas:[],n=[];for(const r of s){const e=this.decodeStatisticMeta(r);e&&n.push(e)}return n}decodeMsync(e){const t=pi().lookupType("easemob.pb.MSync").decode(e);return{command:"number"==typeof t.command?t.command:-1,payload:this.normalizeBinaryPayload(t.payload)}}normalizeBinaryPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array}decodeSync(e){const t=pi(),s=t.lookupType("easemob.pb.CommSyncDL"),n=t.lookupType("easemob.pb.MessageBody"),r=s.decode(e);c.debug("decodeSync commSyncDl",{hasMetas:Array.isArray(r.metas)});const i=Array.isArray(r.metas)?r.metas:[],o=this.decodeAck(r);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const a=We(r.metaId),d=We(r.nextKey),l=r.queue??void 0,u="boolean"==typeof r.isLast?r.isLast:void 0,h=[],p=[];if(a&&"0"!==a){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,n):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&p.push(...e)}return{ack:o,messages:h,notifies:p.length>0?p:void 0,metaId:a,queue:l,nextKey:d,isLast:u,replacedMessage:e}}for(const c of i){const e=this.decodeChatMeta(c,n);e&&h.push(e);const t=this.decodeChatActionMeta(c,n);t&&p.push(t);const s=this.decodeNotifyMeta(c);s.length>0&&p.push(...s)}return{ack:o,messages:h,notifies:p.length>0?p:void 0,metaId:a,queue:l,nextKey:d,isLast:u}}decodeReplacedMessage(e,t){for(const s of e){const e=this.decodeChatMeta(s,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const s=e,n=s.payload;let r=null;if(n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!r)return null;if(("number"==typeof s.ns?s.ns:void 0)!==je.CHAT)return null;try{const e=t.decode(r);if(!e||"object"!=typeof e)return null;const n=e;return this.decodeMessage(s,n)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const s=e,n=s.payload;let r=null;if(n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!r)return null;if(("number"==typeof s.ns?s.ns:void 0)!==je.CHAT)return null;try{const e=t.decode(r);if(!e||"object"!=typeof e)return null;const n=e,i="number"==typeof n.type?n.type:Qe.NORMAL;if(i!==Qe.READ_ACK&&i!==Qe.RECALL&&i!==Qe.CHANNEL_ACK&&i!==Qe.EDIT&&i!==Qe.DELIVER_ACK)return null;const o=this.readJid(s.to),a=Number(We(s.timestamp))||Date.now(),d=this.resolveActionConversationType(o.domain,n.meta,n),{senderId:l,receiverId:u}=this.resolveIncomingMessageParties(s,n,d),h=this.resolveActionConversationId(l,u,d);if(i===Qe.CHANNEL_ACK)return!0===n.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:a}}:h?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:a}}:null;if(i===Qe.READ_ACK){c.debug("Received READ_ACK MessageBody",n);const e=(Array.isArray(n.ackMessageIds)?n.ackMessageIds:[]).map(e=>We(e)).filter(e=>Boolean(e)),t=We(n.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!h)return null;const s=$e(Array.isArray(n.ext)?n.ext.filter(ra):void 0),r=ra(s.group_ack_count)?s.group_ack_count:{},i=e.flatMap(e=>{const t=r[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:a,..."groupChat"===d?{receiptDetails:i}:{}}}}if(i===Qe.DELIVER_ACK){const e=We(n.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(i===Qe.RECALL){const e=We(n.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:a}}:null}const p=We(n.editMessageId),m=(Array.isArray(n.contents)?n.contents.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)):[])[0],f=m?this.decodeContent(m,n.meta):null;if(!p||!h||!f)return null;const g=this.payloadDecoder.resolveModifiedInfo(n.meta);return{type:"message_updated",data:{messageId:p,conversationId:h,conversationType:d,timestamp:a,message:{type:f.type,body:f.body,ext:$e(n.ext),...g?{modifiedInfo:g}:{}}}}}catch{return null}}decodeNotifyMeta(e){if(!e||"object"!=typeof e)return[];const t=e,s="number"==typeof t.ns?t.ns:void 0;if(s!==je.NOTIFY&&s!==je.ROSTER&&s!==je.MUC&&s!==je.STATISTIC)return[];const n=t.payload;let r=null;return n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),r?s===je.ROSTER?this.decodeRosterMeta(t,r):s===je.MUC?this.decodeMucMeta(t,r):s===je.STATISTIC?this.decodeStatisticGroupReceiptNotifies(t,r):this.decodeNotifyPayload(r):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const s=pi(),n=s.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof n.location||0===n.location.length)return[];const r=JSON.parse(n.location);if(!ra(r)||!Array.isArray(r.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=/* @__PURE__ */new Map;for(const e of r.group_ack){if(!ra(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[s,n]of Object.entries(e)){if("groupId"===s)continue;const e="number"==typeof n?n:"string"==typeof n&&n.trim().length>0?Number(n):Number.NaN;!s||!Number.isInteger(e)||e<0||o.set(s,{conversationId:t,count:e})}}return c.debug("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:s}])=>({messageId:e,conversationId:t,count:s}))}),Array.from(o,([e,{conversationId:t,count:s}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:s}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==je.STATISTIC)return null;const s=t.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;try{const e=pi(),t=e.lookupType("easemob.pb.StatisticsBody").decode(n);return{operation:"number"==typeof t.operation?t.operation:-1,reason:"string"==typeof t.reason?t.reason:void 0}}catch{return null}}decodeRosterMeta(e,t){try{const s=pi(),n=s.lookupType("easemob.pb.RosterBody").decode(t),r="number"==typeof n.operation?n.operation:-1,i=this.readRosterJid(n.from),o=this.readRosterJidList(n.to),a="string"==typeof n.reason?n.reason:"",c="string"==typeof n.rosterVer&&n.rosterVer.trim().length>0?n.rosterVer:void 0,d=i.name??"",l=o[0]?.name??"";if(!d&&!l)return[];const u=eo({operation:r,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:n},this.msyncCodecContext());if(u)return[this.createMultiDeviceNotify(u)];const h=this.mapRosterOperationToEvent(r,{from:d,to:l,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const s=pi(),n=s.lookupType("easemob.pb.MUCBody").decode(t),r="number"==typeof n.operation?n.operation:-1,i=!0===n.isChatroom,o=!0===n.isThread,a=this.readJid(n.from),c=Array.isArray(n.to)?n.to.map(e=>this.readJid(e)):[],d=n.eventInfo&&"object"==typeof n.eventInfo?n.eventInfo:void 0,l=Array.isArray(n.members)?n.members.filter(e=>"string"==typeof e):[],u=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=so({operation:r,threadId:this.readJid(n.mucId).name??"",threadName:"string"==typeof n.mucName?n.mucName:void 0,parentId:this.readJid(n.mucParentId).name??void 0,from:a,to:c,members:l,timestamp:this.readMetaTimestamp(e),raw:n},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const s=37===r&&c.some(e=>e.name===this.context.userId),i=this.readJid(n.mucId).name??"",o=this.readJid(n.mucParentId).name??"";return s&&i&&o?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:i,name:"string"==typeof n.mucName?n.mucName:void 0,muc_parent_id:o,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!i){const t=to({operation:r,groupId:this.readJid(n.mucId).name??"",groupName:"string"==typeof n.mucName?n.mucName:void 0,from:a,to:c,reason:"string"==typeof n.reason?n.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:l,timestamp:this.readMetaTimestamp(e),raw:n},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=i?Ti({operation:r,chatRoomId:this.readJid(n.mucId).name??"",chatRoomName:"string"==typeof n.mucName?n.mucName:void 0,from:a,to:c,reason:"string"==typeof n.reason?n.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof n.ext?n.ext:void 0,members:l}):ki({operation:r,groupId:this.readJid(n.mucId).name??"",groupName:"string"==typeof n.mucName?n.mucName:void 0,from:a,to:c,reason:"string"==typeof n.reason?n.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof n.ext?n.ext:void 0,members:l,source:u});return h?[{type:i?"chatroom":"group",eventName:i?"onChatRoomNotify":"onGroupNotify",data:h}]:[]}catch{return[]}}mapRosterOperationToEvent(e,t){const s={from:t.from,to:t.to,message:t.message,userInfo:{userId:t.from||t.to}};switch(((e,t)=>{t&&qi.set(e,t)})(s,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:s};case 3:return{eventName:"onContactDeleted",payload:s};case 4:return{eventName:"onContactAdded",payload:s};case 5:case 9:return{eventName:"onContactRefuse",payload:s};case 8:return{eventName:"onContactAgreed",payload:s};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const s=e[i];if(void 0===s)return[];t+=`%${s.toString(16)}`}const s=decodeURIComponent(t),n=JSON.parse(s);c.debug("Decoded MSync notify payload",{payload:n});const r="string"==typeof n.type?n.type:"";if(!r)return[];if("thread"===r){return[{type:r,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:ra(n.data)?n.data:n}}]}if("conv"===r){const e=ra(n.data)?n.data:n,t=[],s="string"==typeof e.op?e.op:"";if("pin"===s||"pin_delete"===s)return[{type:r,eventName:"onPinnedMessageChanged",data:e}];const i=no({operation:s,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===r){const e=ra(n.data)?n.data:n,t=ro({chatType:"string"==typeof e.chatType?e.chatType:void 0,to:"string"==typeof e.to?e.to:void 0,resource:"string"==typeof e.resource?e.resource:void 0,msgIdList:Array.isArray(e.msgIdList)?e.msgIdList.filter(e=>"string"==typeof e):void 0,deleteTime:e.deleteTime,lastMsgId:"string"==typeof e.lastMsgId?e.lastMsgId:void 0,messageRoamingType:"string"==typeof e.messageRoamingType?e.messageRoamingType:void 0,raw:e},this.msyncCodecContext());return t?[this.createMultiDeviceNotify(t)]:[]}if("user_notification_mute"===r){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const s=[];for(const n of e){if(!Qi(n))continue;const e=$i(n.operator_resource,n.resource,n.clientResource);if(Yi(e,t.clientResource))continue;const r=zi(n.group)??zi(n.user);if(!r||!Qi(n.data))continue;const i=zi(n.group)?Vi:Gi,o=n.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:r,conversationType:i,remindType:zi(o.type),silentMode:o,deviceId:e,raw:n})}return s})(ra(n.data)&&Array.isArray(n.data.values)?n.data.values:Array.isArray(n.values)?n.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:r,data:n.data??n}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,s=Number(We(t));if(Number.isFinite(s)&&s>0)return s}msyncCodecContext(){return{userId:this.context.userId,clientResource:this.context.clientResource}}createMultiDeviceNotify(e){return{type:"multiDevice",eventName:io(e.category),data:e}}decodeNotice(e){const t=pi().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=pi().lookupType("easemob.pb.CommUnreadDL").decode(e);return{queues:(Array.isArray(t.unread)?t.unread:[]).map(e=>e&&"object"==typeof e?e:null).map(e=>e?.queue&&"object"==typeof e.queue?e.queue:null).filter(e=>Boolean(e))}}encodeBackQueue(e){const t=pi(),s=t.lookupType("easemob.pb.CommSyncUL"),n=t.lookupType("easemob.pb.MSync"),r=ia(s,{queue:e}),i={version:0,encryptType:[Ve.ENCRYPT_NONE],command:st.SYNC,payload:r,traceId:l()};return ia(n,i)}encodeLastSession(e,t){const s=pi(),n=s.lookupType("easemob.pb.CommSyncUL"),r=s.lookupType("easemob.pb.MSync"),i=ia(n,{queue:e,key:t}),o={version:0,encryptType:[Ve.ENCRYPT_NONE],command:st.SYNC,payload:i,traceId:l()};return ia(r,o)}encodeChatMessage(e,t){const s=pi(),n=s.lookupType("easemob.pb.CommSyncUL"),r=s.lookupType("easemob.pb.MSync"),i=this.buildChatMeta(e,t),o=ia(n,{meta:i}),a={version:0,encryptType:[Ve.ENCRYPT_NONE],command:st.SYNC,payload:o,traceId:l()};return ia(r,a)}encodeCombineMessageMeta(e){const t=pi().lookupType("easemob.pb.Meta"),s=Ye(e.msgServerId||e.msgLocalId),n=this.buildChatMeta(e,s,!0);return ia(t,n)}buildChatMeta(e,t,s=!1){const n=pi().lookupType("easemob.pb.MessageBody"),r=this.buildContents(e),i=this.resolveMessageProfileVersionFields(e),o=this.buildMessageMeta(e),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=s?e.from||e.sender.userId:this.context.userId,d=s&&e.to||a.name,l={type:this.resolveChatType(e),from:{name:c},to:{name:d},contents:r,ext:Je(e.ext??{}),...o?{meta:o}:{},...i,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},u=ia(n,l),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e);return{id:t,to:ze({appKey:this.context.appKey,name:d,domain:h,clientResource:s?void 0:a.clientResource}),...s?{timestamp:e.timestamp}:{},ns:je.CHAT,payload:u,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}}}encodeActionMessage(e,t){const s=pi(),n=s.lookupType("easemob.pb.MessageBody"),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o=s.lookupEnum("easemob.pb.MessageBody.EditScope"),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),d=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],u={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:a.name},contents:d,ext:Je(e.ext??{})};if("recall"!==e.kind&&"deliveryAck"!==e.kind||(u.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(u.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(u.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(u.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(u.sendToPeer=e.sendToPeer??!1,u.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind){u.editMessageId=e.messageId,u.editScope=e.ext&&Object.keys(e.ext).length>0?o.values.BODY_AND_EXT:o.values.BODY;const t=this.buildMessageMetaFromBody(e.messageType,e.body);t&&(u.meta=t)}const h=ia(n,u);if("clearAllConversationUnreadMessageCount"===e.kind){const e=n.decode(h),s=n.fields.clearAllUnreadMessageCount;c.debug("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:u.type,fieldId:s?.id,requestedValue:u.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:h.byteLength,wireTailHex:Array.from(h.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const p={id:t,to:ze({appKey:this.context.appKey,name:a.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:a.clientResource}),ns:je.CHAT,payload:h,routetype:tt.ROUTE_ALL,directedUsers:[],ext:[]},m=ia(r,{meta:p}),f={version:0,encryptType:[Ve.ENCRYPT_NONE],command:st.SYNC,payload:m,traceId:l()};return ia(i,f)}encodeChatRoomOperation(e,t){const s=pi(),n=s.lookupType("easemob.pb.MUCBody"),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o={mucId:ze({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=ia(n,o),c={id:t,from:ze({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:je.MUC,payload:a},d=ia(r,{meta:c}),u={version:0,encryptType:[Ve.ENCRYPT_NONE],command:st.SYNC,payload:d,traceId:l()};return ia(i,u)}decodeServerMessageMeta(e){const t=pi(),s=t.lookupType("easemob.pb.Meta"),n=t.lookupType("easemob.pb.MessageBody");try{const t=s.decode(e);return this.decodeChatMeta(t,n)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?Xe(e):e&&"object"==typeof e&&"data"in e?this.normalizeIncoming(e.data):new Uint8Array}decompressIncoming(e){if(!this.compressor||!this.compressor.enableDownlinkCompression)return e;try{return this.compressor.decompress(e)}catch{return this.compressionFailureCount+=1,null}}prepareOutgoing(e){if(!this.compressor||!this.compressor.enableUplinkCompression)return e;try{return this.compressor.compress(e)}catch{throw this.compressionFailureCount+=1,new Error("compress outgoing message failed")}}resetCompressionNegotiation(){this.compressor?.reset(),this.disableCompression()}toProtocolId(e){return Ye(e)}decodeChatRoomJoinInfo(e){const t=pi().lookupType("easemob.pb.MUCBody");for(const n of e){if(!ra(n)||n.ns!==je.MUC)continue;const e=n.payload,r=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(r)try{const e=t.decode(r);if(!ra(e)||!ra(e.status))continue;const s=e.status.chatroomInfo;if("string"!=typeof s||""===s)continue;const n=JSON.parse(s);if(!ra(n))continue;const i=n[this.context.userId];if(!ra(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(s){c.error("Failed to decode chat room info from ACK",s)}}}decodeAck(e){const t=We(e.metaId);if(!t||"0"===t)return;const s=e.status??{},n="number"==typeof s.errorCode?s.errorCode:Be.FAIL,r="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:We(e.serverId),ok:n===Be.OK,statusCode:n,reason:r}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:Qe.SINGLECHAT;if(!this.isPublicMessageType(s))return null;const n=Array.isArray(t.contents)?t.contents.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)):[];if(0===n.length)return null;const r=this.resolveConversationType(s),{senderUserId:i,senderId:o,receiverId:a}=this.resolveIncomingMessageParties(e,t,r),c=o===this.context.userId?"SEND":"RECEIVE",d="singleChat"===r?"SEND"===c?a:o:a,l=this.payloadDecoder.decodeMetadata(t,r,c,e.meta),u=l.stream&&n.length>=2?Ht(n,"stream content is not composed into a multi_body message"):n,h=this.payloadDecoder.resolveMessageMetaPayload(t.meta,e.meta),p=zt(u,e=>this.decodeContent(e,h));if(!p)return null;const m=$e(t.ext),f=$e(e.ext),g=Number(We(e.timestamp))||Date.now(),y=We(e.id),I=this.resolveBroadcast(f),v=this.resolvePriority(f),C=this.resolveProfileVersionTime(t.userInfoUpdateTime),E=this.resolveProfileVersionTime(t.namecardUpdateTime);let S={...{msgServerId:y,msgLocalId:"",from:o,to:a,sender:{userId:i},conversationId:d,conversationType:r,sendStatus:"sent",ext:m,timestamp:g,direct:c,isOnline:this.resolveMessageIsOnline(s,f)},type:p.type,body:p.body};xi(S,{userInfoUpdateTime:C,namecardUpdateTime:E});const A=l.stream;if(A&&"multi_body"!==p.type&&"multi_body"!==S.type){const e={...S,type:"text",body:{content:A.fullText},stream:A};Bi(S,e),S=e}return void 0!==I&&(S.isBroadcast=I),void 0!==v&&(S.priority=v),Object.assign(S,l),S}resolveMessageProfileVersionFields(e){const t=Fi(e),s={};return"number"==typeof t?.userInfoUpdateTime&&(s.userInfoUpdateTime=t.userInfoUpdateTime),"groupChat"===e.conversationType&&"number"==typeof t?.namecardUpdateTime&&(s.namecardUpdateTime=t.namecardUpdateTime),s}buildMessageMeta(e){const t={};if("text"===e.type){const s=this.buildTranslationsMeta(e.body);s&&Object.assign(t,s)}return e.isChatThread&&(t.thread={}),Object.keys(t).length>0?JSON.stringify(t):""}buildMessageMetaFromBody(e,t){if("text"!==e||!t||Array.isArray(t)||!("translations"in t))return"";const s=this.buildTranslationsMeta(t);return s?JSON.stringify(s):""}buildTranslationsMeta(e){if(Array.isArray(e)||!("translations"in e))return null;const t=Ze(e.translations);return t.length>0?{translations:t}:null}resolveProfileVersionTime(e){return Yt(We(e))}isPublicMessageType(e){return e===Qe.SINGLECHAT||e===Qe.GROUPCHAT||e===Qe.CHATROOM}resolveMessageIsOnline(e,t){if(e===Qe.CHATROOM)return!0;const s=t.is_online;return"boolean"==typeof s?s:"number"==typeof s?0!==s:"string"!=typeof s||"0"!==s}buildContents(e){if("multi_body"!==e.type)return[this.buildContent(e)];const t=e.body;if(!Array.isArray(t)||t.length<2)throw new Error("multi_body message requires at least 2 bodies");return c.debug("MultiBody message encoded as contents",{operation:"message.multibody.encode",msgLocalId:e.msgLocalId,segmentCount:t.length,segmentTypes:t.map(e=>e.type)}),t.map(t=>this.buildContent({...e,type:t.type,body:t}))}buildContent(e){if("multi_body"===e.type)throw new Error("multi_body message must be encoded as multiple contents");if("text"===e.type){const t=e.body;return{type:et.TEXT,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:et.COMMAND,action:t.action}}if("custom"===e.type){const t=e.body;return{type:et.CUSTOM,customEvent:t.event,customExts:Je(t.params??{})}}if("location"===e.type){const t=e.body;return{type:et.LOCATION,latitude:t.latitude,longitude:t.longitude,address:t.address,buildingName:t.buildingName}}if("image"===e.type){const t=e.body,s=t.isGif||t.isOriginalImage?"original":"large";return{type:et.IMAGE,displayName:t.filename,remotePath:t.originalImageUrl??"",imageType:u(s),secretKey:t.secret,fileLength:t.fileLength,size:{width:t.width,height:t.height},subType:t.isGif?1:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailDisplayName:t.filename}}if("video"===e.type){const t=e.body;return{type:et.VIDEO,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,size:t.width&&t.height?{width:t.width,height:t.height}:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailSecretKey:t.secret,thumbnailDisplayName:t.filename}}if("voice"===e.type){const t=e.body;return{type:et.VOICE,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,thumbnailDisplayName:t.filename}}if("combine"===e.type){const t=e.body;return{type:et.TEXT,subType:0,text:ut(e)??"版本过低",displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,title:t.title,summary:t.summary,combineLevel:t.combineLevel}}const t=e.body;return{type:et.FILE,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,thumbnailDisplayName:t.filename}}decodeContent(e,t){return this.payloadDecoder.decodeContent(e,t)}resolveChatType(e){switch(e.conversationType){case"groupChat":return Qe.GROUPCHAT;case"chatRoom":return Qe.CHATROOM;default:return Qe.SINGLECHAT}}resolveActionConversationType(e,t,s){const n=this.resolveConversationTypeFromMeta(t);if(n)return n;const r=s?.msgConfig&&"object"==typeof s.msgConfig?s.msgConfig:null;return!0===r?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),s=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,n=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof s?.chat_type?s.chat_type:void 0);if("chat:user"===n||"singleChat"===n)return"singleChat";if("chat:group"===n||"groupChat"===n)return"groupChat";if("chat:room"===n||"chatRoom"===n)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,s){return"singleChat"===s?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const s=`${this.context.userId}/`;if(!e.startsWith(s))return{name:e};const n=e.slice(s.length);return n?{name:this.context.userId,clientResource:n}:{name:e}}resolveIncomingMessageParties(e,t,s){const n=this.readJid(e.from),r=this.readJid(e.to),i=mi(t.from,e.from),o=mi(t.to,e.to);if(!("singleChat"===s&&i===this.context.userId&&o===this.context.userId))return{senderUserId:i,senderId:i,receiverId:o};return{senderUserId:i,senderId:n.clientResource&&n.clientResource!==this.context.clientResource?`${i}/${n.clientResource}`:i,receiverId:r.clientResource?`${o}/${r.clientResource}`:o}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return Qe.CHANNEL_ACK;case"sendMessageReadReceipts":return Qe.READ_ACK;case"deliveryAck":return Qe.DELIVER_ACK;case"recall":return Qe.RECALL;case"update":return Qe.EDIT;default:return Qe.SINGLECHAT}}resolveConversationType(e){return e===Qe.GROUPCHAT?"groupChat":e===Qe.CHATROOM?"chatRoom":"singleChat"}resolveDirectedUsers(e){return"singleChat"===e.conversationType?[]:Array.isArray(e.receiverList)?e.receiverList:[]}resolveDeliverOnlineOnly(e){if("boolean"==typeof e.deliverOnlineOnly)return e.deliverOnlineOnly;if("cmd"===e.type){const t=e.body;return Boolean(t.deliverOnlineOnly)}return!1}resolveMetaExt(e){return"chatRoom"!==e.conversationType?[]:e.priority?Je({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?tt.ROUTE_DIRECT:this.resolveDeliverOnlineOnly(e)?tt.ROUTE_ONLINE:tt.ROUTE_ALL}resolveBroadcast(e){if(!Object.prototype.hasOwnProperty.call(e,"is_broadcast"))return;const t=e.is_broadcast;return"boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?"1"===t||"true"===t.toLowerCase():Boolean(t)}resolvePriority(e){if(!Object.prototype.hasOwnProperty.call(e,"chatroom_msg_tag"))return;const t=Number(e.chatroom_msg_tag);return 0===t?"high":2===t?"low":"normal"}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[Ge.COMPRESS_LZ4]}configureCompression(e,t){if(!e||!e.includes(Ge.COMPRESS_LZ4))return void this.disableCompression();this.compressor||(this.compressor=new na);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===ta.UPLINK_ONLY||s===ta.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===ta.DOWNLINK_ONLY||s===ta.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?ta.UPLINK_ONLY:1===e?ta.DOWNLINK_ONLY:2===e?ta.BIDIRECTIONAL:ta.NONE}disableCompression(){this.compressor&&(this.compressor.mode=ta.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const aa=t=>new I("Connection attempt cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:t,cancelled:!0,retryable:!0}}),ca=t=>t instanceof I&&t.code===e.CONNECTION_CANCELLED&&!0===t.details?.cancelled;class da{constructor(e,t){this.serverUrlIndex=0,this.websocket=null,this.provisionTimeoutId=null,this.reconnectAttempts=0,this.messageReceiver=null,this.provisionPromise=null,this.provisionResolve=null,this.provisionReject=null,this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames=/* @__PURE__ */new Set,this.offlineMessageQueueReports=/* @__PURE__ */new Map,this.offlineMessageQueueCounts=/* @__PURE__ */new Map,this.offlineMessageTotalCount=0,this.reconnectTimerId=null,this.reconnectDelayReject=null,this.reconnectTask=null,this.pendingReconnectReason=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.hasEverConnected=!1,this.isOnline=!0,this.internalHandlerId="__internal:connection-manager",this.suppressNextCloseEvent=!1,this.socketDisposers=[],this.inboundMessageQueue=Promise.resolve(),this.socketGeneration=0,this.connectionAttemptGeneration=0,this.activeConnectionAttemptCancel=null,this.activeLoginDeadline=null,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:p,autoReconnectNumMax:10,connectTimeout:h,...e},this.eventHub=t,this.msyncCodec=new oa({appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,userId:e.userId,token:e.token,useReplacedMessageContents:e.useReplacedMessageContents,useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,serviceId:e.serviceId}),this.serverUrls=this.normalizeServerUrls(e),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:dt.DISCONNECTED,serverUrl:this.config.serverUrl,userId:e.userId,token:e.token,reconnectAttempts:0},this.connectionRetry=new ci({maxAttempts:this.config.autoReconnectNumMax,initialDelay:g,maxDelay:f,backoffMultiplier:m}),this.heartbeatManager=new ui({interval:this.config.heartBeatWait,timeout:y}),this.connectionEventNormalizer=new Qs,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[ht.SEND_TIMEOUT]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(t,s){const n=Date.now();if(s<=n)throw new I("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=t,this.connection.token=t,this.msyncCodec.updateToken(t),this.setupTokenLifecycle(t,s,n),c.warn("Connection token renewed",{userId:this.config.userId,expireAt:s}),{token:t,expireAt:s}}handleOnline(){if(c.warn("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0,this.terminalDisconnectError)return void c.warn("Network online recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});const e=this.offlineRecoverPending?pt.OFFLINE_RECOVER:pt.ONLINE;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){c.warn("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.stopHeartbeat(),this.closeWebSocket(pt.OFFLINE,!0),c.warn("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(this.terminalDisconnectError)return void c.warn("Foreground recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void c.warn("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(pt.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(pt.HEARTBEAT_FAILED)}}catch(t){if(c.warn("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(pt.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(pt.HEARTBEAT_FAILED)}}resumeReconnect(e){if(this.terminalDisconnectError)c.warn("Reconnect recovery skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()});else if(this.isLoggedIn)return this.reconnectTask||this.reconnectInProgress?(this.pendingReconnectReason=e,void c.warn("Reconnect recovery queued",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()})):void(this.connection.status===dt.CONNECTED&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),c.warn("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===pt.SEND_TIMEOUT&&c.warn("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,terminalDisconnectCode:this.terminalDisconnectError?.code,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId,hasReconnectTask:null!==this.reconnectTask,hasActiveConnectionAttempt:null!==this.activeConnectionAttemptCancel}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof I))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(qe(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){const e=this.reconnectDelayReject;this.reconnectDelayReject=null,this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null),e?.(aa("retry-delay"))}resolveLoginStageTimeout(e){return this.isLoginPhase&&this.activeLoginDeadline?this.activeLoginDeadline.clamp(e):e}isLoginDeadlineExpired(){return Boolean(this.isLoginPhase&&this.activeLoginDeadline&&this.activeLoginDeadline.remainingMs()<=0)}requireLoginTimeoutError(){const t=this.activeLoginDeadline;return t?(t.expire(),t.createTimeoutError()):new I("Login timeout",{code:e.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",retryable:!0}})}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay(),t=this.resolveLoginStageTimeout(e);if(t<=0)throw this.requireLoginTimeoutError();c.warn("Reconnect retry scheduled",{delayMs:Math.round(t),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise((e,s)=>{this.reconnectDelayReject=e=>{this.reconnectDelayReject=null,s(e)},this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,this.reconnectDelayReject=null,e()},t)})}buildConnectionEventPayload(e,t){const s=this.connection.error instanceof I?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:s?.code,errorMessage:s?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,t){if(e===dt.DISCONNECTED&&!this.hasEverConnected)return;if(e===dt.RECONNECT_FAILED&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===dt.DISCONNECTED||e===dt.RECONNECT_FAILED))return;const s=this.buildConnectionEventPayload(e,t),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,s,n=!1){const r=this.connection.status!==e;(r||n)&&(r&&(this.connection.status=e,this.connection.lastConnectedAt=e===dt.CONNECTED?Date.now():void 0),s&&this.dispatchConnectionEvent(e,t),c.debug("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,s=Date.now()){this.clearTokenTimers();const n=Math.max(t-s,0),r=s+Math.floor(.8*n);this.tokenLifecycle={token:e,issuedAt:s,expireAt:t,willExpireAt:r,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(r-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void c.warn("Provision auth token has invalid payload");const s=Number(t.expires_in);if(!Number.isFinite(s))return void c.warn("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,s)}catch(t){c.warn("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,c.warn("Token will expire"),this.eventHub.dispatch(lt.TOKEN_WILL_EXPIRE,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,c.warn("Token expired"),this.eventHub.dispatch(lt.TOKEN_EXPIRED,void 0))}isTokenExpiredConnectionError(t){return t instanceof I&&t.code===e.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(t){c.warn("Connection closing because token expired",{source:t}),this.connection.error=new I("Token expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:t,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(pt.TOKEN_EXPIRED,!0,!0),this.updateStatus(dt.DISCONNECTED,pt.TOKEN_EXPIRED,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(pt.HEARTBEAT_FAILED)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,y)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(t){if(!this.reconnectInProgress)if(this.connection.status!==dt.CONNECTED&&this.connection.status!==dt.CONNECTING){this.isLoginPhase=!0,this.activeLoginDeadline=t??null,this.terminalDisconnectError=null,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(pt.LOGIN,!0),this.isLoggedIn=!0}catch(s){throw this.isLoggedIn=!1,s instanceof I&&s.code===e.CONNECTION_LOGIN_TIMEOUT&&"login"===s.details?.stage&&(this.cancelActiveConnectionAttempt(),this.closeWebSocket(pt.ERROR,!1,!1),this.updateStatus(dt.DISCONNECTED,pt.ERROR,!1)),s}finally{this.isLoginPhase=!1,this.activeLoginDeadline=null}}else c.warn("Connection already established or connecting")}async connectWithRetry(t,s){if(c.warn("Reconnect flow requested",{reason:t,throwOnFailure:s,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void c.warn("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:t,...this.getReconnectDiagnostic()});if(this.connection.status===dt.CONNECTED&&this.websocket)return;if(this.reconnectPaused)return void c.warn("Reconnect flow skipped",{guard:"reconnect-paused",reason:t,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let n=null,r=null,i=null;const o=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),c.warn("Reconnect flow started",{reason:t,throwOnFailure:s,maxAttempts:o,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<o;){if(this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(!this.isLoginPhase&&(this.reconnectPaused||!this.isOnline||!this.isLoggedIn)){i=aa("ws");break}this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const e=this.isLoginPhase?dt.CONNECTING:dt.RECONNECTING;c.warn("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:o,reason:t,nextStatus:e,...this.getReconnectDiagnostic()}),this.updateStatus(e,t,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(t)}catch(a){if(n=a,this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(ca(a)){i=a,c.warn("Reconnect attempt cancelled",{attempt:this.reconnectAttempts,reason:t,...this.getReconnectDiagnostic()});break}if(c.warn("Connection attempt failed",{attempt:this.reconnectAttempts,reason:t,error:n}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(n))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(n)){r=n;break}}if(this.connectionRetry.getAttemptCount()>=o)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){c.warn("Reconnect retry loop interrupted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,...this.getReconnectDiagnostic()});break}try{await this.waitForReconnectDelay()}catch(a){if(!ca(a))throw a;i=a,c.warn("Reconnect retry delay cancelled",{reason:t,attempt:this.reconnectAttempts,...this.getReconnectDiagnostic()});break}}if(i){if(s)throw i;return}if(r){if(this.connection.error=r,s)throw this.updateStatus(dt.DISCONNECTED,pt.ERROR,!1),r;return this.reconnectPaused=!0,void this.updateStatus(dt.DISCONNECTED,pt.ERROR,!0)}if(s)throw this.updateStatus(dt.DISCONNECTED,pt.ERROR,!1),n??new I("Connection failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,c.warn("Reconnect attempts exhausted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,lastError:n,...this.getReconnectDiagnostic()}),this.updateStatus(dt.RECONNECT_FAILED,pt.LIMIT,!0)}finally{this.reconnectInProgress=!1,c.warn("Reconnect flow finished",{reason:t,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.cancelActiveConnectionAttempt(),this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(pt.RECONNECT,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(dt.CONNECTED,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),c.warn("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}triggerReconnect(e){if(c.warn("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.terminalDisconnectError)return c.warn("Reconnect trigger skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(!this.isLoggedIn)return c.warn("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectTask)return c.warn("Reconnect task reused",{reason:e,...this.getReconnectDiagnostic()}),this.reconnectTask;if(this.reconnectInProgress)return c.warn("Reconnect trigger skipped",{guard:"reconnect-in-progress-without-task",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectPaused)return c.warn("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();this.connection.status===dt.CONNECTED&&this.websocket&&this.closeWebSocket(e,!0,!0);const t=this.connectWithRetry(e,!1).finally(()=>(this.reconnectTask===t&&(this.reconnectTask=null),this.startPendingReconnectIfNeeded()??void 0));return this.reconnectTask=t,t}recoverConnectionForSend(){return this.connection.status===dt.CONNECTED&&this.websocket?Promise.resolve():this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.isLoginPhase||0===this.config.autoReconnectNumMax?(c.warn("Send connection recovery skipped",{guard:"connection-not-recoverable",...this.getReconnectDiagnostic()}),Promise.resolve()):this.reconnectTask?(c.warn("Send connection recovery reused",this.getReconnectDiagnostic()),this.reconnectTask):(this.reconnectPaused=!1,this.resetReconnectState(),c.warn("Send connection recovery requested",this.getReconnectDiagnostic()),this.triggerReconnect(pt.RECONNECT))}startPendingReconnectIfNeeded(){const e=this.pendingReconnectReason;return this.pendingReconnectReason=null,!e||null!==this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.connection.status===dt.CONNECTED&&this.websocket?null:(this.reconnectPaused=!1,this.resetReconnectState(),c.warn("Queued reconnect recovery started",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e))}handleDisconnection(e){c.warn("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(dt.DISCONNECTED,e,!0),e!==pt.TOKEN_EXPIRED&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,t,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(dt.DISCONNECTED,e,t)):s&&this.updateStatus(dt.DISCONNECTED,e,t)}createWebSocketConnection(){const t=this.resolveLoginStageTimeout(this.config.connectTimeout);return t<=0?Promise.reject(this.requireLoginTimeoutError()):new Promise((s,n)=>{const r=++this.connectionAttemptGeneration,i=this.pickNextServerUrl();c.debug("WebSocket connecting",{url:i}),this.clearSocketListeners();let o=!1,a=!1,d=null;const l=()=>{this.connectionAttemptGeneration===r&&(this.activeConnectionAttemptCancel=null)},u=e=>{o||(o=!0,d&&(clearTimeout(d),d=null),l(),n(e))};this.activeConnectionAttemptCancel=()=>{const e=aa(a?"provision":"ws");this.rejectPendingProvision(e),u(e)},d=setTimeout(()=>{c.warn("WebSocket connection attempt timed out",{url:i,connectTimeout:t,...this.getReconnectDiagnostic()}),u(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new I("Connection timeout",{code:e.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},t),this.socketAdapter.connect({url:i,timeoutMs:t}).then(e=>{if(o||r!==this.connectionAttemptGeneration||this.reconnectPaused)return c.warn("WebSocket connection result discarded",{url:i,cancelled:o||r!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),e.close(),void u(aa("ws"));d&&(clearTimeout(d),d=null),this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),a=!0,this.startProvision().then(()=>{if(this.resetProvisionHandlers(),o||r!==this.connectionAttemptGeneration||this.reconnectPaused)return c.warn("Provision result discarded",{url:i,cancelled:o||r!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),this.closeWebSocket(pt.ERROR,!1,!1),void u(aa("provision"));o||(o=!0,d&&(clearTimeout(d),d=null),l(),s())}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(pt.ERROR,!1,!1),u(e instanceof Error?e:new Error(String(e)))})}).catch(t=>{if(o)return;const s=t instanceof I?t:new I("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});this.handleConnectionError(s,pt.ERROR),u(s)})}).catch(t=>{if(t instanceof I)throw t;const s=new I("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});throw this.handleConnectionError(s,pt.ERROR),s})}cancelActiveConnectionAttempt(){this.activeConnectionAttemptCancel?.()}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(c.warn("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(pt.CLOSE))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new I("Provision interrupted",{code:e.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(t,s){c.error("Connection error:",t),this.connection.error=t,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null);const n=t instanceof I?t:new I(t.message,{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",retryable:!0}});if(this.rejectPendingProvision(n)||this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(s)}handleTerminalConnectionError(e,t){if(c.warn("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.terminalDisconnectError=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.pendingReconnectReason=null,this.isLoggedIn=!1,this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(dt.DISCONNECTED,t,!0,!0)}async handleWebSocketMessage(t,s){try{if(s!==this.socketGeneration)return;c.debug("WebSocket message received",{dataType:typeof t});const r=await this.msyncCodec.normalizeIncoming(t);if(s!==this.socketGeneration)return;if(c.debug("handleWebSocketMessage data",{length:r.length}),!r.length)return;const i=this.msyncCodec.decompressIncoming(r);if(!i){const t=null!==this.provisionReject;return c.error("Failed to decompress mSync payload, closing connection",{stage:t?"provision":"connected"}),void(t?(this.rejectPendingProvision(new I("Failed to decompress Provision payload",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(pt.ERROR,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(i))return void c.debug("Ignore server normal close payload",{length:i.length});let o=null;try{o=this.msyncCodec.decodeMsync(i)}catch(n){const e=n instanceof Error?n:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void c.warn("Discard invalid mSync payload",{length:i.length,message:e.message,prefixHex:Array.from(i.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(i.subarray(Math.max(0,i.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw c.warn("Invalid mSync payload signature",{length:i.length,prefixHex:Array.from(i.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),c.debug("handleWebSocketMessage decoded",{command:o.command}),o.command){case st.PROVISION:this.handleProvisionMessage(o.payload);break;case st.LOGOUT:this.handleLogoutMessage(o.payload);break;case st.NOTICE:this.handleNoticeMessage(o.payload);break;case st.UNREAD:this.handleUnreadMessage(o.payload);break;case st.SYNC:this.handleSyncMessage(o.payload)}}catch(n){const e=n instanceof Error?n:new Error("Failed to handle mSync payload");c.error("Failed to handle mSync payload",e),this.handleConnectionError(e,pt.ERROR)}}startProvision(){const t=this.resolveLoginStageTimeout(v);if(t<=0)return Promise.reject(this.requireLoginTimeoutError());this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new I("Provision timeout",{code:e.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},t);try{const e=this.msyncCodec.encodeProvision();c.debug("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new I("Provision send failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(t){const s=this.msyncCodec.decodeProvision(t);if(this.isLoginPhase&&this.activeLoginDeadline?.markProvisionReceived(),this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),s.ok)this.msyncCodec.updateResource(s.resource),this.setupTokenLifecycleFromProvision(s.authToken),this.provisionResolve?.();else{c.warn("Provision rejected",{statusCode:s.statusCode,reason:s.reason});const t=js(s.statusCode,s.reason),n=t.code===e.UNKNOWN?e.CONNECTION_PROVISION_REJECTED:t.code;this.provisionReject?.(new I("Provision rejected",{code:n,details:{stage:"provision",reason:s.reason,statusCode:s.statusCode,retryable:t.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),s=t?this.getQueueId(t):null,n=!!t&&this.isSelfQueue(t),r=!!t&&this.isQueueInList(t);t&&s&&(n||r||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),s=t.filter(e=>this.getQueueId(e));if(s.length){s.length!==t.length&&c.warn("Unread queues without usable identity were ignored",{ignoredCount:t.length-s.length}),this.startOfflineMessageSync(s);for(const e of s)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,pt.ERROR);if(!this.messageReceiver)return;const s=this.messageReceiver.handleSyncPayload(e);if(c.debug("handleSyncMessage result",{result:s}),!s)return;(void 0!==s.queue||void 0!==s.nextKey||void 0!==s.isLast)&&this.handleSyncQueueState(s)}handleSyncQueueState(e){c.debug("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:s,queueId:n}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(n)){const t=this.offlineMessageQueueCounts.get(n)??0;this.offlineMessageQueueCounts.set(n,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const r=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(n),this.removeQueueEntry(s),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(r){if(r!==this.nextKey||!this.isSameQueue(s,this.currentQueue))return this.nextKey=r,this.currentQueueId=n,this.currentQueue=s,void this.sendLastSession(s,r);this.removeQueueEntry(s),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,s=t?this.getQueueName(t):null,n=t?this.getQueueId(t):null,r=void 0!==t&&null!==n&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&n&&r)return{queue:t,queueId:n};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,a=i??o??this.queues[0],d=a?this.getQueueName(a):null,l=a?this.getQueueId(a):null;return a&&l?(c.warn("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:s,responseQueueId:n,fallbackQueueName:d,fallbackQueueId:l,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:a,queueId:l}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);c.warn("Logout message received",t)}resolveStatisticDisconnectError(t){for(const s of t)switch(s.operation){case 1:return new I("User has been removed",{code:e.USER_REMOVED,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 2:return new I("The user is already logged on another device",{code:e.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1,...s.reason?{loginInfoCustomExt:s.reason}:{}}});case 3:return new I("The user was kicked by changing password",{code:e.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 4:return new I("The user was kicked by other device",{code:e.USER_KICKED_BY_OTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.closeWebSocket(pt.CLOSE,!0,!0),this.updateStatus(dt.DISCONNECTED,pt.CLOSE,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),c.warn("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){return oi(e.socketAdapter)}attachSocketListeners(t,s){this.clearSocketListeners(),this.socketDisposers=[t.onMessage(e=>{this.websocket===t&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(e,s)))}),t.onError(()=>{if(this.websocket!==t)return;c.warn("WebSocket error",{stage:"ws"});const s=new I("WebSocket connection error",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(s,pt.ERROR)}),t.onClose(e=>{this.websocket===t&&this.handleWebSocketClose(e)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===o.OPEN)try{const t=this.msyncCodec.prepareOutgoing(e);c.debug("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{c.error("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){c.error("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);c.debug("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){c.debug("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const s=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(s)}sendNextQueue(){c.debug("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=/* @__PURE__ */new Set;for(const s of e){const e=this.getQueueId(s);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=C({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of t){this.offlineMessageQueueCounts.set(e,0);const t=this.offlineMessageReport?.startRequest({requestName:"MSYNC_SYNCOFFLINEMESSAGE",method:"WS",url:e});t&&this.offlineMessageQueueReports.set(e,t)}this.offlineMessageSyncLifecycleActive&&this.eventHub.dispatch(lt.OFFLINE_MESSAGE_SYNC_START,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const t=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:t}),this.offlineMessageQueueReports.delete(e),this.offlineMessageQueueNames.delete(e),this.offlineMessageQueueNames.size>0||(this.offlineMessageSyncing=!1,this.offlineMessageReport?.finish({code:0,success:!0,resultCount:this.offlineMessageTotalCount}),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleActive=!1,this.eventHub.dispatch(lt.OFFLINE_MESSAGE_SYNC_FINISH,void 0)))}isQueueInList(e){return this.queues.some(t=>this.isSameQueue(t,e))}isSelfQueue(e){const t=this.getQueueName(e),s=this.getQueueResource(e),n=this.msyncCodec.getContext();return t===n.userId&&s===n.clientResource}getQueueName(e){return"string"==typeof e.name&&e.name.trim().length>0?e.name:null}getQueueResource(e){return this.getQueueField(e,"clientResource")}getQueueId(e){const t=this.getQueueName(e);if(t)return`name:${t}`;const s=this.getQueueField(e,"domain"),n=this.getQueueResource(e);if(s)return`domain:${s}|resource:${n??""}`;if(n)return`resource:${n}`;const r=this.getQueueField(e,"appKey");return r?`appKey:${r}`:null}getQueueField(e,t){const s=e[t];return"string"==typeof s&&s.trim().length>0?s:null}isSameQueue(e,t){if(!e||!t)return!1;const s=this.getQueueId(e),n=this.getQueueId(t);return null!==s&&s===n}resetSyncState(){this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames.clear(),this.offlineMessageReport?.discard(),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageTotalCount=0}}const la=new Uint8Array([99,109]),ua=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ha=e=>Array.isArray(e)&&e.every(ua),pa=e=>"string"==typeof e?e:void 0,ma=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,fa=e=>{const t=new Uint8Array(4);return t[0]=e>>>24&255,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t},ga=(t,s)=>{const n=t[s],r=t[s+1],i=t[s+2],o=t[s+3];if("number"!=typeof n||"number"!=typeof r||"number"!=typeof i||"number"!=typeof o)throw new S("Combine payload length header is invalid",{code:e.COMBINE_PARSE_FAILED});return n<<24|r<<16|i<<8|o},ya=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},Ia=(e,t)=>{const s=pi().lookupType(e).decode(t);if(!ua(s))throw new Error(`${e} decoded result is invalid`);return s},va=e=>ua(e)&&"string"==typeof e.name?e.name:"",Ca=(e,t,s)=>{const n=ha(e.contents)?e.contents:[];if(0===n.length)throw new Error("MessageBody contents is empty");const r=n.map(e=>(e=>{const t=ma(e.type)??et.TEXT,s=Boolean(pa(e.remotePath))||Boolean(pa(e.title))||Boolean(pa(e.summary))||(ma(e.combineLevel)??0)>0,n=t===et.TEXT&&0===e.subType&&s;if(t===et.COMBINE||n){const t=ma(e.combineLevel)??0;return{type:"combine",body:{title:pa(e.title)??"",summary:pa(e.summary)??"",filename:pa(e.displayName)??"combine",filetype:"application/octet-stream",url:pa(e.remotePath),secret:pa(e.secretKey),fileLength:ma(e.fileLength),combineLevel:t},combineLevel:t}}if(t===et.TEXT)return{type:"text",body:{content:pa(e.text)??""}};if(t===et.COMMAND)return{type:"cmd",body:{action:pa(e.action)??""}};if(t===et.CUSTOM){const t=$e(ha(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:pa(e.customEvent)??"",params:t}}}if(t===et.LOCATION)return{type:"location",body:{latitude:ma(e.latitude)??0,longitude:ma(e.longitude)??0,address:pa(e.address),buildingName:pa(e.buildingName)}};if(t===et.IMAGE){const t=ua(e.size)?e.size:{},s=pa(e.remotePath)??"",n=A(s),r=pa(e.thumbnailRemotePath),i=T(e.imageType)===b;return{type:"image",body:{localUrl:"",filename:pa(e.displayName)??"image",filetype:"application/octet-stream",width:ma(t.width)??0,height:ma(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:pa(e.secretKey),fileLength:ma(e.fileLength),thumbnailUrl:r??n.thumbnailUrl}}}if(t===et.VIDEO){const t=ua(e.size)?e.size:{};return{type:"video",body:{url:pa(e.remotePath)??"",filename:pa(e.displayName)??"video",filetype:"application/octet-stream",duration:ma(e.duration)??0,width:ma(t.width),height:ma(t.height),secret:pa(e.secretKey),fileLength:ma(e.fileLength),thumbnailUrl:pa(e.thumbnailRemotePath)}}}if(t===et.VOICE)return{type:"voice",body:{url:pa(e.remotePath)??"",filename:pa(e.displayName)??"voice",filetype:"application/octet-stream",duration:ma(e.duration)??0,secret:pa(e.secretKey),fileLength:ma(e.fileLength)}};if(t===et.FILE)return{type:"file",body:{url:pa(e.remotePath)??"",filename:pa(e.displayName)??"file",filetype:"application/octet-stream",secret:pa(e.secretKey),fileLength:ma(e.fileLength)}};return null})(e)),i=jt(r);if(!i)throw new Error("MessageBody content type is unsupported");const o=va(e.from)||va(s?.from)||`unknown-${t}`,a=va(e.to)||va(s?.to)||`unknown-${t}`,c=(d=e.type)===Qe.GROUPCHAT?"groupChat":d===Qe.CHATROOM?"chatRoom":"singleChat";var d;const l=a||o,u=Number(We(s?.timestamp))||Date.now(),h=$e(ha(e.ext)?e.ext:void 0),p="text"===i.type?nt(e.meta):void 0,m={msgServerId:We(s?.id),msgLocalId:"",type:i.type,sender:{userId:o},conversationId:l,conversationType:c,timestamp:u,body:Array.isArray(i.body)?i.body:{...i.body,...p?{translations:p}:{}},ext:h},f=1===r.length?r[0]?.combineLevel:void 0;return"number"==typeof f&&ua(m.body)&&(m.body.combineLevel=f),m},Ea=(e,t)=>{const s=[];try{const r=Ia("easemob.pb.Meta",e),i=(n=r.payload)instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):void 0;if(i&&i.length>0){const e=Ia("easemob.pb.MessageBody",i);return Ca(e,t,r)}s.push("Meta payload is empty")}catch(r){s.push(r instanceof Error?r.message:String(r))}var n;try{const s=Ia("easemob.pb.MessageBody",e);return Ca(s,t)}catch(r){s.push(r instanceof Error?r.message:String(r))}try{const s=Ia("easemob.pb.MessageBody.Content",e),n={type:Qe.SINGLECHAT,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[s],ext:[]};return Ca(n,t)}catch(r){s.push(r instanceof Error?r.message:String(r))}throw new Error(s.join("; "))},Sa=(t,s)=>{const n=qe(t);try{const t=JSON.parse(n);if(!ua(t))throw new S("Combine payload item is invalid",{code:e.COMBINE_PARSE_FAILED,details:{index:s}});return t}catch(r){if(r instanceof S)throw r;try{return Ea(t,s)}catch(i){throw new S("Combine payload item parse failed",{code:e.COMBINE_PARSE_FAILED,details:{index:s,cause:r instanceof Error?r.message:String(r),protobufCause:i instanceof Error?i.message:String(i)}})}}},Aa=t=>{const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[t];if(void 0===s)throw new E("Combine payload base64 encode failed",{code:e.COMBINE_ENCODE_FAILED});return s},Ta=(t,s)=>{const n=t[s];if(void 0===n)throw new E("Combine payload byte is missing",{code:e.COMBINE_ENCODE_FAILED});return n},ba=e=>{let t="";for(let s=0;s<e.length;s+=3){const n=Ta(e,s),r=s+1<e.length,i=s+2<e.length,o=n<<16|(r?Ta(e,s+1):0)<<8|(i?Ta(e,s+2):0);t+=Aa(o>>18&63),t+=Aa(o>>12&63),t+=r?Aa(o>>6&63):"=",t+=i?Aa(63&o):"="}return t},wa=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},Na=(t,s)=>new E("Failed to write the combine message file",{code:e.COMBINE_UPLOAD_FAILED,details:{filePath:t,cause:s}}),Ma=(t,s)=>new E("Failed to remove the combine message file",{code:e.COMBINE_UPLOAD_FAILED,details:{filePath:t,cause:s}}),Ra=(t,s)=>{const n=t.getFileSystemManager?.(),r=n?.writeFile;if(!n||!r)throw new E("Mini program file system is missing",{code:e.COMBINE_UPLOAD_FAILED});const i=`${(t=>{const s=t.env?.USER_DATA_PATH;if("string"!=typeof s||0===s.length)throw new E("Mini program user data path is missing",{code:e.COMBINE_UPLOAD_FAILED});return s.replace(/\/+$/,"")})(t)}/combine-${(t=>{const s=t.replace(/[^A-Za-z0-9._-]/g,"_");if(0===s.length)throw new E("Combine payload file id is missing",{code:e.COMBINE_ENCODE_FAILED});return s})(s.fileId)}`,o=wa(s.payload);return new Promise((e,t)=>{try{r.call(n,{filePath:i,data:ba(new Uint8Array(o)),encoding:"base64",success:()=>{e({path:i,name:s.filename,type:s.filetype,size:s.payload.byteLength})},fail:e=>{t(Na(i,e))}})}catch(a){t(Na(i,a))}})},_a=async t=>{const s=ln(t.runtime);return un(s.hostPlatform)?Ra(s.global,t):Promise.resolve((t=>{if("undefined"==typeof File)throw new E("Combine payload file is not supported on this runtime",{code:e.COMBINE_ENCODE_FAILED});return new File([wa(t.payload)],t.filename,{type:t.filetype})})(t))},Da=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Oa{constructor(e,t,s,n){this.websocket=null,this.pendingMessages=/* @__PURE__ */new Map,this.ackTimeout=w,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=s,this.msyncCodec=e,this.attachmentUploader=n??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(t,s){const n=this.msyncCodec.toProtocolId(t.msgLocalId);if(rt(t))throw new E("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==o.OPEN){const s=this.msyncCodec.toProtocolId(t.msgLocalId);throw new E("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:s,retryable:!0}})}let r={...t,sendStatus:"sending"};Bi(t,r),c.debug("Message send queued",{msgLocalId:t.msgLocalId,protocolId:n,type:t.type,conversationType:t.conversationType,conversationId:t.conversationId});try{const t="combine"===r.type?await this.prepareCombineMessage(r):r,n=this.attachmentUploader?await this.attachmentUploader.prepareMessage(t,s):t;if(this.attachmentUploader&&"combine"===r.type)try{await(async(t,s)=>{if(void 0===t||!(e=>"path"in e&&"string"==typeof e.path&&e.path.length>0)(t))return;const n=ln(s);if(!un(n.hostPlatform))return;const r=n.global,i=r.getFileSystemManager?.(),o=i?.unlink;if(!i||!o)throw new E("Mini program file system is missing",{code:e.COMBINE_UPLOAD_FAILED,details:{filePath:t.path}});const a=t.path;await new Promise((e,t)=>{try{o.call(i,{filePath:a,success:()=>{e()},fail:e=>{t(Ma(a,e))}})}catch(s){t(Ma(a,s))}})})(mt.get(r.msgLocalId))}catch(i){c.warn("Failed to remove combine payload file after upload",{msgLocalId:r.msgLocalId,cause:i})}const o={...n,sendStatus:"sending"};Bi(r,o),r=o,s?.onSending?.(o);const a=await this.doSendMessage(o);return s?.onSuccess?.(a),a}catch(i){const e={...r,sendStatus:"failed"};throw Bi(r,e),s?.onFailed?.(e,i instanceof Error?i:new Error(String(i))),i}}async sendAction(e,t){const s=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&c.debug("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:s,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const n=this.msyncCodec.encodeActionMessage(e,s);"clearAllConversationUnreadMessageCount"===e.kind&&c.debug("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:s,payloadBytes:n.byteLength});const r="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(s,n,t,this.createPendingDataReport({category:"message",operationName:r,operationType:"MESSAGE",requestName:r,msgId:e.messageId,messageType:Da(e.conversationType)}))}async sendChatRoomOperation(e,t){const s=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),n=this.msyncCodec.encodeChatRoomOperation(e,s),r="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(s,n,t,this.createPendingDataReport({category:"chatroom",operationName:r,operationType:"CHATROOM",requestName:r,msgId:e.chatRoomId}))}async doSendMessage(t){const s=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:t.msgLocalId,messageType:Da(t.conversationType)});return new Promise((n,r)=>{const i=this.msyncCodec.toProtocolId(t.msgLocalId),a=setTimeout(()=>{this.pendingMessages.delete(i),this.finishPendingDataReport(s,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),r(new E("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(i,{kind:"message",message:t,protocolId:i,timeoutId:a,resolve:e=>{clearTimeout(a),n(e)},reject:e=>{clearTimeout(a),r(e)},report:s});try{if(!this.websocket||this.websocket.readyState!==o.OPEN)throw new E("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}});const n=this.msyncCodec.encodeChatMessage(t,i),d=this.msyncCodec.prepareOutgoing(n);Promise.resolve(this.websocket.send(d)).catch(n=>{const o=n instanceof Error?n.message:String(n);this.pendingMessages.delete(i),clearTimeout(a),this.finishPendingDataReport(s,{code:-1,success:!1,description:o}),c.warn("Message send socket failure",{msgLocalId:t.msgLocalId,protocolId:i,websocketReadyState:this.websocket?.readyState??null,cause:o}),r(new E(`WebSocket send failed: ${o}`,{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0,cause:o}}))}),c.debug("Message sent",{msgLocalId:t.msgLocalId,protocolId:i})}catch(d){if(this.pendingMessages.delete(i),clearTimeout(a),this.finishPendingDataReport(s,{code:d instanceof E?d.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof E)throw d;throw new E("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}})}})}async sendProtocolPayload(t,s,n,r){return new Promise((i,a)=>{const c=setTimeout(()=>{this.pendingMessages.delete(t),this.finishPendingDataReport(r,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),a(new E("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{protocolId:t,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(t,{kind:"action",protocolId:t,timeoutId:c,createAckError:n,resolve:i,reject:a,report:r});try{if(!this.websocket||this.websocket.readyState!==o.OPEN)throw new E("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0}});const n=this.msyncCodec.prepareOutgoing(s);Promise.resolve(this.websocket.send(n)).catch(s=>{const n=s instanceof Error?s.message:String(s);this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(r,{code:-1,success:!1,description:n}),a(new E(`WebSocket action send failed: ${n}`,{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0,cause:n}}))})}catch(d){if(this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(r,{code:d instanceof E?d.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof E)throw d;a(new E("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{protocolId:t,retryable:!1}}))}})}async prepareCombineMessage(t){const s=t.body,n=s.messageList??[];ft(n);const r=gt(n);yt(r);const i=((t,s)=>{try{const n=t.map((t,n)=>{const r=s(t,n);if(0===r.length)throw new E("Combine payload item encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{index:n}});return r}),r=la.length+n.reduce((e,t)=>e+4+t.length,0)+1,i=new Uint8Array(r);let o=0;i.set(la,o),o+=la.length;for(const e of n){const t=fa(e.length);i.set(t,o),o+=t.length,i.set(e,o),o+=e.length}const a=ya(i.subarray(0,i.length-1));return i[i.length-1]=a,i}catch(n){if(n instanceof E)throw n;throw new E("Combine payload encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{cause:n instanceof Error?n.message:String(n)}})}})(n,e=>this.msyncCodec.encodeCombineMessageMeta(e)),o=s.filename||"combine",a=s.filetype||"application/octet-stream",c=await _a({payload:i,filename:o,filetype:a,fileId:t.msgLocalId}),d=It(c);if(!d&&!this.attachmentUploader)throw new E("Combine payload local url generation failed",{code:e.COMBINE_ENCODE_FAILED});mt.set(t.msgLocalId,c);const l={...t,body:{...s,combineLevel:r,fileLength:i.byteLength,filename:o,filetype:a,url:d??s.url}};return Bi(t,l),vt(t,l),l}handleAck(e,t,s,n){const r=this.pendingMessages.get(e);if(!r)return void c.debug("Received ACK without a tracked pending message",{protocolId:e});if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:200,success:!0}),void r.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:n});const i=r.message,o={...i,...this.resolveReplacedMessage(i,s),sendStatus:"sent",msgServerId:t||s?.msgServerId||i.msgServerId};if(Bi(i,o),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:200,success:!0}),"multi_body"===i.type){const e=i.body;Array.isArray(e)&&e.forEach((e,t)=>{mt.delete(Wt(i.msgLocalId,t))})}else"image"!==o.type&&"video"!==o.type&&"voice"!==o.type&&"file"!==o.type&&"combine"!==o.type||mt.delete(o.msgLocalId);c.debug("Message ACK matched",{protocolId:e,msgLocalId:o.msgLocalId,msgServerId:o.msgServerId??null,type:o.type,conversationType:o.conversationType,conversationId:o.conversationId}),this.eventHub.dispatch(ht.MESSAGE_SENT,o),r.resolve(o)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const s=this.pendingMessages.get(e);if(!s)return;if("action"===s.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(s.report,{code:t instanceof E?t.code:-1,success:!1,description:t.message}),void s.reject(t);const n={...s.message,sendStatus:"failed"};Bi(s.message,n),this.pendingMessages.delete(e),this.finishPendingDataReport(s.report,{code:t instanceof E?t.code:-1,success:!1,description:t.message}),c.warn("Message send failed after ACK/error",{protocolId:e,msgLocalId:n.msgLocalId,type:n.type,conversationType:n.conversationType,conversationId:n.conversationId,error:t.message}),s.reject(t)}handleAckFailure(e,t,s,n){const r=this.pendingMessages.get(e);if(r)return"action"===r.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t,success:!1,description:s??n.message}),void r.reject(r.createAckError?.(t,s)??n)):void this.handleSendError(e,n)}setWebSocket(e){this.websocket=e}destroy(){for(const[t,s]of this.pendingMessages)clearTimeout(s.timeoutId),this.finishPendingDataReport(s.report,{code:-1,success:!1,description:"Message sender destroyed"}),s.reject(new E("Message sender destroyed",{code:e.MESSAGE_SENDER_DESTROYED,details:"message"===s.kind?{msgLocalId:s.message.msgLocalId,protocolId:t,retryable:!1}:{protocolId:t,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=N){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(c.warn("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=C({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(t)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:t,request:t.startRequest({requestName:e.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(e,t){e&&!e.released&&(e.released=!0,e.request.finish(t),e.operation.finish(t),"message"===e.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<N&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<N&&(this.chatRoomReportSaturated=!1)))}}class Ua{constructor(e){this.sessions=/* @__PURE__ */new Map,this.ttlMs=e?.ttlMs??3e5,this.maxSessions=e?.maxSessions??100}getOrCreate(e){this.evictStale();const t=this.sessions.get(e);if(t)return t.lastActivityTs=Date.now(),t;this.sessions.size>=this.maxSessions&&this.evictOldest();const s={msgId:e,startSeq:null,lastDispatchedSeq:-1,fullText:"",completed:!1,chunksBySeq:/* @__PURE__ */new Map,lastActivityTs:Date.now()};return this.sessions.set(e,s),s}get(e){return this.sessions.get(e)}addChunk(e,t){const s=this.getOrCreate(e),n=t.stream.seq;return s.chunksBySeq.has(n)?{duplicate:!0,session:s}:(s.chunksBySeq.set(n,t),s.lastActivityTs=Date.now(),t.stream.status!==it.START&&t.stream.status!==it.START_COMPLETED||null!==s.startSeq||(s.startSeq=n),{duplicate:!1,session:s})}getSequentialChunks(e){const t=this.sessions.get(e);if(!t||t.completed||null===t.startSeq)return[];let s=t.lastDispatchedSeq<t.startSeq?t.startSeq:t.lastDispatchedSeq+1;const n=[];for(;t.chunksBySeq.has(s);){const e=t.chunksBySeq.get(s);if(!e)break;n.push(e),s+=1}return n}markDispatched(e,t,s){const n=this.sessions.get(e);if(!n)return;const r=t.stream.seq;n.lastDispatchedSeq=Math.max(n.lastDispatchedSeq,r),n.fullText=s,n.chunksBySeq.delete(r)}markCompleted(e,t,s){const n=this.getOrCreate(e);n.completed=!0,n.completedReason=t,n.fullText=s}clear(e){this.sessions.delete(e)}clearAll(){this.sessions.clear()}evictStale(){const e=Date.now();for(const[t,s]of this.sessions)e-s.lastActivityTs>this.ttlMs&&this.sessions.delete(t)}evictOldest(){let e=null,t=1/0;for(const[s,n]of this.sessions)n.lastActivityTs<t&&(t=n.lastActivityTs,e=s);e&&this.sessions.delete(e)}}class La{constructor(e,t){this.completedIds=/* @__PURE__ */new Set,this.eventHub=e,this.cache=t??new Ua}handle(e){const t=this.resolveMessageId(e);if(!t)return void c.warn("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void c.debug("stream message already completed, ignore",{msgId:t});if(e.stream.status===it.FULL)return void this.handleFullChunk(t,e);const s=this.cache.get(t);if(s?.completed)return void c.debug("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:n}=this.cache.addChunk(t,e);n?c.debug("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const s of t){const t=this.cache.get(e);if(!t)return;const n=t.fullText,r=s.stream.deltaText,i=`${n}${r}`,o=s.stream.errorType>0?it.ERROR:s.stream.status,a=this.buildDispatchMessage(s,{status:o,fullText:i,deltaText:r});if(this.eventHub.dispatch(kt.STREAM_MESSAGE,a),this.cache.markDispatched(e,s,i),o===it.START_COMPLETED||o===it.COMPLETED||o===it.ERROR){const t=o===it.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else c.debug("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const s=this.cache.get(e),n=s?.fullText??"",r=this.resolveFullText(t,n),i=this.resolveDeltaText(n,r,t.stream.deltaText),o=!s||-1===s.lastDispatchedSeq&&0===s.chunksBySeq.size,a=t.stream.errorType>0?it.ERROR:o?it.START_COMPLETED:it.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:r,deltaText:i});this.eventHub.dispatch(kt.STREAM_MESSAGE,c);const d=a===it.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,d,r),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const s=this.cache.get(e),n=s?.fullText??"",r=this.resolveFullText(t,n),i=this.resolveDeltaText(n,r,t.stream.deltaText),o=this.buildDispatchMessage(t,{status:it.ERROR,fullText:r,deltaText:i});this.eventHub.dispatch(kt.STREAM_MESSAGE,o),this.cache.markCompleted(e,"timeout_error",r),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const s=e.stream.fullText;if(s&&s.length>=t.length)return s;const n=e.body.content;return n&&n.length>=t.length?n:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,s){return t.startsWith(e)?t.slice(e.length):s}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class ka{constructor(e=100){this.seenIds=/* @__PURE__ */new Set,this.orderedIds=[],this.limit=Math.max(1,Math.floor(e))}checkAndRecord(e){if(!e)return!1;if(this.seenIds.has(e))return!0;for(this.seenIds.add(e),this.orderedIds.push(e);this.orderedIds.length>this.limit;){const e=this.orderedIds.shift();e&&this.seenIds.delete(e)}return!1}clear(){this.seenIds.clear(),this.orderedIds.length=0}size(){return this.seenIds.size}}const Pa=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class xa{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new La(s),this.messageContexts=/* @__PURE__ */new Map,this.recentMessageIds=new ka(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{c.debug("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);c.debug("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:s,messages:n}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),s&&(c.debug("Decoded sync ACK",{ok:s.ok,protocolId:s.protocolId,serverId:s.serverId??null,statusCode:s.statusCode??null,reason:s.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(s,t.replacedMessage));for(const e of n)this.dispatchMessage(e);return t}catch(t){c.error("Failed to decode sync payload",t)}return null}handleAck(t,s){if(t.ok)return c.debug("ACK accepted",{protocolId:t.protocolId,serverId:t.serverId??null,hasReplacedMessage:Boolean(s)}),void(t.chatRoomInfo?this.messageSender.handleAck(t.protocolId,t.serverId,s,t.chatRoomInfo):this.messageSender.handleAck(t.protocolId,t.serverId,s));c.warn("ACK rejected",{protocolId:t.protocolId,statusCode:t.statusCode,reason:t.reason,hasReplacedMessage:Boolean(s)});const n=((t,s)=>{const n=js(t,s),r=n.code===e.UNKNOWN?e.MESSAGE_SEND_FAILED:n.code;return{code:r,message:Ws[r]??(s?`Message send failed: ${s}`:"Message send failed for an unknown reason"),retryable:n.retryable}})(t.statusCode,t.reason),r=new E(n.message,{code:n.code,details:{protocolId:t.protocolId,serverCode:t.statusCode,reason:t.reason,retryable:!1}});this.messageSender.handleAckFailure(t.protocolId,t.statusCode,t.reason,r)}dispatchMessage(e){if(rt(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?c.debug("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(kt.MESSAGE,e),c.debug("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{c.warn("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const s of e)if("presence"===s.type)this.handlePresenceNotify(s);else if("contact"===s.type)this.handleContactNotify(s);else if("group"===s.type)this.handleGroupNotify(s);else if("thread"===s.type)this.handleChatThreadNotify(s);else if("chatroom"===s.type)this.handleChatRoomNotify(s);else if("reaction"===s.type)this.handleReactionNotify(s);else if("conv"===s.type)this.handleConversationNotify(s);else if("multiDevice"===s.type)this.handleMultiDeviceNotify(s);else if("message_receipts"===s.type){const e=this.toMessageReceiptPayload(s);e&&t.push(e)}else"message_recalled"===s.type?this.handleMessageRecalledNotify(s):"message_updated"===s.type?this.handleMessageUpdatedNotify(s):"message_delivered"===s.type?this.handleMessageDeliveredNotify(s):this.handleUserInfoNotify(s);t.length>0&&this.eventHub.dispatch(kt.MESSAGE_READ_RECEIPTS,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const s=e.data;if(!s||"object"!=typeof s)return;const n=s,r="string"==typeof n.username?n.username:"string"==typeof n.userId?n.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=n.metadata&&"object"==typeof n.metadata&&!Array.isArray(n.metadata)?n.metadata:null,o="number"==typeof n.lastModified?n.lastModified:"string"==typeof n.lastModified?Number(n.lastModified):Number.NaN;if(!r||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:r,metadata:i,lastModified:o};this.eventHub.dispatch(ht.USER_INFO_NOTIFY,a)}handleContactNotify(e){if(c.debug("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==Pt.INVITED&&e.eventName!==Pt.DELETED&&e.eventName!==Pt.ADDED&&e.eventName!==Pt.REFUSE&&e.eventName!==Pt.AGREED)return;const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.from&&s.from&&"string"==typeof s.to&&s.to&&"string"==typeof s.message&&this.eventHub.dispatch(e.eventName,s)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t,n=Array.isArray(s.values)?s.values:[];if(0===n.length)return;const r=[];for(const i of n){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),s="string"==typeof e.uid?e.uid:"";s&&r.push({userId:s,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==r.length&&this.eventHub.dispatch(xt.STATUS_CHANGE,r)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(ht.GROUP_NOTIFY,s)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(ht.CHATROOM_NOTIFY,s)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const s of t){if(!Pa(s)||"string"!=typeof s.messageId)continue;const e=this.resolveReactionConversationContext(s);e&&this.eventHub.dispatch(kt.REACTION_CHANGED,{messageId:s.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(s.reactions),timestamp:this.normalizeTimestamp(s.ts)})}}handleConversationNotify(e){if(!Pa(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const s=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===s.clientResource&&"string"==typeof t.from&&t.from===s.userId)return;const n="string"==typeof t.ext?t.ext:"",r="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";n&&i&&o&&this.eventHub.dispatch(kt.PINNED_MESSAGE_CHANGED,{messageId:n,conversationId:"chat"===r?i:o,conversationType:"chat"===r?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!Pa(e.data)||"string"!=typeof e.eventName)return;const t=e.data;switch(e.eventName){case"onMultiDeviceContact":case"onMultiDeviceGroup":case"onMultiDeviceThread":case"onMultiDeviceConversation":case"onMultiDeviceMessageRemoved":return void this.eventHub.dispatch(e.eventName,t);default:return}}toMessageReceiptPayload(e){if(!Pa(e.data))return null;const t=e.data;if(!Array.isArray(t.messageIds)||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||"number"!=typeof t.timestamp)return null;const s=t.messageIds.filter(e=>"string"==typeof e&&e.length>0);if(0===s.length)return null;const n=s[0];if(!n)return null;const r=this.resolveMessageReceiptContext(n,t.conversationId,t.conversationType);if("groupChat"===r.conversationType){const e=new Set(s),n=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!Pa(t))return[];const s=t.messageId,n=t.count;return"string"==typeof s&&e.has(s)&&"number"==typeof n&&Number.isInteger(n)&&n>=0?[{messageId:s,count:n}]:[]}):[];return{messageIds:s,conversationId:r.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:n}}return{messageIds:s,conversationId:r.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!Pa(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(kt.MESSAGE_DELIVERED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!Pa(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(kt.MESSAGE_RECALLED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}handleMessageUpdatedNotify(e){if(!Pa(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Pa(t.message)||"string"!=typeof t.message.type||!Pa(t.message.body)||!Pa(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Pa(t.message.modifiedInfo)?{modifiedInfo:{operatorId:"string"==typeof t.message.modifiedInfo.operatorId?t.message.modifiedInfo.operatorId:"",operationCount:"number"==typeof t.message.modifiedInfo.operationCount?t.message.modifiedInfo.operationCount:0,operationTime:"number"==typeof t.message.modifiedInfo.operationTime?t.message.modifiedInfo.operationTime:0}}:{}};this.eventHub.dispatch(kt.MESSAGE_UPDATED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",message:s,timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}normalizeUpdatedMessageBody(e,t){if("text"!==e)return t;const s="string"==typeof t.content?t.content:"string"==typeof t.message?t.message:void 0;if(void 0===s)return t;const{message:n,...r}=t;return{...r,content:s}}handleChatThreadNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"onChatThreadChange"===s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(ht.CHAT_THREAD_NOTIFY,s)}normalizePresenceStatus(e){if(!e||"object"!=typeof e)return[];return Object.entries(e).map(([e,t])=>({device:e,status:Number(t)||0}))}destroy(){this.streamMessageHandler.destroy(),this.recentMessageIds.clear(),this.messageContexts.clear()}rememberMessageContext(e){const t=this.resolveMessageContextId(e),s=this.resolveMessageConversationContext(e);if(t&&s)for(this.messageContexts.delete(t),this.messageContexts.set(t,s);this.messageContexts.size>500;){const e=this.messageContexts.keys().next().value;if(!e)break;this.messageContexts.delete(e)}}resolveMessageReceiptContext(e,t,s){const n=this.messageContexts.get(e);return n||("groupChat"===s?{conversationId:t,conversationType:"groupChat"}:{conversationId:t,conversationType:"singleChat"})}resolveMessageContextId(e){return"string"==typeof e.msgServerId&&e.msgServerId.length>0?e.msgServerId:"string"==typeof e.msgLocalId&&e.msgLocalId.length>0?e.msgLocalId:""}resolveMessageConversationContext(e){if("string"!=typeof e.conversationId||!e.conversationId)return null;if("groupChat"===e.conversationType)return{conversationId:e.conversationId,conversationType:"groupChat"};if("chatRoom"===e.conversationType)return{conversationId:e.conversationId,conversationType:"chatRoom"};if("singleChat"!==e.conversationType)return null;const t=this.msyncCodec.getContext().userId,s="SEND"===e.direct||e.sender.userId===t?e.conversationId:e.sender.userId;return s?{conversationId:s,conversationType:"singleChat"}:null}resolveReactionConversationContext(e){const t="string"==typeof e.from?e.from:"",s="string"==typeof e.to?e.to:"",n="string"==typeof e.channel_type?e.channel_type:"";if(!t||!s)return null;if("groupChat"===n||"groupchat"===n||"group"===n)return{conversationId:s,conversationType:"groupChat",from:t,to:s};if(""!==n&&"chat"!==n&&"singleChat"!==n)return null;return{conversationId:t===this.msyncCodec.getContext().userId?s:t,conversationType:"singleChat",from:t,to:s}}normalizeReactionList(e){if(!Array.isArray(e))return[];const t=[];for(const s of e)Pa(s)&&"string"==typeof s.reaction&&t.push({reaction:s.reaction,count:"number"==typeof s.count&&Number.isFinite(s.count)?s.count:0,userList:Array.isArray(s.userList)?s.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof s.isAddedBySelf?s.isAddedBySelf:void 0,op:this.normalizeReactionOperations(s.op)});return t}normalizeReactionOperations(e){if(!Array.isArray(e))return;const t=[];for(const s of e)!Pa(s)||"string"!=typeof s.operator||"create"!==s.reactionType&&"delete"!==s.reactionType||t.push({operator:s.operator,reactionType:s.reactionType});return t.length>0?t:void 0}normalizeTimestamp(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){const t=Number(e);return Number.isFinite(t)?t:0}return 0}}const Fa=e=>e instanceof Error?e.message:String(e);class Ba{constructor(e){this.requestAdapter=M(e)}async downloadAndParse(t){const s=t.url.trim();if(!s)throw new R("Combine message url is required",{code:e.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const n="number"==typeof t.maxItems?t.maxItems:Ct;Et(1,n);const r=_(s,t.secret);try{const s=await this.requestAdapter.request({url:r,method:"GET",responseType:"arraybuffer",timeoutMs:t.timeoutMs??15e3,headers:{[D]:l()}});if(401===s.status||403===s.status)throw new O(401===s.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===s.status?e.AUTH_UNAUTHORIZED:e.AUTH_FORBIDDEN,details:{url:r,httpStatus:s.status}});if(s.status>=400)throw new S("Combine payload download failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{status:s.status,url:r}});const i=(t=>{if(t.length<la.length+1)throw new S("Combine payload is too short",{code:e.COMBINE_PARSE_FAILED});const s=t.subarray(0,la.length);if(s[0]!==la[0]||s[1]!==la[1])throw new S("Combine payload header is invalid",{code:e.COMBINE_PARSE_FAILED});const n=t.subarray(0,t.length-1),r=ya(n),i=t[t.length-1]??0;if(i!==r)throw new S("Combine payload checksum failed",{code:e.COMBINE_PARSE_FAILED,details:{expectedChecksum:r,actualChecksum:i}});const o=[];let a=la.length;const c=t.length-1;for(;a<c;){if(a+4>c)throw new S("Combine payload length header is incomplete",{code:e.COMBINE_PARSE_FAILED});const s=ga(t,a);if(a+=4,s<=0||a+s>c)throw new S("Combine payload item length is invalid",{code:e.COMBINE_PARSE_FAILED,details:{itemLength:s}});const n=t.subarray(a,a+s);a+=s;const r=Sa(n,o.length);o.push(r)}if(a!==c)throw new S("Combine payload has unexpected trailing bytes",{code:e.COMBINE_PARSE_FAILED,details:{offset:a,expected:c}});return o})((t=>{if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if("string"==typeof t)return Xe(t);throw new S("Combine payload response type is invalid",{code:e.COMBINE_DOWNLOAD_FAILED})})(s.data));return Et(i.length,n),ft(i),i.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(i){if(i instanceof R||i instanceof O||i instanceof S)throw i;throw new S("Combine payload download or parse failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{cause:Fa(i),url:r}})}}}const qa=e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}},Ka=e=>{switch(e.type){case"image":return e.body.filename??"image";case"video":return e.body.filename??"video";case"voice":return e.body.filename??"voice";case"file":return e.body.filename??"file";default:return"attachment"}},Ga=e=>{switch(e.type){case"image":case"video":case"voice":case"file":return e.body.filetype??"application/octet-stream";default:return"application/octet-stream"}};class Va{constructor(e){this.requestAdapter=M(e)}resolveMultiBodyTargets(t){const s=(Array.isArray(t.body)?t.body:[]).flatMap(e=>e&&Qt(e.type)?[{...t,type:e.type,body:e}]:[]);if(0===s.length)throw new R("message does not contain downloadable attachment",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});return s}assertHasDownloadUrl(t){const{url:s}=qa(t);if(!s)throw new R("attachment url is required",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}})}async download(e,t=15e3){if("multi_body"===e.type){const s=this.resolveMultiBodyTargets(e);for(const e of s)this.assertHasDownloadUrl(e);const n=[];for(const e of s)n.push(await this.downloadSingle(e,t));return n}return this.downloadSingle(e,t)}async downloadSingle(t,s){if("image"!==t.type&&"video"!==t.type&&"voice"!==t.type&&"file"!==t.type)throw new R("message does not contain downloadable attachment",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:n,secret:i}=qa(t);if(!n)throw new R("attachment url is required",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});let o;try{o=await this.requestAdapter.request({url:_(n,i),method:"GET",responseType:"arraybuffer",timeoutMs:s,headers:{[D]:l()}})}catch(a){if("object"==typeof a&&null!==a&&a.code===r.MISSING_CAPABILITY)throw new U("request adapter is required for attachment download");throw a}if(401===o.status)throw new O("attachment download unauthorized",{code:e.AUTH_UNAUTHORIZED,details:{url:n,httpStatus:o.status}});if(403===o.status)throw new O("attachment download forbidden",{code:e.AUTH_FORBIDDEN,details:{url:n,httpStatus:o.status}});if(404===o.status){const t=("string"==typeof o.data?o.data:"").includes("expired");throw new L(t?"attachment file is expired":"attachment not found",t?e.ATTACHMENT_EXPIRED:e.ATTACHMENT_NOT_FOUND)}if(429===o.status)throw new L("attachment download rate limited",e.SERVICE_LIMIT_EXCEEDED);if(o.status>=400)throw new L("attachment download failed",e.FILE_DOWNLOAD_FAILED,{details:{status:o.status,url:n}});return{filename:Ka(t),mimeType:Ga(t),size:(()=>{switch(t.type){case"image":case"video":case"voice":return t.body.fileLength;case"file":return t.body.fileLength??t.body.fileSize;default:return}})(),data:new Uint8Array(o.data),downloadUrl:n}}}const Ha=(e,t,s)=>({Authorization:`Bearer ${e}`,Accept:t,[D]:l(),...s??{}}),za=async t=>{const s=Ha(t.token,"application/json",t.headers),n=Date.now(),r="upload.multipart.init"===t.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===t.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",i=t.dataReportOperation?.startRequest({requestName:r,method:t.method,url:t.url});let o=0;c.debug("Upload request start",{operation:t.operation,method:t.method});try{const r=await t.requestAdapter.request({url:t.url,method:t.method,headers:s,responseType:"json",timeoutMs:a});o=r.status;const l=Date.now()-n;if(r.status<200||r.status>=300)throw c.warn("Upload response error",{operation:t.operation,method:t.method,status:r.status,duration:l}),new P("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:r.status}});c.debug("Upload response success",{operation:t.operation,method:t.method,status:r.status,duration:l});const u="string"==typeof(d=r.data)?JSON.parse(d):d;return i?.finish({code:r.status,success:!0}),u}catch(l){if(i?.finish({code:0!==o?o:l instanceof P?l.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:l instanceof Error?l.message:String(l)}),l instanceof P)throw l;throw c.warn("Upload request failed",{operation:t.operation,method:t.method}),new P("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}var d},ja=async t=>{const s=Date.now(),n=t.dataReportOperation?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:t.url});c.debug("Upload part start",{operation:"upload.multipart.part",partNumber:t.partNumber});try{const r=await t.uploadAdapter.upload({url:t.url,method:"PUT",headers:Ha(t.token,"*/*",{"restrict-access":"true"}),source:{sourceType:"web-file",file:t.part,name:`${t.fileName}.part-${t.partNumber}`,mimeType:t.fileType,size:t.part.size},fields:{part_number:t.partNumber},fileFieldName:"part_file",timeoutMs:a,onProgress:e=>t.onProgress?.(e.loaded)}),i=Date.now()-s;if(r.status<200||r.status>=300)throw new P("Upload part failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,partNumber:t.partNumber,status:r.status,response:r.body}});c.debug("Upload part success",{operation:"upload.multipart.part",partNumber:t.partNumber,duration:i}),n?.finish({code:r.status,success:!0})}catch(r){const e=Jt(r),s=e.details&&"object"==typeof e.details?e.details:void 0;throw n?.finish({code:e.code,success:!1,description:e.message}),c.warn("Upload part failed",{operation:"upload.multipart.part",partNumber:t.partNumber}),new P(e.message,{code:e.code,details:{...s,url:t.url,partNumber:t.partNumber}})}},Wa=async t=>{if(t.fileSize<=k)throw new P("Multipart not required",{code:e.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:s,file:n,conversationId:r,conversationType:i,fileName:o,fileType:a,fileSize:c,messageType:d,imageType:l,md5:u,width:h,height:p}=t,m=(e=>M(e))(s.requestAdapter),f=(t=>{if(t)return t;const s=Kn();if(s)return s;throw new P("Upload adapter is required for multipart upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:g,appName:y}=x(s.appKey),I=`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload`;let v;try{v=await za({url:I,method:"POST",token:s.token,operation:"upload.multipart.init",requestAdapter:m,dataReportOperation:t.dataReportOperation})}catch(O){throw new P("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:O,url:I}})}const C=(t=>{const s=t.entities?.[0],n="number"==typeof s?.file_upper_limit?s.file_upper_limit:0,r="number"==typeof s?.part_lower_limit?s.part_lower_limit:G,i="string"==typeof s?.uuid?s.uuid:"";if(!i)throw new P("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{fileMaxSize:n,partMinSize:r,uuid:i}})(v);if(C.fileMaxSize&&c>C.fileMaxSize)throw new P("File size exceeds limit",{code:e.UPLOAD_SIZE_EXCEEDED,details:{fileSize:c,maxSize:C.fileMaxSize}});const E=C.partMinSize||G,S=Math.ceil(c/E),A=Array.from({length:S},()=>0),T=`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload/${C.uuid}`,b=[],w=(e,s)=>{A[e]=s;const n=A.reduce((e,t)=>e+t,0),r=c?n/c*100:void 0;t.callbacks?.onFileUploadProgress?.({loaded:n,total:c,percent:r})};for(let e=0;e<S;e+=1){const r=e*E,i=Math.min(c,r+E),d=n.slice(r,i),l=String(e+1),u=ja({url:T,token:s.token,partNumber:l,part:d,fileName:o,fileType:a,uploadAdapter:f,onProgress:t=>w(e,t),dataReportOperation:t.dataReportOperation}).finally(()=>{const e=b.indexOf(u);e>=0&&b.splice(e,1)});b.push(u),b.length>=F&&await Promise.race(b)}await Promise.all(b);const N=V(i),R=B(`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload/${C.uuid}`,{"restrict-access":"true","chat-type":N,"chat-target":r,"thumbnail-width":t.thumbnailWidth,"thumbnail-height":t.thumbnailHeight,md5:u??"",..."image"===d?{imageType:q(l),width:h,height:p}:{}}),_=await za({url:R,method:"POST",token:s.token,operation:"upload.multipart.complete",requestAdapter:m,dataReportOperation:t.dataReportOperation}),D=K({response:_,restBaseUrl:s.restBaseUrl,orgName:g,appName:y,fileType:a,fileName:o,fallbackSize:c,messageType:d,imageType:l,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(D),D},Qa=async t=>{const{config:s,file:n,conversationId:r,conversationType:i,messageType:o,imageType:d,md5:u,width:h,height:p,fileName:m,fileType:f,fileSize:g}=t,y=(t=>{if(t)return t;const s=Kn();if(s)return s;throw new P("Upload adapter is required for simple upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:I,appName:v}=x(s.appKey),C=V(i),E=B(`${s.restBaseUrl}/${I}/${v}/chatfiles`,{"chat-type":C,"chat-target":r,md5:u??"",..."image"===o?{imageType:q(d),width:h,height:p}:{}}),S=Date.now(),A=t.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:E});c.debug("Upload request start",{operation:"upload.simple",method:"POST",fileSize:g,messageType:o});const T={};let b;void 0!==t.thumbnailWidth&&(T["thumbnail-width"]=String(t.thumbnailWidth)),void 0!==t.thumbnailHeight&&(T["thumbnail-height"]=String(t.thumbnailHeight));try{b=await y.upload({url:E,method:"POST",headers:{"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${s.token}`,[D]:l()},source:{sourceType:"web-file",file:n,name:m,mimeType:f,size:g},fields:T,fileFieldName:"file",timeoutMs:a,onProgress:e=>t.callbacks?.onFileUploadProgress?.(e)})}catch(w){const s=Jt(w),n=s.details&&"object"==typeof s.details?s.details:void 0,r=new P(s.message,{code:s.code,details:{...n,url:E,...s.code===e.UPLOAD_TIMEOUT?{timeout:a}:{}}});throw A?.finish({code:r.code,success:!1,description:r.message}),r.code===e.UPLOAD_ABORTED?(c.warn("Upload request aborted",{operation:"upload.simple"}),t.callbacks?.onFileUploadCanceled?.()):r.code===e.UPLOAD_TIMEOUT?c.warn("Upload request timeout",{operation:"upload.simple",timeout:a}):c.warn("Upload request failed",{operation:"upload.simple"}),r}try{const n=JSON.parse(b.body),r=Date.now()-S;if(b.status>=400)throw c.warn("Upload response error",{operation:"upload.simple",status:b.status,duration:r}),new P("Upload failed",{code:e.UPLOAD_REQUEST_FAILED,details:{status:b.status,response:n}});c.debug("Upload response success",{operation:"upload.simple",status:b.status,duration:r});const i=K({response:n,restBaseUrl:s.restBaseUrl,orgName:I,appName:v,fileType:f,fileName:m,fallbackSize:g,messageType:o,imageType:d,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(i),A?.finish({code:b.status||200,success:!0}),i}catch(w){throw A?.finish({code:w instanceof P?w.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:w instanceof Error?w.message:String(w)}),w instanceof Error?w:new Error(String(w))}},$a=sr(),Ya=e=>Object.prototype.toString.call(e),Ja=e=>{const t=e&&"object"==typeof e?e:null,s="string"==typeof t?.path?t.path:void 0,n="string"==typeof t?.uri?t.uri:void 0,r="string"==typeof t?.name?t.name:void 0,i="string"==typeof t?.type?t.type:void 0,o="number"==typeof t?.size?t.size:void 0;return{kind:Ya(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof s&&s.length>0,pathPrefix:s?s.slice(0,48):void 0,hasUri:"string"==typeof n&&n.length>0,uriPrefix:n?n.slice(0,48):void 0,name:r,type:i,size:o}},Xa=e=>({sourceType:e.source.sourceType,fileName:e.fileName,fileType:e.fileType,fileSize:e.fileSize,hasWebFile:Boolean(e.webFile),sourceName:e.source.name,sourceMimeType:e.source.mimeType,sourceSize:e.source.size}),Za=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,ec=e=>"object"==typeof e&&null!==e,tc=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,sc=e=>"number"==typeof e.total&&e.total>0?tc(e.loaded/e.total):"number"==typeof e.percent?tc(e.percent/100):0,nc=e=>{if("number"==typeof e&&Number.isFinite(e)&&e>=0)return e},rc=(e,t)=>{const s=ec(t)?t:void 0,n=s?.code===r.MISSING_CAPABILITY&&s.stage===i.RUNTIME,o=s?.code===r.UPLOAD_FAILED&&s.stage===i.RUNTIME;return"miniapp-path"===e&&((e=>{if(!ec(e))return!1;const t=ec(e.details)?e.details:void 0;return e.code===r.MISSING_CAPABILITY&&e.stage===i.RUNTIME&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||o)||"rn-uri"===e&&n};class ic{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(t,s){if("multi_body"===t.type)return this.prepareMultiBodyMessage(t,s);if(!Za(t.type))return t;const n=t.body;if(this.hasUploadedRemoteResource(t.type,n))return t;const r=this.resolveUploadUrl(t.type,n),i=mt.get(t.msgLocalId),o=Boolean(i);if(c.warn("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:t.msgLocalId,messageType:t.type,conversationType:t.conversationType,hasFile:o,uploadUrl:r,cachedFile:Ja(i),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!H(r,o))return t;if(!i)throw new P("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:t.msgLocalId,url:r}});if(!this.config?.restBaseUrl)throw new P("REST base url is required for upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let a,d,l;try{a=await this.prepareAttachmentUpload(t,n,i),a.precheck?.hit||(l=C({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:t.msgLocalId,messageType:t.type})),d=a.precheck?.hit?this.buildPrecheckedUploadResult(t,a,s):await this.uploadAttachment(t,a,s,l),l?.finish({code:0,success:!0})}catch(u){const t=Jt(u);throw l?.finish({code:t.code,success:!1,description:t.message}),t.code===e.UPLOAD_ABORTED&&s?.onFileUploadCanceled?.(),s?.onFileUploadError?.(t),t}return this.buildPreparedMessage(t,a,d)}async prepareMultiBodyMessage(e,t){const s=e.body,n=s.flatMap((e,t)=>e&&Qt(e.type)?[t]:[]),r=s.map((t,s)=>{if(!t||!Qt(t.type))return 0;return((e,t)=>{const s=nc(ec(e)?e.size:void 0);if(void 0!==s)return s;const n=t;return nc(n.fileLength)??nc(n.fileSize)??0})(mt.get(Wt(e.msgLocalId,s)),t)}),i=r.reduce((e,t)=>e+t,0);let o=0;const a=e=>{i<=0||t?.onFileUploadProgress?.({loaded:e,total:i,percent:e/i*100})};c.warn("MultiBody attachment prepare started",{operation:"upload.multibody.prepare",msgLocalId:e.msgLocalId,segmentCount:s.length,segmentTypes:s.map(e=>e?.type),uploadIndexes:n,totalSize:i});for(let l=0;l<s.length;l+=1){const n=s[l];if(!n||!Qt(n.type))continue;const u=r[l]??0,h={...e,type:n.type,msgLocalId:Wt(e.msgLocalId,l),body:n};try{const r=await this.prepareMessage(h,this.withSegmentCallbacks({...t,onFileUploadProgress:e=>{i<=0?t?.onFileUploadProgress?.(e):a(o+sc(e)*u)}},e.msgLocalId));s[l]={...r.body,type:n.type},o+=u,a(o)}catch(d){throw c.warn("MultiBody attachment segment failed",{operation:"upload.multibody.segment_failed",msgLocalId:e.msgLocalId,bodyIndex:l,segmentType:n.type,cause:d instanceof Error?d.message:String(d)}),$t(d,e.msgLocalId),d}}return e}withSegmentCallbacks(e,t){return{onFileUploadProgress:t=>{e?.onFileUploadProgress?.(t)},onFileUploadComplete:t=>{e?.onFileUploadComplete?.(t)},onFileUploadError:s=>{$t(s,t),e?.onFileUploadError?.(s)},onFileUploadCanceled:()=>{e?.onFileUploadCanceled?.()}}}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&z(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&z(t.url)}async prepareAttachmentUpload(e,t,s){const n=j(s,t);if(c.warn("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Xa(n)}),"image"!==e.type){return{body:t,fileInfo:n,md5FileInfo:n,precheck:await this.maybePrecheck(e,n,n,void 0)}}const r=t,i=await this.resolveImageCandidate(r,n),o={...r,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===b},a=await this.maybePrecheck(e,i.fileInfo,n,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:n,imageType:i.imagePolicy.resolvedImageType,precheck:a,originalWidth:r.width,originalHeight:r.height}}async resolveImageCandidate(e,t){const s=W(e);if(c.warn("Image send policy resolved",{operation:"upload.image.policy",reason:s.reason,imageType:s.resolvedImageType,isGif:e.isGif,source:Xa(t)}),s.resolvedImageType===b){let n=e.width,r=e.height;if(!n||!r){const e=this.resolveImageProcessor(t.source.sourceType);c.warn("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Xa(t)});const s=await e.getImageInfo(t.source);n=s.width,r=s.height}return{imagePolicy:s,sourceKind:"origin",fileInfo:t,width:n,height:r}}try{const e=this.resolveImageProcessor(t.source.sourceType);c.warn("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Xa(t)});const n=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:s,sourceKind:"big",fileInfo:{source:n.source,fileName:n.fileName??t.fileName,fileType:n.fileType??t.fileType,fileSize:n.fileSize??t.fileSize,webFile:n.webFile},width:n.width,height:n.height}}catch(n){return c.warn("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:s.reason,error:n instanceof Error?n.message:String(n),source:Xa(t)}),{imagePolicy:{resolvedImageType:b,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,s,n){if(!Za(e.type))return;if(!0!==this.config?.enableMd5Check)return void c.debug("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:n,fileSize:t.fileSize});const r=Q({messageType:e.type,fileSize:t.fileSize,imageType:n});if(!r.shouldPrecheck)return void c.debug("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:n,fileSize:t.fileSize,thresholdBytes:r.thresholdBytes});let i;try{i=await this.computeMd5(s)}catch(a){if(rc(s.source.sourceType,a))return void c.warn("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:n,thresholdType:r.thresholdType,source:Xa(s),error:a instanceof Error?a.message:String(a)});throw a}const o=await this.requestPrecheck(e,r.thresholdType,i,n);return c.debug(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:n,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return c.warn("Attachment md5 compute start",{operation:"upload.md5.start",source:Xa(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return c.warn("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return c.warn("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),$a;throw c.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),n("Image processor capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(t,s,n,r){if(!this.config)throw new P("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:o}=x(this.config.appKey),a=B(`${this.config.restBaseUrl}/${i}/${o}/chatfiles/exists`,{md5:n,..."image"===t.type?{imageType:q(r)}:{}}),d=await this.requestJson({url:a,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(e=>{c.warn("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:t.type,imageType:r,thresholdType:s,md5:n,error:e instanceof Error?e.message:String(e)})});return d?$(d):{exists:!1,hit:!1}}async requestJson(e){return this.requestByAdapter(M(this.config?.requestAdapter),e)}async requestByAdapter(t,s){const n=await t.request({url:s.url,method:s.method,headers:s.headers,responseType:"json",timeoutMs:a});if(n.status>=400)throw new P("Upload precheck request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:n.status,operation:s.operation}});return"string"==typeof n.data?JSON.parse(n.data):n.data}buildPrecheckedUploadResult(t,s,n){if(!this.config||!s.precheck)throw new P("Precheck result is required",{code:e.UPLOAD_REQUEST_FAILED});if(!s.precheck.uuid)throw new P("Precheck hit missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{precheck:s.precheck}});if(!Za(t.type))throw new P("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const{orgName:r,appName:i}=x(this.config.appKey),o="image"===t.type?s.precheck.existsType??s.imageType:void 0,a="image"===t.type&&o===b?s.md5FileInfo:s.fileInfo,c="image"===t.type&&o===b?s.originalWidth:"image"===t.type?s.body.width:void 0,d="image"===t.type&&o===b?s.originalHeight:"image"===t.type?s.body.height:void 0,l={entities:[{uuid:s.precheck.uuid,...s.precheck.shareSecret?{"share-secret":s.precheck.shareSecret}:{}}]},u=K({response:l,restBaseUrl:this.config.restBaseUrl,orgName:r,appName:i,fileType:a.fileType,fileName:a.fileName,fallbackSize:a.fileSize,messageType:t.type,imageType:o,width:c,height:d,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(u),u}async uploadAttachment(t,s,n,r){if(!this.config)throw new P("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});if(!Za(t.type))throw new P("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const i=t.type,o=await this.resolveUploadMetadata(i,s);if(!s.fileInfo.webFile){if(this.config.uploadAdapter)return this.uploadByAdapter(this.config.uploadAdapter,t,s,o,n);throw new P("Upload adapter is required for non-web file source",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:s.fileInfo.source.sourceType}})}const a={message:t,file:s.fileInfo.webFile,conversationId:t.conversationId,conversationType:t.conversationType,messageType:i,imageType:s.imageType,md5:o.md5,width:o.width,height:o.height,fileName:s.fileInfo.fileName,fileType:s.fileInfo.fileType,fileSize:s.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(i,s.body),thumbnailHeight:this.resolveThumbnailHeight(i,s.body),callbacks:n,config:this.config,dataReportOperation:r},d=!1!==this.config?.enableMultipartUpload,l=d&&s.fileInfo.fileSize>k;if(c.warn("Attachment web upload selected",{operation:"upload.web.selected",messageType:i,source:Xa(s.fileInfo),multipartEnabled:d,uploadMode:l?"multipart":"simple"}),l)try{return await Wa(a)}catch(u){const e=u instanceof P?u.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return Qa(a);throw u}return this.config.uploadAdapter?(c.warn("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:i,source:Xa(s.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,t,s,o,n)):Qa(a)}async uploadByAdapter(t,s,n,r,i){if(!this.config)throw new P("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:o,appName:a}=x(this.config.appKey),d=V(s.conversationType);if(!Za(s.type))throw new P("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:s.type}});const u=s.type,h=B(`${this.config.restBaseUrl}/${o}/${a}/chatfiles`,{"chat-type":d,"chat-target":s.conversationId,md5:r.md5,..."image"===u?{imageType:q(n.imageType),width:r.width,height:r.height}:{}}),p={},m={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[D]:l()},f=this.resolveThumbnailWidth(u,n.body),g=this.resolveThumbnailHeight(u,n.body);void 0!==f&&(p["thumbnail-width"]=String(f)),void 0!==g&&(p["thumbnail-height"]=String(g)),c.warn("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:u,source:Xa(n.fileInfo),uploadUrl:h,fields:p});const y=await t.upload({url:h,headers:m,source:n.fileInfo.source,fields:p,onProgress:e=>{i?.onFileUploadProgress?.(e)}});if(y.status>=400){const t=y.body??"",s=413===y.status?e.FILE_TOO_LARGE:"string"==typeof t&&t.includes("content improper")?e.FILE_CONTENT_IMPROPER:e.UPLOAD_REQUEST_FAILED;throw new P("Upload failed",{code:s,details:{status:y.status,response:y.body}})}let I;try{I=JSON.parse(y.body)}catch(C){throw new P("Upload response parse failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:y.body,cause:C instanceof Error?C.message:String(C)}})}const v=K({response:I,restBaseUrl:this.config.restBaseUrl,orgName:o,appName:a,fileType:n.fileInfo.fileType,fileName:n.fileInfo.fileName,fallbackSize:n.fileInfo.fileSize,messageType:u,imageType:n.imageType,width:r.width,height:r.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return i?.onFileUploadComplete?.(v),v}buildPreparedMessage(e,t,s){if("image"===e.type){const n=t.body,r={...e,body:{...n,isOriginalImage:s.isOriginalImage??n.isOriginalImage,originalImageUrl:s.originalImageUrl??n.originalImageUrl,bigImageUrl:s.bigImageUrl??n.bigImageUrl,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename,thumbnailUrl:s.thumbnailUrl??n.thumbnailUrl,width:s.width??n.width,height:s.height??n.height}};return Bi(e,r),vt(e,r),r}if("video"===e.type){const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename,thumbnailUrl:s.thumbnailUrl??n.thumbnailUrl}};return Bi(e,r),r}if("voice"===e.type){const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename}};return Bi(e,r),r}if("combine"===e.type){const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename}};return Bi(e,r),r}const n=t.body,r={...e,body:{...n,url:s.url,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename}};return Bi(e,r),r}resolveThumbnailWidth(e,t){if("video"===e){const e="width"in t?t.width:void 0;return"number"==typeof e&&e>0?e:void 0}}resolveThumbnailHeight(e,t){if("video"===e){const e="height"in t?t.height:void 0;return"number"==typeof e&&e>0?e:void 0}}async resolveUploadMetadata(e,t){let s=t.precheck?.md5??"";if(!t.precheck)try{s=await this.computeMd5(t.md5FileInfo)}catch(r){if(!rc(t.md5FileInfo.source.sourceType,r))throw r;c.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Xa(t.md5FileInfo),error:r instanceof Error?r.message:String(r)})}const n=t.body;return{md5:s,width:"image"===e&&"number"==typeof n.width&&n.width>0?n.width:void 0,height:"image"===e&&"number"==typeof n.height&&n.height>0?n.height:void 0}}}class oc{constructor(e,t){this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null,this.runtime=e,this.handlers=t}start(){this.unsubscribeNetwork||this.unsubscribeVisibility||(this.unsubscribeNetwork=this.runtime.onNetworkChange(e=>{this.handleNetworkChange(e)}),this.unsubscribeVisibility=this.runtime.onAppVisibilityChange(e=>{this.handleVisibilityChange(e)}))}stop(){this.unsubscribeNetwork?.(),this.unsubscribeVisibility?.(),this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null}handleNetworkChange(e){this.lastOnline!==e&&(this.lastOnline=e,e?this.handlers.onOnline():this.handlers.onOffline())}handleVisibilityChange(e){this.lastForeground!==e&&(this.lastForeground=e,e?this.handlers.onForeground():this.handlers.onBackground())}}const ac="__internal:core";class cc{constructor(e,t){this.runtimeEventBridge=null,this.handleOnline=()=>{this.connectionManager.handleOnline()},this.handleOffline=()=>{this.connectionManager.handleOffline()},this.handleForegroundChange=e=>{e&&this.connectionManager.handleForeground()},this.eventHub=t,this.connectionManager=new da({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),n=e.restBaseUrl?new ic({restBaseUrl:e.restBaseUrl,token:e.token,appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,enableMultipartUpload:e.enableMultipartUpload,requestAdapter:e.platformAdapter?.request,uploadAdapter:e.platformAdapter?.upload,imageProcessor:e.platformAdapter?.imageProcessor}):void 0;this.messageSender=new Oa(s,null,this.eventHub,n),this.messageReceiver=new xa(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Ba(e.platformAdapter?.request),this.attachmentDownloader=new Va(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(ac,{[lt.CONNECTED]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[lt.DISCONNECTED]:e=>{this.messageSender.setWebSocket(null)},[lt.RECONNECT_FAILED]:e=>{this.messageSender.setWebSocket(null)},[ht.MESSAGE_SENT]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new oc(e,{onOnline:this.handleOnline,onOffline:this.handleOffline,onForeground:()=>{this.handleForegroundChange(!0)},onBackground:()=>{this.handleForegroundChange(!1)}}),this.runtimeEventBridge.start()}unregisterNetworkListeners(){this.runtimeEventBridge?.stop(),this.runtimeEventBridge=null}resolveRuntimeAdapter(){return this.platformAdapter?this.platformAdapter.runtime:this.createBrowserRuntimeAdapter()}createBrowserRuntimeAdapter(){return{getPlatform:()=>"web",onNetworkChange(e){if("undefined"==typeof window)return()=>{};const t=()=>{e(!0)},s=()=>{e(!1)};return window.addEventListener("online",t),window.addEventListener("offline",s),"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine&&e(navigator.onLine),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}},onAppVisibilityChange(e){if("undefined"==typeof document)return()=>{};const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),t(),()=>{document.removeEventListener("visibilitychange",t)}}}}async connect(e){return this.connectionManager.connect(e)}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}recoverConnectionForSend(){return this.connectionManager.recoverConnectionForSend()}getClientResource(){return this.connectionManager.getClientResource()}renewToken(e,t){const s=this.connectionManager.renewToken(e,t);return this.messageSender.updateAuthToken(e),s}async sendMessage(e,t){return this.messageSender.sendMessage(e,t)}async sendMessageAction(e,t){return this.messageSender.sendAction(e,t)}async sendChatRoomOperation(e,t){return this.messageSender.sendChatRoomOperation(e,t)}async downloadAndParseCombineMessage(e){return this.combineMessageDownloader.downloadAndParse(e)}async downloadAttachment(e,t){return this.attachmentDownloader.download(e,t)}decodeServerMessageMeta(e){return this.connectionManager.getMsyncCodec().decodeServerMessageMeta(e)}destroy(){this.unregisterNetworkListeners(),this.connectionManager.destroy(),this.messageSender.destroy(),this.messageReceiver.destroy(),this.eventHub.removeEventHandler(ac),mt.clear()}}const dc=e=>{if("singleChat"!==e.conversationType)return e.conversationId;const t=e.to||("SEND"===e.direct?e.conversationId:"RECEIVE"===e.direct?e.currentUserId:e.from?e.from===e.currentUserId?e.conversationId:e.currentUserId:""),s=t.indexOf("/");return s<0?t:t.slice(0,s)},lc=e=>{if(e.length>=1048576){const t=[],s=32768;for(let n=0;n<e.length;n+=s)t.push(String.fromCharCode(...e.subarray(n,n+s)));return btoa(t.join(""))}let t="";for(let s=0;s<e.length;s+=1){const n=e[s];void 0!==n&&(t+=String.fromCharCode(n))}return btoa(t)},uc=e=>{const t=new Uint8Array(Rt.util.base64.length(e));return Rt.util.base64.decode(e,t,0),t};class hc{getCrypto(){return t().crypto}constructor(e,n){if(this.enabled=(()=>{const e=t();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const n=ln(e);if("web"!==n.framework&&"worker"!==n.framework&&n.platform!==s.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const t=`${e}:${n}`;this.keyPromise=this.deriveKey(t)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,s=new TextEncoder,n=this.getCrypto().getRandomValues(new Uint8Array(12)),r=s.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:n},t,r),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:lc(n),ct:lc(new Uint8Array(i))};return JSON.stringify(o)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,s=uc(t.iv),n=uc(t.ct),r=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:s},e,n);return(new TextDecoder).decode(r)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),s=this.getCrypto(),n=await s.subtle.digest("SHA-256",t);return s.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const pc="conversationMap",mc="userInfoMap",fc="groupNamecardMap",gc="contactRelationMap",yc="contactVersion",Ic="contactMeta",vc="sessionListMap",Cc="sessionListCheckpoint",Ec="joinedGroupPreview",Sc="metadata",Ac=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Tc{constructor(e,t,s){this.store=e,this.key=t,this.schemaVersion=s}async load(){const e={schemaVersion:this.schemaVersion,lastFlush:0},t=await this.store.readAsync(this.key,e);return t.schemaVersion!==this.schemaVersion?e:t}async save(e){await this.store.writeAsync(this.key,e)}async touchLastFlush(){const e={schemaVersion:this.schemaVersion,lastFlush:Date.now()};return await this.save(e),e}}const bc=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const s=t().localStorage;return s&&"function"==typeof s.getItem?s:null};class wc{constructor(e,t){this.storage=t??wc.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!wc.checkAvailable())return null;const e=bc();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,s)=>(e.setItem(t,s),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=bc();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const s=await this.storage.getItem(e);if(!s)return t;let n=s;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(s);if(null===e)return t;n=e}return rs(n,t)}catch(s){return c.warn("CacheStore read failed",s),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,s){if(!this.storage)return;const n=is(t);if(null!==n)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(n):n;await this.storage.setItem(e,t)}catch(r){if(fr(r))throw r;if(s)throw r;c.warn("CacheStore write failed",r)}else if(s)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){c.warn("CacheStore remove failed",t)}}}const Nc={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Mc={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Rc{constructor(){this.items=/* @__PURE__ */new Map,this.versionState=Nc,this.meta=Mc}load(e,t,s){this.items.clear();for(const n of e){const e=this.normalizeRecord(n);e&&this.items.set(e.userId,e)}this.versionState=this.normalizeVersionState(t),this.meta=this.normalizeMeta(s)}getAll(){return Array.from(this.items.values()).sort((e,t)=>e.addTs!==t.addTs?e.addTs-t.addTs:e.userId.localeCompare(t.userId))}getVersionState(){return this.versionState}getMeta(){return this.meta}getUserIds(){return Array.from(this.items.keys())}replaceAll(e){this.items.clear(),this.upsert(e)}upsert(e){for(const t of e){const e=this.normalizeRecord(t);e&&this.items.set(e.userId,e)}}addByNotice(e,t){const s=e.trim();return!!s&&(!this.items.has(s)&&(this.items.set(s,{userId:s,remark:"",sign:"",addTs:t,updatedAt:t,metadataUpdatedAt:t}),!0))}remove(e){return this.items.delete(e)}updateRemark(e,t,s){const n=this.items.get(e);return!(!n||n.remark===t)&&(this.items.set(e,{...n,remark:t,updatedAt:s}),!0)}setVersionState(e){this.versionState=this.normalizeVersionState(e)}updateVersionFromNotice(e,t){const s=e.trim();return!!s&&((this.versionState.version!==s||"roster_notice"!==this.versionState.lastVersionSource)&&(this.versionState={version:s,lastVersionCheckAt:t,lastVersionSource:"roster_notice"},!0))}setMeta(e){this.meta=this.normalizeMeta(e)}updateMeta(e){this.meta={cacheIntegrity:e.cacheIntegrity,reason:"complete"===e.cacheIntegrity?void 0:e.reason,lastSyncTs:e.lastSyncTs??this.meta.lastSyncTs,lastSuccessfulVersion:e.lastSuccessfulVersion??this.meta.lastSuccessfulVersion,lastSyncMode:e.lastSyncMode??this.meta.lastSyncMode}}computeIntegrity(e){if(0===this.items.size&&!this.meta.lastSuccessfulVersion)return{...this.meta,cacheIntegrity:"incomplete",reason:"first_sync_pending"};const t=new Set(e.map(e=>e.userId));return this.getUserIds().some(e=>!t.has(e))?{...this.meta,cacheIntegrity:"incomplete",reason:"user_info_missing"}:{...this.meta,cacheIntegrity:"complete",reason:void 0}}buildSnapshot(e,t){const s=new Map(e.map(e=>[e.userId,e])),n=this.getAll().map(e=>{const t=s.get(e.userId);return{userId:e.userId,userInfo:{userId:e.userId,nickname:t?.nickname,avatarUrl:t?.avatarUrl,sign:t?.sign??e.sign,ext:t?.ext},remark:e.remark,addTs:e.addTs}}),r="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:n,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:r}}normalizeRecord(e){if(!os(e))return null;const t="string"==typeof e.userId?e.userId:"";return t?{userId:t,remark:"string"==typeof e.remark?e.remark:"",sign:"string"==typeof e.sign?e.sign:"",addTs:"number"==typeof e.addTs?e.addTs:0,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:0,metadataUpdatedAt:"number"==typeof e.metadataUpdatedAt?e.metadataUpdatedAt:0}:null}normalizeVersionState(e){return os(e)?{version:"string"==typeof e.version?e.version:"",lastVersionCheckAt:"number"==typeof e.lastVersionCheckAt?e.lastVersionCheckAt:0,lastVersionSource:"metadata"===e.lastVersionSource||"sync_page"===e.lastVersionSource||"roster_notice"===e.lastVersionSource?e.lastVersionSource:"metadata"}:Nc}normalizeMeta(e){return os(e)?{cacheIntegrity:"complete"===e.cacheIntegrity?"complete":"incomplete",reason:"quota_exceeded"===e.reason||"user_info_missing"===e.reason||"corrupted"===e.reason||"manual_reset"===e.reason||"first_sync_pending"===e.reason?e.reason:void 0,lastSyncTs:"number"==typeof e.lastSyncTs?e.lastSyncTs:0,lastSuccessfulVersion:"string"==typeof e.lastSuccessfulVersion?e.lastSuccessfulVersion:"",lastSyncMode:"full"===e.lastSyncMode||"incremental"===e.lastSyncMode||"skipped"===e.lastSyncMode?e.lastSyncMode:"skipped"}:Mc}}const _c=(e,t,s)=>{if(t<=0)return{kept:e,removed:[]};const n=[],r=[];for(const i of e)s-i.lastUpdate>t?r.push(i):n.push(i);return{kept:n,removed:r}},Dc=(e,t)=>{if(t<=0||0===e.length)return{kept:e,removed:[]};const s=[...e].sort((e,t)=>e.lastAccess-t.lastAccess).slice(0,t),n=new Set(s);return{kept:e.filter(e=>!n.has(e)),removed:s}},Oc=e=>{if(!Array.isArray(e))return[];const t=/* @__PURE__ */new Set,s=[],n=e;for(const r of n){const e="string"==typeof r&&r.startsWith("mark_")?r.slice(5):r,n="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(n)||n<0||n>19)continue;const i=n;t.has(i)||(t.add(i),s.push(i))}return s};class Uc{constructor(){this.items=[]}load(e,t){const s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s}getAll(){return this.items}setAll(e){this.items=[...e]}updateLastAccess(e,t){if(0===e.length)return!1;let s=!1;for(const n of e){const e=this.findIndex(n.conversationId,n.type);if(e<0)continue;const r=this.items[e];r&&(r.lastAccess!==t&&(this.items[e]={...r,lastAccess:t},s=!0))}return s}removeExpired(e,t){const s=_c(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=Dc(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),s=Math.max(this.items.length-e,0),n=t.slice(0,s),r=new Set(n);return this.items=this.items.filter(e=>!r.has(e)),n.length>0}findIndex(e,t){return this.items.findIndex(s=>s.conversationId===e&&s.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const s=e;if("string"!=typeof s.conversationId||0===s.conversationId.length)return null;const n="single"===(r=s.type)||"chat"===r||"singleChat"===r?"singleChat":"group"===r||"groupchat"===r||"groupChat"===r?"groupChat":"room"===r||"chatroom"===r||"chatRoom"===r?"chatRoom":null;var r;if(!n)return null;const i=this.normalizeMessage(s.lastMessage);return{conversationId:s.conversationId,type:n,lastMessage:i,unreadCount:"number"==typeof s.unreadCount?s.unreadCount:0,isPinned:"boolean"==typeof s.isPinned?s.isPinned:void 0,pinnedTime:"number"==typeof s.pinnedTime?s.pinnedTime:void 0,marks:Oc(s.marks),lastAccess:"number"==typeof s.lastAccess?s.lastAccess:0,lastUpdate:"number"==typeof s.lastUpdate?s.lastUpdate:t}}normalizeMessage(e){if(!e||"object"!=typeof e)return null;if(!os(e))return null;const t="string"==typeof e.msgId?e.msgId:"",s="string"==typeof e.type?e.type:"",n="number"==typeof e.timestamp?e.timestamp:0,r=Array.isArray(e.body)||os(e.body)?e.body:{};return t?{...Zt(e),msgId:t,from:"string"==typeof e.from?e.from:void 0,to:"string"==typeof e.to?e.to:void 0,sender:os(e.sender)&&"string"==typeof e.sender.userId?{userId:e.sender.userId,nickname:"string"==typeof e.sender.nickname?e.sender.nickname:void 0,avatarUrl:"string"==typeof e.sender.avatarUrl?e.sender.avatarUrl:void 0}:void 0,type:s,body:Xt(r),ext:os(e.ext)?e.ext:void 0,timestamp:n}:null}}const Lc=(e,t)=>`${e}:${t}`;class kc{constructor(){this.items=/* @__PURE__ */new Map}load(e,t){this.items.clear();for(const s of e){const e=this.normalizeItem(s,t);e&&this.items.set(Lc(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,n){const r=Lc(e,t),i=this.items.get(r);return i?(n&&this.items.set(r,{...i,lastAccess:s}),i):null}getByGroupId(e,t,s){const n=[];for(const r of this.items.values())r.groupId===e&&(n.push(r),s&&this.items.set(Lc(r.groupId,r.userId),{...r,lastAccess:t}));return n}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const n=Lc(e.groupId,e.userId),r=this.items.get(n);this.items.set(n,{...e,lastAccess:r?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(Lc(t.groupId,t.userId))}removeExpired(e,t,s=/* @__PURE__ */new Set){const n=Array.from(this.items.values()),r=n.filter(e=>!s.has(e.userId)),i=_c(r,e,t),o=new Set(i.removed.map(e=>Lc(e.groupId,e.userId)));this.items.clear();for(const a of n)o.has(Lc(a.groupId,a.userId))||this.items.set(Lc(a.groupId,a.userId),a);return i.removed.length>0}evictByLru(e,t=/* @__PURE__ */new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!t.has(e.userId)),r=Dc(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>Lc(e.groupId,e.userId)));this.items.clear();for(const o of s)i.has(Lc(o.groupId,o.userId))||this.items.set(Lc(o.groupId,o.userId),o);return r.removed.length>0}trimMax(e,t=/* @__PURE__ */new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!os(e))return null;const s="string"==typeof e.groupId?e.groupId:"",n="string"==typeof e.userId?e.userId:"";if(!s||!n)return null;return{groupId:s,userId:n,namecard:"string"==typeof e.namecard?e.namecard:"",namecardUpdateTime:"number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Pc=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,xc=e=>{if(!os(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!Array.isArray(e.body)&&!os(e.body))return null;const s=((e,t)=>{if(os(e)&&"string"==typeof e.userId){const t={userId:e.userId};return"string"==typeof e.nickname&&(t.nickname=e.nickname),"string"==typeof e.avatarUrl&&(t.avatarUrl=e.avatarUrl),t}return t?{userId:t}:null})(e.sender,e.from);if(!s)return null;const n=Pc(e.conversationType);return{...Zt({...e,sendStatus:e.sendStatus??e.status}),msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:s,body:Xt(e.body),ext:os(e.ext)?e.ext:{},timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...n?{conversationType:n}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{}}},Fc=e=>{if(!Array.isArray(e))return[];const t=/* @__PURE__ */new Set,s=[],n=e;for(const r of n){const e="string"==typeof r&&r.startsWith("mark_")?r.slice(5):r,n="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(n)||n<0||n>19)continue;const i=n;t.has(i)||(t.add(i),s.push(i))}return s},Bc=(e,t)=>{const s="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,n="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(s!==n)return n-s;const r=e.lastMessageAt??e.updatedAt,i=t.lastMessageAt??t.updatedAt;return r!==i?i-r:e.conversationId.localeCompare(t.conversationId)};class qc{constructor(){this.items=[]}load(e,t){const s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s.sort(Bc)}getAll(){return this.items}setAll(e){const t=Date.now(),s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s.sort(Bc)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!os(e))return null;const s=e,n="string"==typeof s.conversationId?s.conversationId:"";if(!n)return null;const r=Pc(s.conversationType);if(!r)return null;const i="string"==typeof s.conversationName&&s.conversationName.length>0?s.conversationName:n,o="string"==typeof s.conversationAvatar?s.conversationAvatar:void 0;return{conversationId:n,conversationType:r,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:xc(e.lastMessage),lastMessageAt:"number"==typeof e.lastMessageAt?e.lastMessageAt:void 0,isPinned:"boolean"==typeof e.isPinned?e.isPinned:void 0,pinnedTimestamp:"number"==typeof s.pinnedTimestamp?s.pinnedTimestamp:void 0,marks:Fc(e.marks),readAt:"number"==typeof s.readAt?s.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class Kc{constructor(){this.items=/* @__PURE__ */new Map}load(e,t){this.items.clear();for(const s of e){const e=this.normalizeItem(s,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,s){const n=[];for(const r of e){const e=this.items.get(r);e&&(n.push(e),s&&this.items.set(r,{...e,lastAccess:t}))}return n}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const n=this.items.get(e.userId),r=n?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:r,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,s=/* @__PURE__ */new Set){const n=Array.from(this.items.values()),r=n.filter(e=>!s.has(e.userId)),i=_c(r,e,t),o=new Set(i.removed.map(e=>e.userId));this.items.clear();for(const a of n)o.has(a.userId)||this.items.set(a.userId,a);return i.removed.length>0}evictByLru(e,t=/* @__PURE__ */new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!t.has(e.userId)),r=Dc(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>e.userId));this.items.clear();for(const o of s)i.has(o.userId)||this.items.set(o.userId,o);return r.removed.length>0}trimMax(e,t=/* @__PURE__ */new Set){if(e<=0||this.items.size<=e)return!1;const s=Array.from(this.items.values()),n=Math.max(s.length-e,0);return this.evictByLru(n,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!os(e))return null;const s="string"==typeof e.userId?e.userId:"";if(!s)return null;return{userId:s,nickname:"string"==typeof e.nickname?e.nickname:void 0,avatarUrl:"string"==typeof e.avatarUrl?e.avatarUrl:void 0,sign:"string"==typeof e.sign?e.sign:void 0,ext:"string"==typeof e.ext?e.ext:void 0,userInfoUpdateTime:"number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Gc=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Vc=e=>e.lastMessageAt??e.updatedAt,Hc=e=>[...e].sort((e,t)=>{const s=Gc(t)-Gc(e);if(0!==s)return s;const n=Vc(t)-Vc(e);return 0!==n?n:e.conversationId.localeCompare(t.conversationId)}),zc=e=>`${e.conversationType}:${e.conversationId}`,jc=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Wc=(e,t)=>((e,t)=>Vc(t)>Vc(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:jc(e,t),lastMessageAt:Math.max(e.lastMessageAt??0,t.lastMessageAt??0),isPinned:t.isPinned??e.isPinned,pinnedTimestamp:"number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:e.pinnedTimestamp,marks:t.marks.length>0?t.marks:e.marks,readAt:t.readAt??e.readAt,remindType:t.remindType??e.remindType,conversationName:t.conversationName===t.conversationId?e.conversationName:t.conversationName,conversationAvatar:t.conversationAvatar??e.conversationAvatar,updatedAt:Math.max(e.updatedAt,t.updatedAt)}:e,Qc=e=>{const t=/* @__PURE__ */new Map,s=/* @__PURE__ */new Set;for(const i of e.snapshot)s.add(zc(i));for(const i of e.existing)t.set(zc(i),i);const n=e.snapshot.map(e=>{const s=t.get(zc(e));return s?Wc(e,s):e}),r=e.existing.filter(t=>!s.has(zc(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Hc([...n,...r])},$c=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Yc=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Jc=e=>({userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,lastAccess:e.lastAccess,lastUpdate:e.lastModified});class Xc{constructor(){this.records=/* @__PURE__ */new Map}clear(){this.records.clear()}get(e,t=!1,s=Date.now()){const n=this.records.get(e)??null;if(!n||!t)return n;const r={...n,lastAccess:s};return this.records.set(e,r),r}setAll(e,t=Date.now()){for(const s of e){const e=s.lastModified??t,n=this.records.get(s.profile.userId),r=n?.lastAccess??t;this.records.set(s.profile.userId,{profile:s.profile,lastModified:e,lastAccess:r,source:s.source})}}applyPatch(e,t,s=Date.now()){const n=this.records.get(e.userId),r={userId:e.userId,...t??{},...n?.profile??{}};if(n&&e.lastModified<n.lastModified)return{applied:!1,reason:"stale",record:n};const i={...r,...e.attributes,userId:e.userId};if(n&&e.lastModified===n.lastModified&&(o=n.profile,a=i,$c.every(e=>o[e]===a[e])))return{applied:!1,reason:"duplicate",record:n};var o,a;const c={profile:i,lastModified:e.lastModified,lastAccess:n?.lastAccess??s,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const Zc=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class ed{constructor(e){this.conversationDeletionTimestamps=/* @__PURE__ */new Map,this.currentConversation=null,this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.flushTimer=null,this.flushIdleHandle=null,this.activeFlushPromise=null,this.sessionListCommitInProgress=!1,this.mutationRevision=0,this.domainRevisions=/* @__PURE__ */new Map,this.pendingDirtyRevisions=/* @__PURE__ */new Map,this.userId=e.userId,this.config={schemaVersion:1,ttlSeconds:86400,flushIntervalMs:1e3,maxUserInfoCount:1e3,maxGroupNamecardCount:1e3,maxConversations:e.config?.maxConversations,...e.config};const t="off"===e.cacheEncryptionMode?null:new hc(e.appKey,e.userId);this.store=new wc(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Ac(s,pc),this.userInfoKey=Ac(s,mc),this.groupNamecardKey=Ac(s,fc),this.sessionListKey=Ac(s,vc),this.sessionListCheckpointKey=Ac(s,Cc),this.joinedGroupPreviewKey=Ac(s,Ec),this.contactRelationKey=Ac(s,gc),this.contactVersionKey=Ac(s,yc),this.contactMetaKey=Ac(s,Ic),this.metadataKey=Ac(s,Sc),this.metadataStore=new Tc(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Uc,this.userInfoCache=new Kc,this.groupNamecardCache=new kc,this.sessionListCache=new qc,this.joinedGroupPreviewCache=new Kt,this.contactCache=new Rc,this.userInfoRuntimeStore=new Xc,this.loadPromise=this.loadFromStorage()}getConfig(){return this.config}async prepare(){await this.loadPromise}loadConversationSummaries(){return this.conversationCache.getAll()}loadSessionList(){return this.sessionListCache.exportItems()}loadJoinedGroupPreviewSnapshot(){return this.joinedGroupPreviewCache.getSnapshot()}applyJoinedGroupPreviewSnapshot(e){this.joinedGroupPreviewCache.setSnapshot(e),this.scheduleFlush(["joinedGroupPreview"])}async commitJoinedGroupPreviewSnapshot(e){this.activeFlushPromise&&await this.activeFlushPromise;const t=this.getDomainRevision("joinedGroupPreview"),s=new Kt;if(s.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,s.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const n=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==n&&n<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),s=t.items.filter(t=>t.groupId!==e);return s.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:s,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let s=!1,n=!1;const r=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:(s=!0,0===r.unreadCount?r:(n=!0,{...r,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(n=>n.conversationId!==e.conversationId||n.conversationType!==e.type?n:(s=!0,0===n.unreadCount&&n.readAt===t?n:(i=!0,{...n,unreadCount:0,readAt:t,updatedAt:t})));return n||i?(n&&this.conversationCache.setAll(r),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:s}):{items:this.sessionListCache.exportItems(),changed:!1,matched:s}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),s=this.conversationCache.getAll(),n=s.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),r=this.sessionListCache.getAll(),i=r.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(s,n),a=!this.isSessionListEqual(r,i);return o||a?(o&&this.conversationCache.setAll(n),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),s=this.conversationCache.getAll(),n=this.conversationCache.getAll().map(s=>s.conversationId!==e.conversationId||s.type!==e.type?s:{...s,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),r=this.sessionListCache.getAll(),i=r.map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:{...s,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(s,n),a=!this.isSessionListEqual(r,i);return o||a?(o&&this.conversationCache.setAll(n),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),s=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,s,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),s=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(s,e.deletedAt))}const n=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),r=s.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=n.length!==t.length,o=r.length!==s.length;return i||o?(i&&this.conversationCache.setAll(n),o&&this.sessionListCache.setAll(r),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),r=this.conversationCache.getAll(),i=r.map(e=>{const r=`${e.type}:${e.conversationId}`;if(!t.has(r))return e;const i=n(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:s}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const r=`${e.conversationType}:${e.conversationId}`;if(!t.has(r))return e;const i=n(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:s}}),c=!this.isConversationListEqual(r,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,s){const n=Date.now(),r=e.map(e=>({...e,updatedAt:e.lastMessageAt??n})),i=Qc({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:s?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(i,n)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],s=this.getDomainRevision("sessionList");try{let n=!1;for(;!n;){const r=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),s=this.getDomainRevision("sessionList"),s===r&&(n=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const r=this.pendingDirtyRevisions.get("sessionList");return void 0!==r&&r<=s&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],s=t?Yc(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Jc(t)])}getUserInfoSummaries(e,t){const s=Date.now(),n=this.userInfoCache.getByIds(e,s,t);return t&&this.scheduleFlush(["userInfo"]),n}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,s){const n=this.groupNamecardCache.get(e,t,Date.now(),s);return s&&n&&this.scheduleFlush(["groupNamecard"]),n}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),s=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:s,lastUpdate:s})),s),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:s,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const n=this.loadContactSnapshot("sync");return{snapshot:n,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(n)}}refreshSessionListDisplayFromUserInfos(e){const t=/* @__PURE__ */new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.loadContactSnapshot("cache").items,r=new Map(n.map(e=>[e.userId,e])),i=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),o=this.sessionListCache.getAll().map(e=>{let n=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,i)){const t=r.get(e.conversationId),o=this.resolveSessionDisplayUserInfo(e.conversationId,i),a=this.buildSingleSessionDisplayFields(e.conversationId,t,o,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(n={...n,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:s})}const o=n.lastMessage;if(o&&!this.shouldSkipSessionUserDisplayRefresh(o.sender.userId,t,i)){const e=r.get(o.sender.userId),t=this.resolveSessionDisplayUserInfo(o.sender.userId,i),a=this.buildSessionMessageSender(o.sender.userId,o.sender,e,t);this.isSenderEqual(o.sender,a)||(n={...n,lastMessage:{...o,sender:a},updatedAt:s})}return n}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,o);return c&&(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const s=/* @__PURE__ */new Map;for(const a of e){const e=a.groupId.trim();e&&s.set(e,a)}if(0===s.size)return{items:this.sessionListCache.exportItems(),changed:!1};const n=Date.now(),r=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const r=s.get(e.conversationId);if(!r)return e;const i=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&i)return e;const o=r.name?.trim(),a=o||e.conversationName,c=r.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(r.remindType),l=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||l?{...e,conversationName:a,conversationAvatar:c,remindType:l?d:e.remindType,updatedAt:n}:e}),i=this.sessionListCache.getAll(),o=!this.isSessionListEqual(i,r);return o&&(this.sessionListCache.setAll(r),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:o}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),s=Date.now(),n="add"===e.action?this.contactCache.addByNotice(e.userId,s):this.contactCache.remove(e.userId),r="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,s);(n||r)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const i=this.loadContactSnapshot("cache");return{snapshot:i,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(i)}}updateConversationsFromServer(e,t){const s=Date.now(),n=this.conversationCache.getAll(),r=this.mergeConversationLists(n,e,s,t?.syncStartedAt),i=!this.isConversationListEqual(n,r);return this.conversationCache.setAll(r),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:r,changed:i}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const s=Date.now(),n=this.conversationCache.getAll(),r=n.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),i=r>=0?n[r]:void 0,o=this.buildConversationFromMessage(e,i,s);if(!o)return{items:n,changed:!1};const a=[o,...n.filter((e,t)=>t!==r)];return this.isConversationListEqual(n,a)?{items:n,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}patchConversationLastMessage(e){const t=this.patchConversationLastMessages([e]);return{items:this.loadSessionList(),changed:t}}patchConversationLastMessages(e){const t=(e,t,s)=>JSON.stringify([t,e,s]),s=/* @__PURE__ */new Map;for(const h of e){if(!h.messageId||!h.patch)continue;const e=t(h.conversationId,h.conversationType,h.messageId),n=s.get(e)??[];n.push(h.patch),s.set(e,n)}if(!s.size)return!1;const n=/* @__PURE__ */new Map,r=e=>{const t=n.get(e);if(t)return t;const r=s.get(e);if(!r)return;const i=r.map(e=>({...Zt(e),...e.type?{type:e.type}:{},...e.body?{body:Xt(e.body)}:{},...e.ext?{ext:e.ext}:{},...Object.prototype.hasOwnProperty.call(e,"chatThreadOverview")&&void 0===e.chatThreadOverview?{chatThreadOverview:void 0}:{}}));return n.set(e,i),i},i=(e,t)=>{let s=e;for(const n of t)n.modifiedInfo&&s.modifiedInfo&&n.modifiedInfo.operationCount<s.modifiedInfo.operationCount||(s={...s,...n,...void 0!==n.groupReadCount?{groupReadCount:Math.max(s.groupReadCount??0,n.groupReadCount)}:{}});return es(e)===es(s)?e:s},o=this.conversationCache.getAll();let a=!1;const c=o.map(e=>{if(!e.lastMessage)return e;const s=r(t(e.conversationId,e.type,e.lastMessage.msgId));if(!s)return e;const n=i(e.lastMessage,s);return n===e.lastMessage?e:(a=!0,{...e,lastMessage:n})}),d=this.sessionListCache.getAll();let l=!1;const u=d.map(e=>{if(!e.lastMessage)return e;const s=r(t(e.conversationId,e.conversationType,e.lastMessage.msgServerId));if(!s)return e;const n=i(e.lastMessage,s);return n===e.lastMessage?e:(l=!0,{...e,lastMessage:n})});return a&&(this.conversationCache.setAll(c),this.scheduleFlush(["conversation"])),l&&(this.sessionListCache.setAll(u),this.scheduleFlush(["sessionList"])),a||l}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const s=this.sessionListCache.getAll(),n=s.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),r=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!r)return{items:this.sessionListCache.exportItems(),changed:!1};const i=(e=>{const t=zc(e.nextRecord),s=e.existing.filter(e=>zc(e)!==t);return Hc([e.nextRecord,...s])})({existing:s,nextRecord:this.buildSessionListRecordFromConversation(r,e,n,Date.now())});return this.isSessionListEqual(s,i)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const s=await this.readDump(this.userInfoKey);this.userInfoCache.load(s,e);const n=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(n,e);const r=await this.readValue(this.sessionListKey,null),i=r&&os(r)&&Array.isArray(r.items)?r.items:[];this.sessionListCache.load(i,e);const o=(r&&os(r)&&os(r.checkpoint)?r.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(o);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),l=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,l),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&os(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&os(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=/* @__PURE__ */new Map,e}restoreDirtyBatch(e){for(const[t,s]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(s,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(/* @__PURE__ */new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const n=6;for(let r=0;r<=n;r+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!fr(t))return this.restoreDirtyBatch(e),void c.warn("Cache flush failed",t);const n=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,n),"none"===n)return void c.warn("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(n)}catch(s){if(!fr(s))return this.restoreDirtyBatch(e),void c.warn("Cache quota cleanup persistence failed",s)}}c.warn("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of Zc)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,s=!1){const n={items:e,checkpoint:t};s?await this.store.writeStrictAsync(this.sessionListKey,n):await this.store.writeAsync(this.sessionListKey,n),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),s=/* @__PURE__ */new Map;for(const r of t)s.set(`${r.conversationType}:${r.conversationId}`,r);const n=Date.now();return(e=>{const t=e.incoming.filter(e=>Gc(e)>0),s=/* @__PURE__ */new Map;for(const r of e.incoming)s.set(zc(r),r);const n=t.length>0?e.existing.filter(e=>!s.has(zc(e))&&0===Gc(e)):e.existing.filter(e=>!s.has(zc(e)));return Hc([...n,...e.incoming])})({existing:t,incoming:this.filterItemsAgainstConversationDeletions(e).map(e=>{const t=`${e.conversationType}:${e.conversationId}`;return{...e,updatedAt:e.lastMessageAt??s.get(t)?.updatedAt??n}})})}buildSessionListSyncCandidate(e){const t=Date.now();if("incremental"===e.mode)return this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e.items),t);const s=this.filterItemsAgainstConversationDeletions(e.items).map(e=>({...e,updatedAt:e.lastMessageAt??t}));return this.hydrateSessionListRecordsFromLocalProfiles(Qc({snapshot:s,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),s=this.conversationDeletionTimestamps.get(t);if(void 0===s)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>s})}getConversationLatestUpdate(e,t,s,n){const r=e.find(e=>e.conversationId===s&&e.type===n),i=t.find(e=>e.conversationId===s&&e.conversationType===n);return Math.max(r?.lastUpdate??0,r?.lastMessage?.timestamp??0,i?.updatedAt??0,i?.lastMessageAt??0,i?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const s=this.groupNamecardCache.getAll().length;if(s>0){const e=this.calculateEvictCount(s,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const n=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),n}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,s=this.calculateEvictCount(t,.05);return s>0?(this.conversationCache.evictByLru(s),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const s=Math.floor(e*t);return Math.max(s,1)}mergeConversationLists(e,t,s,n){const r=/* @__PURE__ */new Map,i=/* @__PURE__ */new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);r.set(e,d.lastAccess),i.set(e,d)}const o=[],a=/* @__PURE__ */new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=r.get(e)??s;o.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:s})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof n&&e.lastUpdate>n)});return[...o,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const n=e[s],r=t[s];if(!n||!r)return!1;if(this.buildConversationSignature(n)!==this.buildConversationSignature(r))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,s=es(t),n=e.isPinned?"1":"0",r="number"==typeof e.pinnedTime?e.pinnedTime:0,i=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${n}:${r}:${i}:${s}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,s)=>e===t[s])}buildConversationFromMessage(e,t,s=Date.now()){const n=this.resolveConversationFromMessage(e);if(!n)return null;const r=e.msgServerId||e.msgLocalId,i=t?.lastMessage?.msgId!==r&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,o="SEND"===e.direct?s:t?.lastAccess??s;return{conversationId:n.conversationId,type:n.type,lastMessage:this.buildMessageSnippet(e),unreadCount:i,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:o,lastUpdate:s}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,s="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return s?{conversationId:s,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=Fi(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e),s="multi_body"===e.type&&Array.isArray(e.body)?{body:ts(e.body)}:{body:this.normalizeMessageBody(e.body)};return{...Zt(e),msgId:e.msgServerId||e.msgLocalId,from:e.sender.userId||e.from,to:dc({conversationId:e.conversationId,conversationType:e.conversationType,currentUserId:this.userId,from:e.sender.userId||e.from,to:e.to,direct:e.direct}),sender:{...e.sender},direct:e.direct,type:e.type,...s,ext:e.ext,timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return Xt(e)}buildSessionListRecordFromConversation(e,t,s,n=Date.now()){const r=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),i=r.get(e.conversationId),o=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],n,!1)[0],c=o??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,l=s?.conversationName,u=s?.conversationAvatar,h="string"==typeof t.sender.userId?t.sender.userId:"",p=this.resolveSessionDisplayUserInfo(h),m=this.buildSessionMessageSender(h,t.sender,r.get(h),p),f=dc({conversationId:e.conversationId,conversationType:e.type,currentUserId:this.userId,from:h,to:t.to,direct:t.direct}),g="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,i,c,l,u):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,l,u):this.buildGroupSessionDisplayFields(e.conversationId,l,u);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,s),lastMessage:d?{...Zt(d),msgServerId:d.msgId,from:h,to:f,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body,ext:d.ext??{}}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:s?.readAt,remindType:s?.remindType??"DEFAULT",conversationName:g.conversationName,conversationAvatar:g.conversationAvatar,updatedAt:n}}resolveSessionListUnreadCount(e,t,s){const n=s?.unreadCount,r=t.msgServerId||t.msgLocalId;return s?.lastMessage?.msgServerId!==r&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof n?Math.max(e.unreadCount,n+1):e.unreadCount:"number"==typeof n?Math.max(e.unreadCount,n):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,s,n,r){const i=t?.remark?.trim(),o=t?.userInfo.avatarUrl??s?.avatarUrl??r;if(i)return{conversationName:i,conversationAvatar:o};const a=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return a?{conversationName:a,conversationAvatar:o}:n?{conversationName:n,conversationAvatar:o}:{conversationName:e,conversationAvatar:o}}shouldSkipSessionUserDisplayRefresh(e,t,s){if(!t.has(e))return!0;const n=t.get(e),r=s.get(e);return"number"==typeof n&&"number"==typeof r?.lastUpdate&&r.lastUpdate>n}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),r=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const s=e.lastMessage;if(!s)return e;const i=s.sender.userId,o=n.get(i),a=this.resolveSessionDisplayUserInfo(i,r),c="singleChat"===e.conversationType&&i===e.conversationId?this.buildSingleChatPeerMessageSender(i,s.sender,o,a):this.buildSessionMessageSender(i,s.sender,o,a);return this.isSenderEqual(s.sender,c)?e:{...e,lastMessage:{...s,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const s=this.userInfoRuntimeStore.get(e,!1)?.profile;if(s)return s;const n=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return n?Yc(n):null}buildSessionMessageSender(e,t,s,n){const r=s?.remark?.trim();return{userId:e,nickname:r||s?.userInfo.nickname?.trim()||n?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:s?.userInfo.avatarUrl??n?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,s,n){const r=this.buildSessionMessageSender(e,void 0,s,n);return{userId:e,nickname:t?.nickname?.trim()||r.nickname,avatarUrl:t?.avatarUrl||r.avatarUrl}}isSenderEqual(e,t){return e.userId===t.userId&&e.nickname===t.nickname&&e.avatarUrl===t.avatarUrl}buildGroupSessionDisplayFields(e,t,s){return t?{conversationName:t,conversationAvatar:s}:{conversationName:e}}mapJoinedGroupRemindTypeToSession(e){if("DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e)return e}buildChatRoomSessionDisplayFields(e,t,s){return t?{conversationName:t,conversationAvatar:s}:{conversationName:e}}isSessionListEqual(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const n=e[s],r=t[s];if(!n||!r)return!1;if(this.buildSessionListSignature(n)!==this.buildSessionListSignature(r))return!1}return!0}buildSessionListSignature(e){const t=e.lastMessage,s=es(t),n=`${e.conversationName}:${e.conversationAvatar??""}`;return[e.conversationType,e.conversationId,e.unreadCount,e.isPinned?"1":"0",e.pinnedTimestamp??0,e.marks.join(","),e.readAt??0,e.remindType,e.lastMessageAt??0,n,s].join(":")}refreshContactCacheIntegrity(e=!0){const t=this.contactCache.computeIntegrity(this.userInfoCache.getAll());this.contactCache.setMeta(t),e&&this.scheduleFlush(["contactMeta"])}buildContactSnapshotSignature(e){const t=e.items.map(e=>`${e.userId}:${e.userInfo.nickname??""}:${e.userInfo.avatarUrl??""}:${e.userInfo.sign??""}:${e.userInfo.ext??""}:${e.remark}:${e.addTs}`).join("|");return`${e.version}:${e.complete?"1":"0"}:${t}`}applyContactLocalPatch(e){const t=this.loadContactSnapshot("cache"),s=e();return s&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactMeta"])),{snapshot:this.loadContactSnapshot("cache"),changed:s&&this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(this.loadContactSnapshot("cache"))}}}class td{constructor(){this.handlers=/* @__PURE__ */new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const s=[],n=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?s.push(i):n.push(i)}const r=this.dispatchToHandlers(e,t,s);r?r.then(()=>{this.dispatchToHandlers(e,t,n)}):this.dispatchToHandlers(e,t,n)}dispatchToHandlers(e,t,s){let n=null;for(const[,r]of s){const s=r[e];s&&(n=n?n.then(async()=>{await this.invokeHandler(e,t,s)}):this.invokeHandler(e,t,s))}return n}invokeHandler(e,t,s){try{const n=s(t);return this.isPromiseLike(n)?Promise.resolve(n).then(()=>{}).catch(t=>{this.reportHandlerError(e,t)}):null}catch(n){return this.reportHandlerError(e,n),null}}reportHandlerError(e,t){e!==Ft.LOG&&c.error(`Event handler error for ${e}`,t)}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const sd={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function nd(e,t){const s=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),n=Math.min(s,t.maxDelay);if(t.jitter){const e=.2*n,t=(2*Math.random()-1)*e;return Math.max(0,n+t)}return n}function rd(e){return new Promise(t=>setTimeout(t,e))}const id=(e,t)=>JSON.stringify([t,e]),od=(e,t,s)=>{const n=e.lastMessage;if(!n)return null;const r=((e,t,s)=>{const n=e.lastMessage,r=s.get(id(e.conversationId,e.type)),i=n?.msgId&&r?.msgServerId===n.msgId?r:void 0,o=n?.sender?.userId||n?.from||i?.sender?.userId||i?.from||"",a=t.getCurrentUserId?.()??"",c=(i?.sender?.userId||i?.from)===o?i:void 0,d=n?.sender?.userId===o?n.sender:c?.sender,l=n?.direct??c?.direct,u=dc({conversationId:e.conversationId,conversationType:e.type,currentUserId:a,from:o,to:n?.to||c?.to,direct:l});return{...Zt(i),...Zt(n),from:o,to:u,sender:{...d,userId:o},direct:l,ext:n?.ext??i?.ext??{}}})(e,t,s);return{...Zt(r),msgServerId:n.msgId,from:r.from,to:r.to,sender:r.sender,direct:r.direct,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof n.type&&n.type.length>0?n.type:"text",timestamp:n.timestamp,body:Xt(n.body),ext:r.ext}},ad=async(e,t)=>{const s=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!s)/* @__PURE__ */
|
|
2
2
|
return new Map;const n=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===n.length)/* @__PURE__ */
|
|
3
|
-
return new Map;const r=[];for(let a=0;a<n.length;a+=50)r.push(n.slice(a,a+50));const i=/* @__PURE__ */new Map;let o=0;return await Promise.all(Array.from({length:Math.min(3,r.length)},async()=>await(async()=>{for(;o<r.length;){const e=o;o+=1;const t=r[e];if(t)try{const e=await s.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&i.set(t.groupId,t)}catch{}}})())),i},Qd=async(e,t)=>{const s=await Wd(e,t),n=(e=>{const t=/* @__PURE__ */new Map,s=e.getCacheManager()?.loadSessionList?.()??[];for(const n of s)n.lastMessage&&t.set(zd(n.conversationId,n.conversationType),n.lastMessage);return t})(t);return e.map(e=>((e,t,s,n)=>{const r=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),i=((e,t)=>{const s=e.getCacheManager();if(!s)return null;const n=s.getRuntimeUserInfo(t,!1);if(n)return n;const r=s.getUserInfoSummaries([t],!1)[0];return r?{userId:r.userId,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}:null})(t,e.conversationId),o="singleChat"===e.type?((e,t,s)=>{const n=t?.remark?.trim();if(n)return{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl};const r=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return r?{conversationName:r,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}})(e.conversationId,r,i):"groupChat"===e.type?(a=e.conversationId,c=s.get(e.conversationId),c?.name?{conversationName:c.name,conversationAvatar:c.avatarUrl}:{conversationName:a}):(e=>({conversationName:e}))(e.conversationId);var a,c;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:jd(e,t,n),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:o.conversationName,conversationAvatar:o.conversationAvatar}})(e,t,s,n))};class $d{constructor(e=`session-list-${Xe()}`){this.status="idle",this.seenBatchKeys=/* @__PURE__ */new Set,this.itemsByConversation=/* @__PURE__ */new Map,this.batchCount=0,this.requestId=e,this.startedAt=Date.now()}getRequestId(){return this.requestId}getStartedAt(){return this.startedAt}start(){"idle"===this.status&&(this.status="connecting")}markSyncing(){if("completed"===this.status||"failed"===this.status||"cancelled"===this.status)throw new L("Session-list sync session cannot re-enter syncing state after completion",e.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(t){if(t.requestId!==this.requestId)throw new L("Session-list sync requestId mismatch",e.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:t.requestId}});if(this.isTerminal())throw new L("Session-list sync batch received after terminal state",e.CONTACT_SYNC_CURSOR_INVALID,{details:{requestId:t.requestId,status:this.status}});const s=(n=t.requestId,r=t.batchSequence,`${n}:${r}`);var n,r;if(this.seenBatchKeys.has(s))return{accepted:!1,done:t.isLastBatch};this.markSyncing(),this.seenBatchKeys.add(s);for(const e of t.sessions)this.itemsByConversation.set(`${e.conversationType}:${e.conversationId}`,e);return this.batchCount+=1,t.isLastBatch&&(this.status="completed",this.finishedAt=Date.now()),{accepted:!0,done:t.isLastBatch}}fail(){this.status="failed",this.finishedAt=Date.now()}cancel(){this.status="cancelled",this.finishedAt=Date.now()}getItems(){return[...this.itemsByConversation.values()]}getBatchCount(){return this.batchCount}getStatus(){return this.status}buildSnapshot(){return{requestId:this.requestId,status:this.status,pageCount:this.batchCount,startedAt:this.startedAt,finishedAt:this.finishedAt,seenBatchKeys:[...this.seenBatchKeys]}}isTerminal(){return"completed"===this.status||"failed"===this.status||"cancelled"===this.status}}const Yd=0,Jd=5,Xd=10,Zd=11,el=1,tl=2,sl=1,nl=2,rl=3,il=e=>e===el?"groupChat":e===tl?"chatRoom":"singleChat",ol=()=>Zi().lookupType("easemob.pb.MessageBody"),al=e=>{const t=e.session_id??"",s=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),n="string"==typeof s?.nickname?s.nickname:void 0,r="string"==typeof s?.remark?s.remark:void 0,i="string"==typeof s?.avatarurl?s.avatarurl:"string"==typeof s?.avatarUrl?s.avatarUrl:void 0;return r?{conversationName:r,conversationAvatar:i}:n?{conversationName:n,conversationAvatar:i}:{conversationName:t,conversationAvatar:i}},cl=e=>{const t={...e};return delete t.type,t},dl=(e,t,s)=>{if(!e)return"";const n=`${t}_${s}_`;return e.startsWith(n)?e.slice(n.length):e},ll=(e,t,s)=>{if(!e)return null;const n=po(s.payload?.from,{name:dl(e.from?.name,s.org,s.app)}),r=((e,t)=>{if(!e)return{};const s=new ho(t.currentUserId,t.useCustomAttachmentUpload),n=uo(e),r=n?s.decodeContent(n):null,i=s.decodeMetadata(e,t.conversationType,t.from===t.currentUserId?"SEND":void 0),o={userInfoUpdateTime:yt(oo(e.userInfoUpdateTime)),namecardUpdateTime:yt(oo(e.namecardUpdateTime))};return{...i,...r?{type:i.stream?"text":r.type,body:i.stream?{content:i.stream.fullText}:{...r.body}}:{},ext:co(e.ext),...o}})(s.payload??null,{currentUserId:s.currentUserId,conversationType:s.conversationType,from:n,useCustomAttachmentUpload:s.useCustomAttachmentUpload}),i={userId:n};return"singleChat"===s.conversationType&&n===s.conversationId&&s.singleChatPeerDisplay&&(s.singleChatPeerDisplay.conversationName!==n&&(i.nickname=s.singleChatPeerDisplay.conversationName),s.singleChatPeerDisplay.conversationAvatar&&(i.avatarUrl=s.singleChatPeerDisplay.conversationAvatar)),{...r,msgServerId:e.id??"",...e.id?{sendStatus:"sent"}:{},from:n,to:$c({conversationId:s.conversationId,conversationType:s.conversationType,from:n,to:po(s.payload?.to,void 0),currentUserId:s.currentUserId}),sender:i,conversationId:s.conversationId,conversationType:s.conversationType,type:r.type??(o=t.type,"text"===o||"image"===o||"file"===o||"voice"===o||"video"===o||"location"===o||"custom"===o||"cmd"===o||"combine"===o?o:"text"),timestamp:e.timestamp??0,body:r.body??cl(t),ext:r.ext??s.ext??{}};var o},ul=e=>{if(!Array.isArray(e))return[];const t=/* @__PURE__ */new Set,s=[],n=e;for(const r of n){const e="string"==typeof r&&r.startsWith("mark_")?r.slice(5):r,n="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(n)||n<0||n>19)continue;const i=n;t.has(i)||(t.add(i),s.push(i))}return s},hl=(e,t,s,n,r)=>e.sessions.map(e=>{const i=(e=>{if(!e||0===e.byteLength)return null;try{return ol().toObject(ol().decode(e),{longs:Number,bytes:Uint8Array})}catch{return null}})(e.last_message?.payload),o=e.session_id??"",a=il(e.session_type),c=(e=>{const t=e.session_id??"",s=il(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:al(e)})(e);return{conversationId:o,conversationType:a,unreadCount:e.unread_count??0,lastMessage:ll(e.last_message,{},{payload:i,useCustomAttachmentUpload:r?.useCustomAttachmentUpload,conversationId:o,conversationType:a,currentUserId:t,org:s,app:n,singleChatPeerDisplay:"singleChat"===a?c:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:ul(e.marks),readAt:e.read_receipt,remindType:(d=e.remind_type,d===sl?"ALL":d===nl?"AT":d===rl?"NONE":"DEFAULT"),conversationName:c.conversationName,conversationAvatar:c.conversationAvatar};var d}),pl={nested:{easemob:{nested:{sessionlist:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},JID:{fields:{app_key:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},client_resource:{type:"string",id:4}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},timestamp:{type:"uint64",id:4},payload:{type:"bytes",id:6}}},SessionItem:{fields:{session_id:{type:"string",id:1},session_type:{type:"int32",id:2},last_message:{type:"Meta",id:3},updated_at:{type:"int64",id:6},pinned_time:{type:"int64",id:7},unread_count:{type:"uint32",id:8},marks:{rule:"repeated",type:"string",id:9},read_receipt:{type:"int64",id:10},remind_type:{type:"int32",id:11},group_name:{type:"string",id:12},group_avatar:{type:"string",id:13},metadata:{type:"string",id:14}}},GetSessionListRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},need_empty_session:{type:"bool",id:7},need_session_mark:{type:"bool",id:8}}},GetSessionListResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},sessions:{rule:"repeated",type:"SessionItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let ml=null,fl=!1;const gl=()=>ml||(fl||(ot.util.Long=nt,ot.configure(),fl=!0),st(),ml=ot.Root.fromJSON(pl),it(ml),ml),yl=e=>gl().lookupType(e),Il=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if("bigint"==typeof e)return Number(e);if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},vl=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Il(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Il(t.protocol_version)??Il(t.protocolVersion)??0}},Cl=e=>{if(!e||"object"!=typeof e)return;const t=e;return{appKey:"string"==typeof t.app_key?t.app_key:"string"==typeof t.appKey?t.appKey:void 0,name:"string"==typeof t.name?t.name:void 0,domain:"string"==typeof t.domain?t.domain:void 0,clientResource:"string"==typeof t.client_resource?t.client_resource:"string"==typeof t.clientResource?t.clientResource:void 0}},Sl=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Il(t.id)?String(Il(t.id)):void 0,from:Cl(t.from),timestamp:Il(t.timestamp),payload:t.payload instanceof Uint8Array?t.payload:Array.isArray(t.payload)?Uint8Array.from(t.payload.filter(e=>"number"==typeof e)):void 0}};class El{constructor(){this.requestType=yl("easemob.sessionlist.GetSessionListRequest"),this.responseType=yl("easemob.sessionlist.GetSessionListResponse"),this.errorType=yl("easemob.sessionlist.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,need_empty_session:e.includeEmpty??!1,need_session_mark:e.includeMark??!0});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const s=this.tryDecodeResponse(e);if(s)return s;const n=this.tryDecodeRequest(e);return n||{type:Yd}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=Il(t.type);return s!==Xd?null:{type:s,header:vl(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Il(t.last_sync_time)??0,includeEmpty:!0===t.need_empty_session,includeMark:!0===t.need_session_mark}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),s=Il(t.type);return s!==Zd?null:{type:s,header:vl(t.header),sessions:Array.isArray(t.sessions)?t.sessions.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{session_id:"string"==typeof t.session_id?t.session_id:void 0,session_type:Il(t.session_type),last_message:Sl(t.last_message),updated_at:Il(t.updated_at),pinned_time:Il(t.pinned_time),unread_count:Il(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Il(t.read_receipt),remind_type:Il(t.remind_type),group_name:"string"==typeof t.group_name?t.group_name:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:void 0,metadata:"string"==typeof t.metadata?t.metadata:void 0}})(e)):[],isLastBatch:!0===t.is_last_batch,lastSyncFinishedTs:Il(t.last_sync_finished_ts)}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),s=Il(t.type);return s!==Jd?null:{type:s,header:vl(t.header),code:Il(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const bl=async t=>{const s=t.client.getCacheManager(),n=t.client.getRestContext(),r=t.client.getSessionListSyncWsUrls();if(!s||0===r.length)throw new C("session-list sync websocket is unavailable",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[i,o]=n.appKey.split("#");if(!i||!o)throw new M("session-list appKey is invalid",{code:e.VALIDATION_INVALID_FORMAT,details:{appKey:n.appKey}});const c=s.loadSessionListCheckpoint(),d=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:t.session.getRequestId(),resource:n.clientResource,org:i,app:o,username:n.userId,lastSyncTime:(l=c.sessionsLastSyncTs,Math.max(0,l-Y)),params:t.params});var l;const u=new El;let h=0,p=c.sessionsLastSyncTs;return await t.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:t.session.getRequestId(),encode:()=>u.encodeRequest(d),decode:e=>{const t=u.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:s=>{if(5===s.type&&"code"in s&&"message"in s)throw 1002===(r=s).code?new D(r.message,{code:e.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:r.code}}):1003===r.code?new L(r.message,e.SERVER_BUSY,{details:{protocol:"session-list",responseCode:r.code}}):1501===r.code||1001===r.code?new M(r.message,{code:e.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:r.code}}):1503===r.code?new L(r.message,e.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:r.code}}):(r.code,new L(r.message,e.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:r.code}}));var r;if(11!==s.type)throw new L("session-list response type is invalid",e.MESSAGE_DECODE_FAILED,{details:{responseType:s.type}});const c=s,d=c.header?.requestId;if(d&&d!==t.session.getRequestId())return;h+=1,a.debug("Decoded session-list sync raw response",{requestId:t.session.getRequestId(),batchSequence:h,response:c});const l=hl(c,n.userId,i,o,t.client.getMessageCreationOptions?.()),u=t.session.pushBatch({requestId:t.session.getRequestId(),batchSequence:h,sessions:l,isLastBatch:!0===c.isLastBatch,lastSyncFinishedTs:c.lastSyncFinishedTs});if("number"==typeof c.lastSyncFinishedTs&&(p=c.lastSyncFinishedTs),!u.done)return;return{done:!0,result:{items:t.session.getItems(),lastSyncFinishedTs:p}}}})},Tl=()=>Date.now(),Al={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},wl=(e,t)=>({status:e,determinedAt:Tl(),reason:t}),Nl=t=>t instanceof L&&(t.code===e.SERVER_BUSY||1103===t.code),Ml=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Nl(e)});class Rl{constructor(e){this.running=null,this.currentSession=null,this.activeFinish=null,this.cancelled=!1,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}cancel(){this.cancelForTeardown()?.()}cancelForTeardown(){this.cancelled=!0,this.currentSession?.cancel();const t=this.activeFinish;return this.activeFinish=null,t?()=>{t({dataType:"conversation",status:"failed",error:{dataType:"conversation",code:e.SESSION_LIST_CANCELLED,stage:"cancelled",message:"session-list sync cancelled",retryable:!1}})}:null}refresh(e){return this.cancelled?Promise.resolve([]):(this.running||(this.currentSession=new $d,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running)}async runRefresh(t,s){const n=this.client.getCacheManager();if(!n)return[];let r=!1;const i=e=>{r||(r=!0,this.client.emitSyncDataFinished(e))};this.activeFinish=i;try{this.client.emitSyncDataStart("conversation");const e=await this.tryDirectFallback(n);if(this.cancelled)return[];if(e)return this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"success"}),e;const r=n.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let a=0;const c=await async function(e,t,s={}){const n={...Gd,...s};let r;for(let o=1;o<=n.maxAttempts;o++)try{return await e()}catch(i){if(r=i,!t(i))throw i;if(o>=n.maxAttempts)throw i;const e=Vd(o,n);await Hd(e)}throw r}(async()=>{if(this.cancelled)throw new L("session-list sync controller is cancelled");a+=1;const e=1===a?t:this.createRetrySession();e.start();try{return await bl({client:this.client,session:e,params:s})}catch(n){throw this.cancelled||e.fail(),n}},e=>!this.cancelled&&Nl(e),Al);if(this.cancelled)return[];const d={result:c,syncStartedAt:t.getStartedAt()},l=d.result.items;this.capabilityState={status:"available",determinedAt:Tl()};const u={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Tl()};try{if(await n.commitSessionListSync({items:l,mode:r,checkpoint:u,syncStartedAt:d.syncStartedAt}),this.cancelled)return[]}catch(o){if(this.cancelled)return[];t.fail();const e=new J("Session-list final persistence failed",{details:{cause:o instanceof Error?o.message:String(o)}});return this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"failed",error:Ml(e)}),n.loadSessionList()}const h=n.loadSessionList();return n.updateConversationsFromServer(h.map(Et),{syncStartedAt:d.syncStartedAt}),await n.flushPending(),this.cancelled?[]:(this.client.emitConversationListUpdate("conversation","full"===r),i({dataType:"conversation",status:"success"}),h)}catch(o){if(this.cancelled)return[];const s=o instanceof L?o:new L(o instanceof Error?o.message:String(o));t.fail();const r=(t=>t.code===e.OPERATION_UNSUPPORTED||t.code===e.AUTH_UNAUTHORIZED?{capabilityState:wl("unsupported",t.message),shouldUseFallback:!0}:t.code===e.AUTH_TOKEN_EXPIRED||t.code===e.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:t.code===e.SERVER_BUSY||1103===t.code?{shouldUseFallback:!0,shouldRetry:!0}:t.code===e.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(s);r.capabilityState&&(this.capabilityState=r.capabilityState),r.shouldResetCheckpoint&&n.resetSessionListCheckpoint();const a=await this.buildFallbackSessionList(n);return this.cancelled?[]:(r.shouldUseFallback&&n.replaceSessionList(a),this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"failed",error:Ml(s)}),a)}finally{this.activeFinish===i&&(this.activeFinish=null)}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}var t;const s=this.client.hasSessionListSyncWsUrl(),n=this.client.isSessionListDnsProbeAvailable();if(!s&&!n){this.capabilityState=wl("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}return null}createRetrySession(){return new $d}async buildFallbackSessionList(e){return await(async(e,t)=>await Qd(e,t))(e.loadConversationSummaries(),this.client)}}const _l=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Dl=async t=>{if("string"==typeof t||_l(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):_l(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength))(t);if((e=>"undefined"!=typeof Blob&&e instanceof Blob&&"function"==typeof e.arrayBuffer||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(t))return new Uint8Array(await t.arrayBuffer());throw new L("sync websocket frame payload type is invalid",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof t}})},Ul=e=>{const t=Math.max(e-1,0),s=ne*Math.pow(re,t);return Math.min(s,se)},Ll=async e=>{await new Promise(t=>{setTimeout(t,e)})},Ol=e=>e instanceof Error?e:new Error(String(e));class kl{constructor(e){this.pending=/* @__PURE__ */new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(t){if(this.cancelled)throw new L("sync websocket session is cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:t.requestId}});if(this.pending.has(t.requestId))throw new L("sync websocket requestId is duplicated",e.VALIDATION_INVALID_FORMAT,{details:{stage:"request_send",requestId:t.requestId}});this.clearCompleteCloseTimer();const s=new Promise((e,s)=>{this.pending.set(t.requestId,{...t,resolve:e,reject:s})});s.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(t.requestId))}catch(n){this.rejectPending(t.requestId,Ol(n))}return await s}cancel(t="sync-websocket-cancelled"){this.cancelled=!0;const s=new L("sync websocket cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",reason:t}});this.rejectAll(s),this.closeSocket(4001,t),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==o.OPEN){if(this.connectPromise)return await this.connectPromise;this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let t=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&a.warn("sync websocket retry started",this.buildLogContext({reason:t?.message}));try{return void(await this.openSocket())}catch(s){if(t=Ol(s),this.cancelled||0===this.pending.size)throw t;if(this.attempt>=3)throw a.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),t;const e=Ul(this.attempt);a.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:e,reason:t.message})),await Ll(e)}}throw new C("sync websocket retry exhausted",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:t?.message??"unknown"}})}async openSocket(){const t=await this.getUrls();if(0===t.length)throw new C("sync websocket urls are unavailable",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const s=t[this.urlIndex%t.length];if(this.urlIndex+=1,!s)throw new C("sync websocket url is invalid",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=s,this.state="connecting",a.warn("sync websocket connect started",this.buildLogContext());const n=ji(this.socketAdapter);let r=null;try{const e=await Promise.race([n.connect({url:s}),new Promise((e,t)=>{r=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},X)})]);r&&clearTimeout(r),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),a.warn("sync websocket connected",this.buildLogContext())}catch(i){if(r&&clearTimeout(r),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),i instanceof C)throw i;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:i instanceof Error?i.message:String(i)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await Dl(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Ol(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(t){const s=[];let n=null;for(const e of this.pending.values())try{const s=e.decode(t);if(s.requestId&&s.requestId===e.requestId){try{const t=await e.onFrame(s.frame,this.socket);t?.done&&(this.pending.delete(e.requestId),e.resolve(t.result),this.closeIfComplete())}catch(r){this.pending.delete(e.requestId),e.reject(Ol(r)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||n||(n={pending:e,frame:s.frame})}catch(r){s.push(Ol(r))}if(n)return await n.pending.onFrame(n.frame,this.socket),!0;if(this.pending.size>0&&s.length===this.pending.size)throw new L("sync websocket frame decode failed",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:s[0]?.message}});return a.warn("sync websocket frame ignored",this.buildLogContext({reason:s[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(a.warn("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(Ol(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===o.OPEN)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),a.warn("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const s=this.pending.get(e);s&&(this.pending.delete(e),s.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(a.warn("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},Z))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},ee))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const s=this.socket;this.socket=null,!s||s.readyState>=o.CLOSING||(this.state="closing",s.close(e,t))}buildConnectionError(t,s,n={}){return new C(t,{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:s,url:this.activeUrl,...n}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:te(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const Pl=async(t,s,n)=>{const{orgName:r,appName:i}=P(t.appKey),o=`/${r}/${i}/user/${encodeURIComponent(t.userId)}/roster/metadata/version`,a=new ie(t.restBaseUrl,{requestAdapter:n,includeRequestId:!0});a.setAuthToken(t.token);try{return((t,s)=>{const n=Date.now(),r=e=>{const t="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:t,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??t!==s,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:n}};if(wt(t))return wt(t.data)?r(t.data):r(t);throw new M("Invalid contact metadata response",{code:e.VALIDATION_INVALID_FORMAT,details:{payload:t}})})(await a.get(o),s)}catch(c){if(c instanceof M)throw c;const t=c instanceof L&&c.details?c.details:{};throw new oe("Contact metadata request failed",{code:e.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:c instanceof Error?c.message:String(c),httpStatus:"number"==typeof t.httpStatus?t.httpStatus:void 0,sourceCode:c instanceof L?c.code:void 0}})}},xl=e=>Nt.string().regex(/^https?:\/\/\S+$/i,e),Fl=Nt.object({appKey:Nt.string().min(1,"appKey is required").optional(),appId:Nt.string().min(1,"appId is required").optional(),enableUserInfoSync:Nt.boolean().optional(),enableSyncData:Nt.array(Nt.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Nt.boolean().optional(),deleteConversationOnGroupDestroyed:Nt.boolean().optional(),syncConversationListConfig:Nt.object({includeEmpty:Nt.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:Nt.boolean().optional(),useFixedDeviceId:Nt.boolean().optional(),deviceId:Nt.string().min(1,"deviceId is required").optional(),serviceConfig:Nt.object({dnsConfigUrls:Nt.array(xl("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:Nt.object({restApiUrl:xl("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(Bl="serviceConfig.serverUrls.wsUrl must be a valid URL",Nt.string().regex(/^wss?:\/\/\S+$/i,Bl)).optional()}).optional()}).optional(),useReplacedMessageContents:Nt.boolean().optional(),customDeviceName:Nt.string().min(1,"customDeviceName is required").optional(),customOSPlatform:Nt.number().int("customOSPlatform must be an integer").min(1,"customOSPlatform must be between 1 and 100").max(100,"customOSPlatform must be between 1 and 100").optional(),uiKitVersion:Nt.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Nt.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:Nt.array(Nt.unknown()).optional(),platformAdapterOptions:Nt.object({prefer:Nt.enum(["web","wechat-miniapp","qq-miniapp","toutiao-miniapp","baidu-miniapp","alipay-miniapp","dingtalk-miniapp","lark-miniapp","kuaishou-miniapp","jd-miniapp","360-miniapp","harmony-miniapp","quickapp","uniapp","react-native","electron-renderer","electron-main","unknown"]).optional(),runtimeInput:Nt.custom(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:Nt.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:Nt.custom(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const s=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===s?t.addIssue({code:Nt.ZodIssueCode.custom,path:["appKey"],message:"appKey or appId is required"}):s>1&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const n=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,r=n?.serverUrls&&"object"==typeof n.serverUrls?n.serverUrls:void 0;n?.dnsConfigUrls&&r&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),r&&(void 0!==e.appId&&t.addIssue({code:Nt.ZodIssueCode.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),r?.restApiUrl||t.addIssue({code:Nt.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),r?.wsUrl||t.addIssue({code:Nt.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var Bl;const ql=Nt.object({userId:Nt.string().min(1,"userId is required"),token:Nt.string().min(1,"token is required")}),Kl=Nt.object({timeoutMs:Nt.number().int("timeoutMs must be an integer").min(ae,`timeoutMs must be at least ${ae}`).max(ce,`timeoutMs must be at most ${ce}`).optional()}).strict(),Gl=Nt.string().trim().min(1,"token is required"),Vl=Nt.object({channelName:Nt.string().trim().min(1,"channelName is required").optional()}).optional(),Hl=Nt.array(Nt.number({invalid_type_error:"rtcUid must be a number"}).int("rtcUid must be an integer").min(0,"rtcUid must be greater than or equal to 0").max(Number.MAX_SAFE_INTEGER,"rtcUid must be a safe integer")).nonempty("rtcUids is required").transform(e=>Array.from(new Set(e))),zl=Nt.object({protocol:Nt.string(),domain:Nt.string().optional(),ip:Nt.string().optional(),port:Nt.union([Nt.string(),Nt.number()]).optional()}).passthrough(),jl=Nt.object({app_key:Nt.string().optional(),rest:Nt.object({hosts:Nt.array(zl).nonempty()}),"msync-wx":Nt.object({hosts:Nt.array(zl).nonempty()}),"sync-ws":Nt.object({hosts:Nt.array(zl).nonempty()}).optional(),enableReportLogs:Nt.enum(["true","false"]).optional(),reportInterval:Nt.number().positive().finite().optional(),enableDataReport:Nt.enum(["true","false"]).optional(),enableMd5Check:Nt.enum(["true","false"]).optional(),uploadinparts_enable:Nt.enum(["true","false"]).optional()}).passthrough(),Wl="5.1.3",Ql=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],$l=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function Yl(e){return"object"==typeof e&&null!==e}function Jl(e){return Array.isArray(e)?{hosts:e}:function(e){return Yl(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Xl(e){if(!Yl(e))return Ze.validateOrThrow(jl,e);const t=Jl(e.rest),s=function(e,t,s){for(const n of t){const t=Jl(e[n]);if(t)return{key:n,section:t}}for(const[n,r]of Object.entries(e)){if(!s(n))continue;const e=Jl(r);if(e)return{key:n,section:e}}}(e,$l,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),n={...e,rest:t??e.rest,"msync-wx":s?.section},r="true"===(i=e.enableReportLogs)||!0===i?"true":"false"===i||!1===i?"false":void 0;var i;r&&(n.enableReportLogs=r);const o=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==o?n.reportInterval=o:delete n.reportInterval;const c=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);c?n.enableDataReport=c:delete n.enableDataReport;const d=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);d?n.enableMd5Check=d:delete n.enableMd5Check;const l=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return l?n.uploadinparts_enable=l:delete n.uploadinparts_enable,s&&"msync-wx"!==s.key&&a.warn("DNS config websocket section normalized",{sourceKey:s.key}),Ze.validateOrThrow(jl,n)}function Zl(t,s){const n=t.domain||t.ip;if(!n)throw new M("DNS host missing domain/ip",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const r=void 0!==t.port?String(t.port):"";return`${"https"===s?"wss":"ws"}://${r&&"80"!==r&&"443"!==r?`${n}:${r}`:n}/websocket`}function eu(e,t){return"https"===e?"https":"http"===e?"http":t}function tu(t,s){const n=t.domain||t.ip;if(!n)throw new M("DNS rest host missing domain/ip",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const r=void 0!==t.port?String(t.port):"";return`${s}://${r&&"80"!==r&&"443"!==r?`${n}:${r}`:n}`}function su(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function nu(e){const t=function(e){return e.filter(e=>Boolean(e.domain))}(e);return t.length>0?t:e.filter(e=>Boolean(e.domain||e.ip))}async function ru(e,t,s,n){const r=new ie(e,{requestAdapter:s,includeRequestId:!0});let i="/easemob/server.json",o=!0;try{const t=new URL(e),s=""!==t.pathname&&"/"!==t.pathname,n=""!==t.search;(s||n)&&(i="",o=!1)}catch{i="/easemob/server.json",o=!0}if(o){i=`${i}?${(void 0!==t.appId?Mt({app_id:t.appId,sdk_version:Wl,file_version:"1"}):Mt({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return Xl(await r.get(i,{timeout:n}))}async function iu(t){const s=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:Ql;if(0===s.length)throw new M("DNS_CONFIG list is empty",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const n=t.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let r;for(const c of s){const s=t.loginDeadline,i=s?.remainingMs();if(s&&void 0!==i&&i<=0)throw s.createTimeoutError();try{const s=void 0!==t.appId?{appId:t.appId}:{appKey:t.appKey},r=void 0===i?void 0:Math.min(de,i),o=await ru(c,s,t.requestAdapter,r),a=void 0!==t.appId?o.app_key:t.appKey;if("string"!=typeof a||0===a.length)throw new M("DNS app_key is required for appId initialization",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const d=nu(su(o["msync-wx"].hosts,n));if(0===d.length)throw new M("DNS msync-wx hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const l=d[0];if(!l)throw new M("DNS msync-wx hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const u=su(o.rest.hosts,n);if(0===u.length)throw new M("DNS rest hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const h=u[0];if(!h)throw new M("DNS rest hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const p=d.map(e=>Zl(e,eu(e.protocol,n))),m=Zl(l,eu(l.protocol,n));return{appKey:a,websocketUrl:m,websocketUrls:p,baseUrl:c,restBaseUrl:tu(h,eu(h.protocol,n)),dnsConfig:o}}catch(o){if(s&&s.remainingMs()<=0)throw s.createTimeoutError();a.warn("DNS config candidate failed",{baseUrl:c,reason:o instanceof Error?o.message:String(o),error:o instanceof Error&&"function"==typeof o.toJSON?o.toJSON():o}),r=o}}const i={stage:"dns"};throw r&&(i.reason=r.message,"code"in r&&"number"==typeof r.code&&(i.causeCode=r.code)),new C("DNS_CONFIG exhausted",{code:e.CONNECTION_DNSLIST_FAILED,details:i})}const ou=e=>{const t=(e=>{const t=e.trim(),s=/^(https?):\/\//i.exec(t);if(!s?.[1])throw new M("REST API URL must use http or https protocol");const n=s[1].toLowerCase(),r=t.slice(s[0].length),i=r.search(/[/?#]/),o=i>=0?r.slice(0,i):r,a=o.lastIndexOf("@"),c=a>=0?o.slice(a+1):o;if(!c)throw new M("REST API URL host is required");let d,l;if(c.startsWith("[")){const e=c.indexOf("]");if(e<=1)throw new M("REST API URL IPv6 host is invalid");d=c.slice(0,e+1);const t=c.slice(e+1);if(t){if(!t.startsWith(":"))throw new M("REST API URL authority is invalid");l=t.slice(1)}}else{const e=c.lastIndexOf(":");if(e>=0){if(c.indexOf(":")!==e)throw new M("REST API URL IPv6 host must use brackets");d=c.slice(0,e),l=c.slice(e+1)}else d=c}if(!d)throw new M("REST API URL host is required");if(void 0!==l){const e=Number(l);if(!/^\d+$/.test(l)||e<1||e>65535)throw new M("REST API URL port is invalid")}return{protocol:n,host:d,port:l}})(e),s="http"===t.protocol&&"80"===t.port||"https"===t.protocol&&"443"===t.port,n="https"===t.protocol?"wss":"ws",r=t.port&&!s?`:${t.port}`:"";return`${n}://${t.host}${r}/ws`},au=t=>new M(t,{code:e.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),cu=e=>{if(!wt(e))throw au("Invalid REST response");return wt(e.data)?e.data:e},du=(e,t)=>{for(const s of t){const t=e[s];if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&t.trim().length>0){const e=Number(t);if(Number.isFinite(e))return e}}},lu=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},uu=e=>{const{orgName:t,appName:s}=P(e.appKey);return`/${t}/${s}`},hu=async(e,t)=>{const s=await e.get((e=>`${uu(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=cu(e),s=du(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw au("Invalid token expires response");return s})(s)},pu=async(e,t,s)=>{const n=await e.get(((e,t)=>{const s=Mt({channelName:t?.channelName??"*"});return`${uu(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${s.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=cu(e);return{appId:lu(t,["app_id","appId"])??"",rtcToken:lu(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:lu(t,["channel_name","channelName"])??"",rtcUid:du(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:du(t,["expires_in","expire","expireAt"])??0}})(n)},mu=async(e,t,s)=>{const n=await e.post((e=>`${uu(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=cu(e),s={};for(const[n,r]of Object.entries(t)){const e=Number(n);!Number.isSafeInteger(e)||e<0||"string"!=typeof r||(s[e]=r)}return s})(n)},fu=async(e,t)=>{const s=await e.get((e=>`${uu(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=wt(e)&&Array.isArray(e.data)?e.data:[],n=[];for(const r of s){if(!wt(r))continue;const e=lu(r,["res","resource","clientResource"]);e&&e!==t.clientResource&&n.push(`${t.userId}/${e}`)}return n})(s,t)};class gu{constructor(e){this.options=e,this.pendingGroups=/* @__PURE__ */new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=/* @__PURE__ */new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,s){if(!e||!t)return;const n=this.pendingGroups.get(e)??/* @__PURE__ */new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,n),this.pendingOrder.push(e));const r=n.get(t);n.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(r?.namecardUpdateTime,s)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const s=Array.from(t.values()),n=Math.max(1,this.options.maxBatchSize);for(let r=0;r<s.length;r+=n)this.readyGroups.push({groupId:e,targets:s.slice(r,r+n)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{a.warn("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),s=t-e;return s<=0?t:e+Math.floor(Math.random()*(s+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class yu{constructor(e){this.options=e,this.pendingTargets=/* @__PURE__ */new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let s=0;s<e.length;s+=t)this.readyBatches.push(e.slice(s,s+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const s=this.generation;this.activeCount+=1;const n=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let r;try{r=Promise.resolve(this.options.onFlush(n))}catch(t){r=Promise.reject(t instanceof Error?t:new Error(String(t)))}r.catch(t=>{const n=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(a.warn("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:n.length>0,error:t instanceof Error?t.message:String(t)}),s===this.generation&&0!==n.length){for(const e of n)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const s of this.readyBatches){const t=s.findIndex(t=>t.userId===e.userId);if(t>=0){const n=s[t];return void(n&&(s[t]=this.mergeTarget(n,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Iu{constructor(e,t,s=Date.now){this.attemptId=e,this.timeoutMs=t,this.now=s,this.timeoutId=null,this.status="active",this.expiresAt=this.now()+t,this.timeoutPromise=new Promise((e,s)=>{this.timeoutId=setTimeout(()=>{"active"===this.status&&(this.status="expired",this.timeoutId=null,s(this.createTimeoutError()))},t)}),this.timeoutPromise.catch(()=>{})}getStatus(){return this.status}remainingMs(){return"expired"===this.status?0:Math.max(0,this.expiresAt-this.now())}clamp(e){return Math.max(0,Math.min(e,this.remainingMs()))}race(e){return"expired"===this.status||0===this.remainingMs()?(e.catch(()=>{}),this.expire(),Promise.reject(this.createTimeoutError())):"active"!==this.status?e:Promise.race([e,this.timeoutPromise])}markProvisionReceived(){return"active"===this.status&&(this.status="provision-received",this.clearTimer(),!0)}expire(){"active"===this.status&&(this.status="expired",this.clearTimer())}dispose(){"active"===this.status&&(this.status="disposed"),this.clearTimer()}createTimeoutError(){return new C("Login timeout",{code:e.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",timeoutMs:this.timeoutMs,attemptId:this.attemptId,retryable:!0}})}clearTimer(){null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const vu=Ue(Le,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Cu=class t{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=Be.DISCONNECTED,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=/* @__PURE__ */new Set,this.managerSessionGeneration=0,this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null,this.postLoginTaskContext=null,this.terminalSessionCleanupTask=null,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=zi(this.config.platformAdapterOptions)),this.managerRegistry=/* @__PURE__ */new Map,this.managerCapabilities=/* @__PURE__ */new Map,this.eventHub=new Kd,Oe(e=>{this.eventHub.dispatch(ut.LOG,e)}),this.managerEventContext={addEventHandler:(e,t)=>{this.eventHub.addEventHandler(e,t)},removeEventHandler:e=>{this.eventHub.removeEventHandler(e)},dispatch:(e,t)=>{this.eventHub.dispatch(e,t)}},this.userInfoHydrationQueue=new yu({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:ue,maxRetries:le,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new gu({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:pe,maxBatchSize:he,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[qe.CONNECTING]:e=>{this.updateState(e.state)},[qe.CONNECTED]:e=>{this.updateState(e.state)},[qe.DISCONNECTED]:e=>{this.updateState(e.state),this.isTerminalManagerSessionDisconnect(e)&&this.startTerminalSessionCleanup(e)},[qe.RECONNECT_FAILED]:e=>{this.updateState(e.state)},[ct.MESSAGE]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[ct.MESSAGE_UPDATED]:e=>{this.patchConversationLastMessage(e,{...e.message,body:{...e.message.body}})},[ct.MESSAGE_READ_RECEIPTS]:e=>{const t=e.flatMap(e=>"singleChat"===e.conversationType?e.messageIds.map(t=>({conversationId:e.conversationId,conversationType:e.conversationType,messageId:t,patch:{isPeerRead:!0}})):e.receiptDetails.map(t=>({conversationId:e.conversationId,conversationType:e.conversationType,messageId:t.messageId,patch:{groupReadCount:t.count}})));this.cacheManager?.patchConversationLastMessages(t)&&this.emitConversationListUpdate("message")},[ct.REACTION_CHANGED]:e=>{this.patchConversationLastMessage(e,{reactions:[...e.reactions]})},[ct.STREAM_MESSAGE]:e=>{this.handleIncomingConversationStreamMessage(e)},[Ge.MESSAGE_SENT]:e=>{this.handleOutgoingConversationMessage(e)},[ct.MULTI_DEVICE_CONTACT]:e=>{this.handleMultiDeviceContactEvent(e)},[ct.MULTI_DEVICE_CONVERSATION]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[dt.ADDED]:e=>this.handleIncomingContactRosterEvent("add",e),[dt.AGREED]:e=>this.handleIncomingContactRosterEvent("add",e),[dt.INVITED]:e=>this.handleIncomingContactRosterEvent("none",e),[dt.REFUSE]:e=>this.handleIncomingContactRosterEvent("none",e),[dt.DELETED]:e=>this.handleIncomingContactRosterEvent("remove",e),[Ge.GROUP_NOTIFY]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===at.GROUP_DESTROYED&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[Ge.CHATROOM_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[Ge.CHAT_THREAD_NOTIFY]:e=>{const t=((e,t,s,n=!1)=>{const r=t.find(t=>"groupChat"===t.conversationType&&t.conversationId===e.muc_parent_id&&t.lastMessage&&(e.msg_parent_id?t.lastMessage.msgServerId===e.msg_parent_id:t.lastMessage.chatThreadOverview?.chatThreadId===e.id)),i=r?.lastMessage;if(!r||!i||!e.id)return null;const o={conversationId:r.conversationId,conversationType:"groupChat",messageId:i.msgServerId};if("delete"===e.operation)return i.chatThreadOverview?.chatThreadId===e.id?{...o,patch:{chatThreadOverview:void 0}}:null;if(!["create","update","update_msg"].includes(e.operation))return null;const a=new ho(s,n).resolveChatThreadOverview({thread_overview:{id:e.id,muc_parent_id:e.muc_parent_id,name:e.name,message_count:e.message_count,update_timestamp:e.timestamp,last_message:e.last_message}});return a?(Object.prototype.hasOwnProperty.call(e,"last_message")||Reflect.deleteProperty(a,"lastMessage"),{...o,patch:{chatThreadOverview:{...i.chatThreadOverview?.chatThreadId===e.id?i.chatThreadOverview:{},...a}}}):null})(e.payload,this.cacheManager?.loadSessionList()??[],this.getCurrentUserId()??"",this.config.useCustomAttachmentUpload);return t&&this.patchConversationLastMessage(t,t.patch),this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e})},[Ge.USER_INFO_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(s){const n=Ze.validateOrThrow(Fl,s),r=n.customOSPlatform,i=t.normalizeServiceConfig(n.serviceConfig),o={appKey:n.appKey,appId:n.appId,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:t.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==r?n.customDeviceName:void 0,customOSPlatform:r,uiKitVersion:n.uiKitVersion,loginExtensionInfo:n.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:ye,userInfoBatchSize:ge,groupNamecardWindowMs:fe,groupNamecardMaxConcurrency:me},platformAdapterOptions:n.platformAdapterOptions},a=s.managers??[];if(t.instance){if(!t.isSameConfig(t.instance.config,o))throw new M("ChatClient already initialized with different config",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:t.instance.config,next:o}});return a.length>0&&t.instance.registerManagers(a),t.instance.validateOptionalCapabilityDependencies(),t.instance}return t.instance=new t(o),a.length>0&&t.instance.registerManagers(a),t.instance.validateOptionalCapabilityDependencies(),t.instance}async login(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const r=Ze.validateOrThrow(ql,s),i=Ze.validateOrThrow(Kl,n??{});if(await this.waitForTerminalSessionCleanup(),this.state===Be.CONNECTING||this.state===Be.CONNECTED){const t=this.currentUserId&&this.currentUserId!==r.userId;throw new C(t?"Another user is already logged in":"ChatClient is already connecting or connected",{code:t?e.USER_ALREADY_LOGIN_ANOTHER:e.AUTH_ALREADY_LOGIN,details:{stage:"auth",...t?{currentUserId:this.currentUserId,nextUserId:r.userId}:{}}})}const o=++this.loginAttempt,c=new Iu(o,i.timeoutMs??Ie);try{let t=this.config.appKey??null;this.activeAppKey=t,a.warn("Login started",{userId:r.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const s=this.platformAdapter??zi(this.config.platformAdapterOptions);this.platformAdapter=s,ve({requestAdapter:s.request,onDiagnostic:(e,t)=>{a.warn(e,t)}});const n=Ce({appKey:t??"default#appkey",uid:r.userId,sdkVersion:Wl,platform:s.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),i=s.runtime.getNetworkType?.();i&&i.then(e=>{Se(e)}).catch(()=>{Se("unknown")});const l=E({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:r.userId});let u,h,p;this.updateState(Be.CONNECTING),this.logReportEnabled=!1,Ee("unknown");let m,f=!1,g=!1,y=!0;if("dns"===this.config.serviceConfig.mode){const e=l?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const n=await c.race(iu(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:c}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:c}));t=n.appKey,this.activeAppKey=t,be({appKey:t}),a.warn("DNS resolved for login",{baseUrl:n.baseUrl,websocketUrl:n.websocketUrl,restBaseUrl:n.restBaseUrl,syncWebSocketSource:"rest"}),u=n.websocketUrl,h=n.websocketUrls;const r=ou(n.restBaseUrl);this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!0,p=n.restBaseUrl,f="true"===n.dnsConfig.enableReportLogs,m=n.dnsConfig.reportInterval,g="true"===n.dnsConfig.enableMd5Check,y="false"!==n.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),Te(n.dnsConfig.enableDataReport),a.debug("DNS report switch resolved",{enabled:f})}catch(d){const t=d instanceof L?d.code:-1,s=d instanceof Error?d.message:String(d);throw e?.finish({code:t,success:!1,description:s}),l?.finish({code:t,success:!1,description:s}),Te(void 0),Ee("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),c.dispose(),d}}else{const t=this.config.serviceConfig.serverUrls;if(!t?.wsUrl||!t.restApiUrl){const t=new M("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw l?.finish({code:t.code,success:!1,description:t.message}),Te(void 0),this.updateState(Be.DISCONNECTED),c.dispose(),t}u=t.wsUrl,p=t.restApiUrl;const s=ou(p);g=this.config.enableMd5Check,this.contactSyncWsUrls=[s],this.syncConversationListConfigWsUrls=[s],this.contactSyncDnsResolved=!1,Te(void 0)}if(!t){const t=new M("appKey is unavailable after service discovery",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(Be.DISCONNECTED),Ae(),c.dispose(),t}we({restBaseUrl:p,appKey:t,userId:r.userId,token:r.token,requestAdapter:s.request}),Ne(m),this.logReportEnabled=f,Ee(f?"enabled":"disabled");const I=this.resetCore();if(I?.(),o!==this.loginAttempt){const t=new C("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}});throw l?.finish({code:e.CONNECTION_CANCELLED,success:!1,description:t.message}),this.updateState(Be.DISCONNECTED),this.activeAppKey=this.config.appKey??null,Ae(),c.dispose(),t}const v=new Qc({serverUrl:u,serverUrls:h,userId:r.userId,token:r.token,appKey:t,restBaseUrl:p,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:g,enableMultipartUpload:y,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:n,platformAdapter:s,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub);this.core=v,we({resource:v.getClientResource()});const S=l?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:u});try{a.warn("Connecting core websocket",{serverUrl:u,restBaseUrl:p,userId:r.userId});try{await c.race(v.connect(c))}finally{c.dispose()}this.throwIfLoginSessionCancelled(o,v),S?.finish({code:200,success:!0}),l?.finish({code:0,success:!0}),a.warn("Core websocket connected",{userId:r.userId,resource:v.getClientResource()}),this.currentUserId=r.userId,be({uid:r.userId}),this.restBaseUrl=p??null,this.authToken=r.token,this.clientResource=v.getClientResource(),await this.initCacheManager(r.userId),this.throwIfLoginSessionCancelled(o,v),a.warn("Cache initialized after login",{userId:r.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),this.notifyManagersSessionReady(r.userId,this.clientResource),this.startPostLoginTasks(r.userId,o)}catch(d){const e=d instanceof L?d.code:-1,t=d instanceof Error?d.message:String(d);if(S?.finish({code:e,success:!1,description:t}),l?.finish({code:e,success:!1,description:t}),this.core===v){const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),Ae()}finally{e?.()}}throw d}}finally{c.dispose()}}startPostLoginTasks(e,t){this.cancelPostLoginTasks();const s={attemptId:t,userId:e,cancelled:!1};this.postLoginTaskContext=s,this.runPostLoginTasks(s).catch(e=>{this.isPostLoginTaskActive(s)&&a.warn("Unexpected post-login task failure",{userId:s.userId,reason:e instanceof Error?e.message:String(e)})}).finally(()=>{this.postLoginTaskContext===s&&(this.postLoginTaskContext=null)})}cancelPostLoginTasks(){this.postLoginTaskContext&&(this.postLoginTaskContext.cancelled=!0,this.postLoginTaskContext=null)}isPostLoginTaskActive(e){return!e.cancelled&&this.postLoginTaskContext===e&&e.attemptId===this.loginAttempt&&this.currentUserId===e.userId}async runPostLoginTasks(e){if(!this.isPostLoginTaskActive(e))return;if(await this.runPostLoginTask(e,"self-user-info",async()=>{await this.syncSelfUserInfoAfterLogin()}),!this.isPostLoginTaskActive(e))return;if(this.config.enableSyncData.includes("conversation")&&await this.runPostLoginTask(e,"conversation",async()=>{await this.refreshSessionList(this.config.syncConversationListConfig)}),!this.isPostLoginTaskActive(e))return;const t=this.triggerConfiguredSyncDataAfterLogin(e.userId,e),s=this.logReportEnabled?this.runPostLoginTask(e,"log-report",async()=>{await Me()}):Promise.resolve();await Promise.all([t,s])}async runPostLoginTask(e,t,s){if(this.isPostLoginTaskActive(e))try{await s()}catch(n){if(!this.isPostLoginTaskActive(e))return;a.warn("Post-login synchronization step failed",{userId:e.userId,task:t,reason:n instanceof Error?n.message:String(n)})}}async logout(){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});for(this.loginAttempt+=1,this.cancelPostLoginTasks();this.terminalSessionCleanupTask;)await this.terminalSessionCleanupTask;if(this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("logout"),!this.core){const e=this.detachSessionListSyncController();try{this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.resetManagerSessionRuntimes(),Ee("disabled"),Re(),Ae()}finally{this.contactSyncController=null,this.groupSyncController=null,this.syncWebSocketSession=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),this.logReportEnabled=!1,e?.()}return}try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await Me()}catch(s){a.warn("Report logs on logout failed",s)}await this.core.disconnect()}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),this.logReportEnabled=!1,Ee("disabled"),Re(),Ae()}finally{e?.()}}}getConnectionState(){return this.state}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new M("restBaseUrl is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new M("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new M("userId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const t=this.clientResource??this.core?.getClientResource();if(!t)throw new M("clientResource is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(t){const s=Ze.validateOrThrow(Gl,t);if(!this.core||!this.currentUserId||this.state!==Be.CONNECTED)throw new C("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const n=this.getRestContext(),r={...n},i=new ie(r.restBaseUrl,{errorMap:vu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(s),a.warn("Renew token started",{userId:n.userId});const o=await hu(i,r);if(o<=Date.now())throw new C("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const c=this.core.renewToken(s,o);return this.authToken=s,we({token:s}),a.warn("Renew token succeeded",{userId:n.userId,expireAt:o}),c}async getRTCTokenInfo(e){const t=Ze.validateOrThrow(Vl,e),s=this.getRestContext(),n=new ie(s.restBaseUrl,{errorMap:vu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return n.setAuthToken(s.token),a.warn("Get RTC token info started",{userId:s.userId,hasChannelName:Boolean(t?.channelName)}),pu(n,s,t)}async getUserIdsWithRTCUids(e){const t=Ze.validateOrThrow(Hl,e),s=this.getRestContext(),n=new ie(s.restBaseUrl,{errorMap:vu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return n.setAuthToken(s.token),a.warn("Get userIds with RTC UIDs started",{userId:s.userId,count:t.length}),mu(n,s,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new ie(e.restBaseUrl,{errorMap:vu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),a.warn("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),fu(t,e)}getCacheManager(){return this.cacheManager}getManagerByCapability(e){return this.managerCapabilities.get(e)}getUploadAdapter(){return this.platformAdapter?.upload??null}getRequestAdapter(){return this.platformAdapter?.request}addInternalEvent(e,t){this.eventHub.dispatch(e,t)}refreshSessionList(e){return this.cacheManager&&this.currentUserId?this.ensureSessionListSyncController().refresh({includeEmpty:e?.includeEmpty??this.config.syncConversationListConfig.includeEmpty,includeMark:!0}).then(e=>(this.enqueueMissingGroupSessionSenderUserInfos(e),e.map(e=>({...e})))):Promise.resolve([])}getServerUrlsConfig(){return this.config.serviceConfig.serverUrls}getSessionListSyncWsUrls(){return this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}hasSessionListSyncWsUrl(){return this.syncConversationListConfigWsUrls.length>0}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new kl({socketAdapter:this.platformAdapter?.socket,getUrls:async()=>{const e=this.getSessionListSyncWsUrls();return e.length>0?e:await this.resolveContactSyncUrls()}})),this.syncWebSocketSession}isSessionListDnsProbeAvailable(){return"dns"===this.config.serviceConfig.mode}getSessionListSyncCapabilityState(){return this.syncConversationListConfigController?.getCapabilityState()??null}markConversationAccess(e){this.cacheManager?.markConversationAccess(e)}patchConversationLastMessage(e,t){const s=this.cacheManager?.patchConversationLastMessages([{...e,patch:t}]);s&&this.emitConversationListUpdate("message")}handleIncomingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleIncomingConversationStreamMessage(e){if(!this.cacheManager)return;const t=e.msgServerId||e.msgLocalId,s=e.stream.status===ss.START_COMPLETED||e.stream.status===ss.FULL||e.stream.status===ss.COMPLETED||e.stream.status===ss.ERROR;if(!this.activeIncomingStreamMessageIds.has(t))return this.applyIncomingConversationMessagePatch(e),void(s||this.activeIncomingStreamMessageIds.add(t));if(!s)return;this.activeIncomingStreamMessageIds.delete(t);this.cacheManager.loadSessionList().some(e=>e.lastMessage?.msgServerId===t)&&this.applyIncomingConversationMessagePatch(e)}applyIncomingConversationMessagePatch(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleOutgoingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}async handleMultiDeviceConversationEvent(e){if("CONVERSATION_DELETED"!==e.operation||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e.conversationId,type:e.conversationType??"singleChat",deletedAt:e.timestamp??Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}async handleGroupDestroyedConversation(e){if(!this.config.deleteConversationOnGroupDestroyed||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e,type:"groupChat",deletedAt:Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}handleMultiDeviceContactEvent(e){if("CONTACT_REMOVE"!==e.operation||!this.cacheManager)return;this.cacheManager.applyContactRosterNotice({action:"remove",userId:e.targetUserId,rosterVersion:e.rosterVersion}).changed&&this.cacheManager.flushPending()}getContactSnapshot(){return this.cacheManager?this.cacheManager.loadContactSnapshot("cache"):null}handleIncomingContactRosterEvent(e,t){const s=this.resolveContactRosterTargetUserId(t);if(s)return this.cacheManager&&this.currentUserId&&"none"!==e&&this.cacheManager.applyContactRosterNotice({action:e,userId:s,rosterVersion:qo(t)}),this.hydrateContactRosterPayload(t,s,"remove"!==e)}resolveContactRosterTargetUserId(e){const t=this.currentUserId;return t?e.from===t&&e.to!==t?e.to:e.to===t&&e.from!==t||e.from&&e.from!==t?e.from:e.to&&e.to!==t?e.to:null:null}async hydrateContactRosterPayload(e,t,s){const n=await Rt(t,{cacheManager:this.cacheManager,fetchUserInfos:s?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=n}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(s){return a.warn("Contact roster event user info fetch failed",{userIds:e,error:s}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&a.warn("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){a.warn("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=xo(e),s=e.sender.userId;if(!s||!this.cacheManager)return;const n=this.cacheManager.getUserInfoSummaries([s],!1)[0];if(n&&(e.sender={userId:s,nickname:n.nickname??e.sender.nickname,avatarUrl:n.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(n?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(s,t.userInfoUpdateTime):n||this.userInfoHydrationQueue.enqueue(s),"groupChat"!==e.conversationType)return;const r=this.cacheManager.getGroupNamecard(e.conversationId,s,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(r?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,s,t.namecardUpdateTime):r||this.groupNamecardHydrationQueue.enqueue(e.conversationId,s)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{ko.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Po(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const s=e.map(e=>e.userId);let n;try{n=await t.getUserInfoByUserId({userIds:s})}catch(l){throw a.warn("User info hydration failed",{userIds:s,error:l}),l}const r=this.currentUserId,i=r?n.find(e=>e.userId===r):void 0,o=n.filter(e=>e.userId!==r);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),n.length>0&&this.refreshConversationDisplayFromUserInfos(n.map(e=>({userId:e.userId})),"profile");const c=new Set(n.map(e=>e.userId)),d=s.filter(e=>!c.has(e));d.length>0&&a.warn("User info hydration returned partial result",{requestedUserIds:s,missingUserIds:d})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(s){a.warn("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:s})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(s){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(s),this}async sendMessage(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!s?.sender?.userId)throw new M("sender.userId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&s.sender.userId!==this.currentUserId)throw new M("sender.userId does not match current user",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(ns(s))throw new b("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:s.msgLocalId,retryable:!1}});if(this.core&&this.state!==Be.CONNECTED&&await this.waitForSendConnectionRecovery(this.core),!this.core||this.state!==Be.CONNECTED)throw new b("ChatClient is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:s.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(s),this.core.sendMessage(s,n)}async waitForSendConnectionRecovery(e){let t=null;const s=e.recoverConnectionForSend().then(()=>!0).catch(e=>(a.warn("Send connection recovery failed",{error:e instanceof Error?e.message:String(e)}),!1)),n=new Promise(e=>{t=setTimeout(()=>{e(!1)},_e)}),r=await Promise.race([s,n]);t&&clearTimeout(t),r||a.warn("Send connection recovery wait timed out",{timeoutMs:_e,state:this.state})}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",s){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),s).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=/* @__PURE__ */new Set;for(const r of e){const e="groupChat"===r.conversationType?r.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const s=this.cacheManager.getUserInfoSummaries([...t],!1),n=new Set(s.map(e=>e.userId));for(const r of t)n.has(r)||this.userInfoHydrationQueue.enqueue(r)}dispatchUserGroupNamecardUpdated(e,t,s){e&&t&&this.eventHub.dispatch(at.USER_GROUP_NAMECARD_UPDATED,{groupId:e,userId:t,namecard:s})}async downloadAndParseCombinePayload(s){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(s)}async sendMessageAction(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendMessageAction(s,n)}async sendChatRoomOperation(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(s,n)}async downloadAttachment(s){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.downloadAttachment(s)}decodeServerMessageMeta(t){if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.decodeServerMessageMeta(t)}registerManagers(t){if(0===t.length)return;const s=/* @__PURE__ */new Set;for(const n of t){const t=this.resolveManagerKey(n);if(s.has(t))throw this.buildManagerValidationError(`Manager key duplicated: ${t}`,e.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t});s.add(t)}for(const e of t)this.registerManagerInput(e)}registerManagerInput(e){return t.isManagerConstructor(e)?this.registerManagerConstructor(e):this.registerManagerInstance(e)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),s=this.managerRegistry.get(t);if(s){if(s.constructor===e)return s;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const n=new e;return n.bind(this,this.managerEventContext),this.managerRegistry.set(t,n),this.registerManagerCapabilities(n),this.attachManager(t,n),this.notifyManagerSessionReady(n),n}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),s=this.managerRegistry.get(t);if(s){if(s===e)return e;if(s.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),this.notifyManagerSessionReady(e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const s=this.getManagerByCapability(e);return s?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(t,s,n){return new M(`${t} requires explicit manager capability: ${s}`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} requires explicit manager capability: ${s}`,rule:"dependency"}],capability:s,requiredManagers:n}})}resolveManagerKey(s){if(t.isManagerConstructor(s))return this.getManagerKeyFromConstructor(s);if("object"!=typeof s||null===s)throw this.buildManagerValidationError("Manager must be constructor or instance",e.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof s});return this.getManagerKeyFromInstance(s)}getManagerKeyFromConstructor(t){const s=t.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.VALIDATION_REQUIRED,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(t)});return s}getManagerKeyFromInstance(t){const s=t.constructor.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.VALIDATION_REQUIRED,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(t)});return s}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,s,n,r){return new M(e,{code:t,details:{fields:[{path:s,message:e,rule:n}],...r}})}buildManagerConflictError(t,s,n,r){return this.buildManagerValidationError("Manager key conflict",e.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t,existingName:s,incomingName:n,reason:r})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}throwIfLoginSessionCancelled(t,s){if(t!==this.loginAttempt||this.core!==s)throw new C("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}})}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new qd({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const s=this.cacheManager.loadSessionList().map(bt),n=this.buildConversationListPatch(this.conversationListSnapshot,s,t);(n.reset||0!==n.upserted.length||0!==n.removed.length||n.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=s,this.eventHub.dispatch(ct.CONVERSATION_LIST_UPDATE,{version:this.conversationListVersion,items:s,reason:e,patch:n}))}buildConversationListPatch(e,t,s){const n=new Map(e.map(e=>[this.buildConversationListKey(e),e])),r=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=/* @__PURE__ */new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=n.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);r.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:s,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,s)=>e===t.marks[s])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}async triggerConfiguredSyncDataAfterLogin(e,t){const s=[];this.config.enableSyncData.includes("contact")&&(a.warn("Triggering automatic contact sync after login",{userId:e}),s.push(this.runPostLoginTask(t,"contact",async()=>{await this.triggerContactSync()}))),this.config.enableSyncData.includes("group")&&(a.warn("Triggering automatic group sync after login",{userId:e}),s.push(this.runPostLoginTask(t,"group",async()=>{await this.triggerGroupSync()}))),await Promise.all(s)}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new Rl(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const t=this.managerRegistry.get("contactManager");if(!t?.createSyncController)throw new M("ContactManager is required for contact sync",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"contactManager",message:"ContactManager must be registered for enableSyncData: ['contact']",rule:"required"}]}});return this.contactSyncController=t.createSyncController({getContextState:()=>{const e=this.requireCacheManager();return{cacheMeta:e.loadContactCacheMeta(),versionState:e.loadContactVersionState(),cachedSnapshot:e.loadContactSnapshot("cache")}},queryMetadata:async e=>await Pl(this.getRestContext(),e,this.platformAdapter?.request),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),buildRosterRequest:({version:e})=>this.buildContactRosterRequest(e),applySyncResult:e=>{const t=this.requireCacheManager().applyContactSync(e);return this.refreshConversationDisplayFromUserInfos(t.snapshot.items.map(e=>({userId:e.userId})),"profile"),t},onStart:()=>{this.emitSyncDataStart("contact")},onFinish:e=>{this.emitSyncDataFinished({dataType:"contact",status:e?.error?"failed":"success",error:e?.error?{dataType:"contact",code:e.error.code,stage:e.error.stage,message:e.error.message,retryable:e.error.retryable}:void 0})}}),this.contactSyncController}ensureGroupSyncController(){if(this.groupSyncController)return this.groupSyncController;const t=this.managerRegistry.get("groupManager");if(!t?.createSyncController)throw new M("GroupManager is required for group sync",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"groupManager",message:"GroupManager must be registered for enableSyncData: ['group']",rule:"required"}]}});return this.groupSyncController=t.createSyncController({getRestContext:()=>this.getRestContext(),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),getCacheManager:()=>this.requireCacheManager(),applyRuntimeSnapshot:e=>{const t=this.managerRegistry.get("groupManager");t?.applyJoinedGroupSnapshot?.(e),this.refreshConversationDisplayFromJoinedGroups(e.items,"profile")},getRuntimeSnapshot:()=>{const e=this.managerRegistry.get("groupManager");return e?.getJoinedGroupSnapshotForSync?.()??null},onStart:()=>{this.emitSyncDataStart("group")},onFinish:e=>{this.emitSyncDataFinished({dataType:"group",status:e.status,error:e.error})}}),this.groupSyncController}emitSyncDataStart(e){this.eventHub.dispatch(ct.SYNC_DATA_START,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(ct.SYNC_DATA_FINISHED,e)}requireCacheManager(){if(!this.cacheManager)throw new M("cacheManager is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw a.warn("Derived contact sync websocket is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new L("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw a.warn("Derived contact sync websocket is unavailable for fixed service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new L("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await iu(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=[ou(e.restBaseUrl)],this.contactSyncDnsResolved=!0}catch(t){throw a.warn("Automatic contact sync REST endpoint DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new L("Contact sync websocket dns resolve failed",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:t instanceof Error?t.message:String(t)}})}return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new M("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const s=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(s))throw new M("sync websocket URL must use ws or wss protocol");const n=s.indexOf("#"),r=n>=0?s.slice(n):"",i=n>=0?s.slice(0,n):s,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,l=a.indexOf("/",d),u=l<0||"/"===a.slice(l)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${u}?${h.join("&")}${r}`}shuffleContactSyncUrls(e){const t=[...e];for(let s=t.length-1;s>0;s-=1){const e=Math.floor(Math.random()*(s+1)),n=t[s],r=t[e];n&&r&&(t[s]=r,t[e]=n)}return t}buildContactRosterRequest(e){const t=this.getRestContext(),{orgName:s,appName:n}=P(t.appKey);return{type:_t.REQUEST,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:s,app:n,username:t.userId,version:e,cursor:0}}detachSessionListSyncController(){const e=this.syncConversationListConfigController;return this.syncConversationListConfigController=null,e?.cancelForTeardown()??null}resetCore(){const e=this.detachSessionListSyncController();try{return this.cancelPostLoginTasks(),this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core?(this.core.destroy(),this.clearCoreSessionState(),this.resetManagerSessionRuntimes(),e):e}catch(t){throw this.clearCoreSessionState(),this.updateState(Be.DISCONNECTED),e?.(),t}}clearCoreSessionState(){this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new M("appKey is unavailable before DNSConfig resolution",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new M("appKey is unavailable for the current session",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){for(const t of this.managerRegistry.values())try{t.resetSessionRuntime?.()}catch(e){a.warn("Manager session runtime reset failed",{manager:this.getManagerNameFromInstance(t),error:e instanceof Error?e.message:"unknown"})}this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null}notifyManagersSessionReady(e,t){const s={generation:++this.managerSessionGeneration,userId:e,clientResource:t};this.activeManagerSessionContext=s,this.managerSessionEndingPromise=null;for(const n of this.managerRegistry.values())this.notifyManagerSessionReady(n)}notifyManagerSessionReady(e){const t=this.activeManagerSessionContext;if(t&&e.onSessionReady)try{e.onSessionReady(t)}catch(s){a.warn("Manager session ready hook failed",{manager:this.getManagerNameFromInstance(e),error:s instanceof Error?s.message:"unknown"})}}notifyManagersSessionEnding(e){const t=this.activeManagerSessionContext;if(!t)return Promise.resolve();if(this.managerSessionEndingPromise)return this.managerSessionEndingPromise;const s={...t,reason:e},n=Array.from(this.managerRegistry.values(),e=>{if(!e.onSessionEnding)return Promise.resolve();try{return Promise.resolve(e.onSessionEnding(s)).catch(t=>{a.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"})})}catch(t){return a.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"}),Promise.resolve()}}),r=Promise.all(n).then(()=>{});let i=null;const o=new Promise(t=>{i=setTimeout(()=>{a.warn("Manager session ending hooks timed out",{timeoutMs:De,reason:e}),t()},De)});return this.managerSessionEndingPromise=Promise.race([r,o]).then(()=>{null!==i&&clearTimeout(i),this.activeManagerSessionContext?.generation===t.generation&&(this.activeManagerSessionContext=null)}),this.managerSessionEndingPromise}isTerminalManagerSessionDisconnect(t){return t.reason===Ve.TOKEN_EXPIRED||[e.AUTH_TOKEN_EXPIRED,e.AUTH_BIND_ANOTHER_DEVICE,e.AUTH_LOGIN_TOO_MANY_DEVICES,e.USER_LOGIN_ANOTHER_DEVICE,e.USER_REMOVED,e.USER_KICKED_BY_CHANGE_PASSWORD,e.USER_KICKED_BY_OTHER_DEVICE].includes(t.errorCode??-1)}startTerminalSessionCleanup(e){if(this.terminalSessionCleanupTask)return;a.warn("Terminal session cleanup started",{errorCode:e.errorCode,errorMessage:e.errorMessage,reason:e.reason});const t=this.finishTerminalSessionCleanup().catch(e=>{a.error("Terminal session cleanup failed",e instanceof Error?e:new Error(String(e)))}).finally(()=>{this.terminalSessionCleanupTask===t&&(this.terminalSessionCleanupTask=null)});this.terminalSessionCleanupTask=t}async waitForTerminalSessionCleanup(){await(this.terminalSessionCleanupTask??Promise.resolve())}async finishTerminalSessionCleanup(){this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("terminal-disconnect");try{try{await(this.cacheManager?.flushPending())}catch(e){a.warn("Cache flush on terminal disconnect failed",{error:e instanceof Error?e.message:String(e)})}if(this.logReportEnabled)try{await Me()}catch(e){a.warn("Report logs on terminal disconnect failed",e)}}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),this.logReportEnabled=!1,Ee("disabled"),Re(),Ae()}finally{e?.()}}a.warn("Terminal session cleanup finished")}static isSameConfig(e,s){return e.appKey===s.appKey&&(e.appId===s.appId&&(!!t.isSameStringArray(e.enableSyncData,s.enableSyncData)&&(e.useCustomAttachmentUpload===s.useCustomAttachmentUpload&&(e.enableMd5Check===s.enableMd5Check&&(!!t.isSameServiceConfig(e.serviceConfig,s.serviceConfig)&&(e.useFixedDeviceId===s.useFixedDeviceId&&(e.deviceId===s.deviceId&&(e.useReplacedMessageContents===s.useReplacedMessageContents&&(e.customDeviceName===s.customDeviceName&&(e.customOSPlatform===s.customOSPlatform&&(e.platformAdapterOptions?.prefer===s.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===s.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.transportAdapter===s.platformAdapterOptions?.transportAdapter&&(e.platformAdapterOptions?.overrides===s.platformAdapterOptions?.overrides&&(e.uiKitVersion===s.uiKitVersion&&(e.cacheEncryptionMode===s.cacheEncryptionMode&&(e.enableUserInfoSync===s.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===s.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===s.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===s.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===s.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===s.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===s.profileSync.groupNamecardMaxConcurrency))))))))))))))))))))}static normalizeServiceConfig(e){const s=e?.serverUrls;return{mode:s?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??Ql,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:s?{restApiUrl:s.restApiUrl,wsUrl:s.wsUrl?t.normalizeFixedWebSocketUrl(s.wsUrl):void 0}:void 0}}static normalizeFixedWebSocketUrl(e){const t=e.search(/[?#]/),s=-1===t?e:e.slice(0,t),n=-1===t?"":e.slice(t),r=s.indexOf("://")+3,i=s.indexOf("/",r);if(-1===i)return`${s}/websocket${n}`;const o=s.slice(i);return/^\/+$/u.test(o)?`${s.slice(0,i)}/websocket${n}`:e}static normalizeSyncDataTypes(e){const t=[];for(const s of e)t.includes(s)||t.push(s);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}static isSameServiceConfig(e,s){if(e.mode!==s.mode)return!1;if(e.dnsConfigUrls.length!==s.dnsConfigUrls.length)return!1;for(let t=0;t<e.dnsConfigUrls.length;t+=1)if(e.dnsConfigUrls[t]!==s.dnsConfigUrls[t])return!1;return t.isSameServerUrls(e.serverUrls,s.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl)}};Cu.instance=null;let Su=Cu;function Eu(e){Pe(e)}function bu(e){ke(e)}export{D as AuthenticationError,Vo as CONVERSATION_MARK,qd as CacheManager,Su as ChatClient,et as ChatManager,Ot as ChatRoom,kt as ChatRoomManager,Ut as ChatThread,Lt as ChatThreadManager,C as ConnectionError,Dt as ContactManager,ft as Group,gt as GroupManager,ts as ImageType,ut as LogEventName,T as MessageReceiveError,b as MessageSendError,U as NetworkError,Pt as PresenceManager,ht as PushEventName,xt as PushManager,s as RUNTIME_PLATFORMS,xe as RestBusinessError,oe as RestTransportError,L as SDKError,J as StorageError,ss as StreamMessageStatus,k as UploadError,Ft as UserInfoManager,M as ValidationError,zi as createPlatformAdapter,Hi as detectRuntimePlatform,Fe as isSDKError,bu as setConsoleLogEnabled,Eu as setLogLevel};
|
|
3
|
+
return new Map;const r=[];for(let a=0;a<n.length;a+=50)r.push(n.slice(a,a+50));const i=/* @__PURE__ */new Map;let o=0;return await Promise.all(Array.from({length:Math.min(3,r.length)},async()=>await(async()=>{for(;o<r.length;){const e=o;o+=1;const t=r[e];if(t)try{const e=await s.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&i.set(t.groupId,t)}catch{}}})())),i},cd=async(e,t)=>{const s=await ad(e,t),n=(e=>{const t=/* @__PURE__ */new Map,s=e.getCacheManager()?.loadSessionList?.()??[];for(const n of s)n.lastMessage&&t.set(id(n.conversationId,n.conversationType),n.lastMessage);return t})(t);return e.map(e=>((e,t,s,n)=>{const r=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),i=((e,t)=>{const s=e.getCacheManager();if(!s)return null;const n=s.getRuntimeUserInfo(t,!1);if(n)return n;const r=s.getUserInfoSummaries([t],!1)[0];return r?{userId:r.userId,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}:null})(t,e.conversationId),o="singleChat"===e.type?((e,t,s)=>{const n=t?.remark?.trim();if(n)return{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl};const r=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return r?{conversationName:r,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}})(e.conversationId,r,i):"groupChat"===e.type?(a=e.conversationId,c=s.get(e.conversationId),c?.name?{conversationName:c.name,conversationAvatar:c.avatarUrl}:{conversationName:a}):(e=>({conversationName:e}))(e.conversationId);var a,c;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:od(e,t,n),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:o.conversationName,conversationAvatar:o.conversationAvatar}})(e,t,s,n))};class dd{constructor(e=`session-list-${St()}`){this.status="idle",this.seenBatchKeys=/* @__PURE__ */new Set,this.itemsByConversation=/* @__PURE__ */new Map,this.batchCount=0,this.requestId=e,this.startedAt=Date.now()}getRequestId(){return this.requestId}getStartedAt(){return this.startedAt}start(){"idle"===this.status&&(this.status="connecting")}markSyncing(){if("completed"===this.status||"failed"===this.status||"cancelled"===this.status)throw new L("Session-list sync session cannot re-enter syncing state after completion",e.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(t){if(t.requestId!==this.requestId)throw new L("Session-list sync requestId mismatch",e.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:t.requestId}});if(this.isTerminal())throw new L("Session-list sync batch received after terminal state",e.CONTACT_SYNC_CURSOR_INVALID,{details:{requestId:t.requestId,status:this.status}});const s=(n=t.requestId,r=t.batchSequence,`${n}:${r}`);var n,r;if(this.seenBatchKeys.has(s))return{accepted:!1,done:t.isLastBatch};this.markSyncing(),this.seenBatchKeys.add(s);for(const e of t.sessions)this.itemsByConversation.set(`${e.conversationType}:${e.conversationId}`,e);return this.batchCount+=1,t.isLastBatch&&(this.status="completed",this.finishedAt=Date.now()),{accepted:!0,done:t.isLastBatch}}fail(){this.status="failed",this.finishedAt=Date.now()}cancel(){this.status="cancelled",this.finishedAt=Date.now()}getItems(){return[...this.itemsByConversation.values()]}getBatchCount(){return this.batchCount}getStatus(){return this.status}buildSnapshot(){return{requestId:this.requestId,status:this.status,pageCount:this.batchCount,startedAt:this.startedAt,finishedAt:this.finishedAt,seenBatchKeys:[...this.seenBatchKeys]}}isTerminal(){return"completed"===this.status||"failed"===this.status||"cancelled"===this.status}}const ld=0,ud=5,hd=10,pd=11,md=1,fd=2,gd=1,yd=2,Id=3,vd=e=>e===md?"groupChat":e===fd?"chatRoom":"singleChat",Cd=()=>pi().lookupType("easemob.pb.MessageBody"),Ed=e=>{const t=e.session_id??"",s=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),n="string"==typeof s?.nickname?s.nickname:void 0,r="string"==typeof s?.remark?s.remark:void 0,i="string"==typeof s?.avatarurl?s.avatarurl:"string"==typeof s?.avatarUrl?s.avatarUrl:void 0;return r?{conversationName:r,conversationAvatar:i}:n?{conversationName:n,conversationAvatar:i}:{conversationName:t,conversationAvatar:i}},Sd=e=>{const t={...e};return delete t.type,t},Ad=(e,t,s)=>{if(!e)return"";const n=`${t}_${s}_`;return e.startsWith(n)?e.slice(n.length):e},Td=(e,t,s)=>{if(!e)return null;const n=mi(s.payload?.from,{name:Ad(e.from?.name,s.org,s.app)}),r=((e,t)=>{if(!e)return{};const s=new He(t.currentUserId,t.useCustomAttachmentUpload),n=Array.isArray(e.contents)?e.contents.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)):[],r=s.decodeMetadata(e,t.conversationType,t.from===t.currentUserId?"SEND":void 0);r.stream&&n.length>=2&&Ht(n,"stream content is not composed into a multi_body message");const i=r.stream?{type:"text",body:{content:r.stream.fullText}}:zt(n,t=>s.decodeContent(t,e.meta)),o={userInfoUpdateTime:Yt(We(e.userInfoUpdateTime)),namecardUpdateTime:Yt(We(e.namecardUpdateTime))};return{...r,...i?"multi_body"===i.type&&Array.isArray(i.body)?{type:i.type,body:i.body.map(e=>({...e}))}:{type:i.type,body:{...i.body}}:{},ext:$e(e.ext),...o}})(s.payload??null,{currentUserId:s.currentUserId,conversationType:s.conversationType,from:n,useCustomAttachmentUpload:s.useCustomAttachmentUpload}),i={userId:n};return"singleChat"===s.conversationType&&n===s.conversationId&&s.singleChatPeerDisplay&&(s.singleChatPeerDisplay.conversationName!==n&&(i.nickname=s.singleChatPeerDisplay.conversationName),s.singleChatPeerDisplay.conversationAvatar&&(i.avatarUrl=s.singleChatPeerDisplay.conversationAvatar)),{...r,msgServerId:e.id??"",...e.id?{sendStatus:"sent"}:{},from:n,to:dc({conversationId:s.conversationId,conversationType:s.conversationType,from:n,to:mi(s.payload?.to,void 0),currentUserId:s.currentUserId}),sender:i,conversationId:s.conversationId,conversationType:s.conversationType,type:r.type??(o=t.type,"text"===o||"image"===o||"file"===o||"voice"===o||"video"===o||"location"===o||"custom"===o||"cmd"===o||"combine"===o?o:"text"),timestamp:e.timestamp??0,..."multi_body"===r.type&&Array.isArray(r.body)?{body:r.body}:{body:r.body??Sd(t)},ext:r.ext??s.ext??{}};var o},bd=e=>{if(!Array.isArray(e))return[];const t=/* @__PURE__ */new Set,s=[],n=e;for(const r of n){const e="string"==typeof r&&r.startsWith("mark_")?r.slice(5):r,n="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(n)||n<0||n>19)continue;const i=n;t.has(i)||(t.add(i),s.push(i))}return s},wd=(e,t,s,n,r)=>e.sessions.map(e=>{const i=(e=>{if(!e||0===e.byteLength)return null;try{return Cd().toObject(Cd().decode(e),{longs:Number,bytes:Uint8Array})}catch{return null}})(e.last_message?.payload),o=e.session_id??"",a=vd(e.session_type),c=(e=>{const t=e.session_id??"",s=vd(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Ed(e)})(e);return{conversationId:o,conversationType:a,unreadCount:e.unread_count??0,lastMessage:Td(e.last_message,{},{payload:i,useCustomAttachmentUpload:r?.useCustomAttachmentUpload,conversationId:o,conversationType:a,currentUserId:t,org:s,app:n,singleChatPeerDisplay:"singleChat"===a?c:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:bd(e.marks),readAt:e.read_receipt,remindType:(d=e.remind_type,d===gd?"ALL":d===yd?"AT":d===Id?"NONE":"DEFAULT"),conversationName:c.conversationName,conversationAvatar:c.conversationAvatar};var d}),Nd={nested:{easemob:{nested:{sessionlist:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},JID:{fields:{app_key:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},client_resource:{type:"string",id:4}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},timestamp:{type:"uint64",id:4},payload:{type:"bytes",id:6}}},SessionItem:{fields:{session_id:{type:"string",id:1},session_type:{type:"int32",id:2},last_message:{type:"Meta",id:3},updated_at:{type:"int64",id:6},pinned_time:{type:"int64",id:7},unread_count:{type:"uint32",id:8},marks:{rule:"repeated",type:"string",id:9},read_receipt:{type:"int64",id:10},remind_type:{type:"int32",id:11},group_name:{type:"string",id:12},group_avatar:{type:"string",id:13},metadata:{type:"string",id:14}}},GetSessionListRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},need_empty_session:{type:"bool",id:7},need_session_mark:{type:"bool",id:8}}},GetSessionListResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},sessions:{rule:"repeated",type:"SessionItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let Md=null,Rd=!1;const _d=()=>Md||(Rd||(Rt.util.Long=Mt,Rt.configure(),Rd=!0),Dt(),Md=Rt.Root.fromJSON(Nd),Ut(Md),Md),Dd=e=>_d().lookupType(e),Od=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if("bigint"==typeof e)return Number(e);if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},Ud=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Od(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Od(t.protocol_version)??Od(t.protocolVersion)??0}},Ld=e=>{if(!e||"object"!=typeof e)return;const t=e;return{appKey:"string"==typeof t.app_key?t.app_key:"string"==typeof t.appKey?t.appKey:void 0,name:"string"==typeof t.name?t.name:void 0,domain:"string"==typeof t.domain?t.domain:void 0,clientResource:"string"==typeof t.client_resource?t.client_resource:"string"==typeof t.clientResource?t.clientResource:void 0}},kd=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Od(t.id)?String(Od(t.id)):void 0,from:Ld(t.from),timestamp:Od(t.timestamp),payload:t.payload instanceof Uint8Array?t.payload:Array.isArray(t.payload)?Uint8Array.from(t.payload.filter(e=>"number"==typeof e)):void 0}};class Pd{constructor(){this.requestType=Dd("easemob.sessionlist.GetSessionListRequest"),this.responseType=Dd("easemob.sessionlist.GetSessionListResponse"),this.errorType=Dd("easemob.sessionlist.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,need_empty_session:e.includeEmpty??!1,need_session_mark:e.includeMark??!0});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const s=this.tryDecodeResponse(e);if(s)return s;const n=this.tryDecodeRequest(e);return n||{type:ld}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=Od(t.type);return s!==hd?null:{type:s,header:Ud(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Od(t.last_sync_time)??0,includeEmpty:!0===t.need_empty_session,includeMark:!0===t.need_session_mark}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),s=Od(t.type);return s!==pd?null:{type:s,header:Ud(t.header),sessions:Array.isArray(t.sessions)?t.sessions.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{session_id:"string"==typeof t.session_id?t.session_id:void 0,session_type:Od(t.session_type),last_message:kd(t.last_message),updated_at:Od(t.updated_at),pinned_time:Od(t.pinned_time),unread_count:Od(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Od(t.read_receipt),remind_type:Od(t.remind_type),group_name:"string"==typeof t.group_name?t.group_name:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:void 0,metadata:"string"==typeof t.metadata?t.metadata:void 0}})(e)):[],isLastBatch:!0===t.is_last_batch,lastSyncFinishedTs:Od(t.last_sync_finished_ts)}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),s=Od(t.type);return s!==ud?null:{type:s,header:Ud(t.header),code:Od(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const xd=async t=>{const s=t.client.getCacheManager(),n=t.client.getRestContext(),r=t.client.getSessionListSyncWsUrls();if(!s||0===r.length)throw new I("session-list sync websocket is unavailable",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[i,o]=n.appKey.split("#");if(!i||!o)throw new R("session-list appKey is invalid",{code:e.VALIDATION_INVALID_FORMAT,details:{appKey:n.appKey}});const a=s.loadSessionListCheckpoint(),d=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:t.session.getRequestId(),resource:n.clientResource,org:i,app:o,username:n.userId,lastSyncTime:(l=a.sessionsLastSyncTs,Math.max(0,l-Y)),params:t.params});var l;const u=new Pd;let h=0,p=a.sessionsLastSyncTs;return await t.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:t.session.getRequestId(),encode:()=>u.encodeRequest(d),decode:e=>{const t=u.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:s=>{if(5===s.type&&"code"in s&&"message"in s)throw 1002===(r=s).code?new O(r.message,{code:e.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:r.code}}):1003===r.code?new L(r.message,e.SERVER_BUSY,{details:{protocol:"session-list",responseCode:r.code}}):1501===r.code||1001===r.code?new R(r.message,{code:e.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:r.code}}):1503===r.code?new L(r.message,e.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:r.code}}):(r.code,new L(r.message,e.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:r.code}}));var r;if(11!==s.type)throw new L("session-list response type is invalid",e.MESSAGE_DECODE_FAILED,{details:{responseType:s.type}});const a=s,d=a.header?.requestId;if(d&&d!==t.session.getRequestId())return;h+=1,c.debug("Decoded session-list sync raw response",{requestId:t.session.getRequestId(),batchSequence:h,response:a});const l=wd(a,n.userId,i,o,t.client.getMessageCreationOptions?.()),u=t.session.pushBatch({requestId:t.session.getRequestId(),batchSequence:h,sessions:l,isLastBatch:!0===a.isLastBatch,lastSyncFinishedTs:a.lastSyncFinishedTs});if("number"==typeof a.lastSyncFinishedTs&&(p=a.lastSyncFinishedTs),!u.done)return;return{done:!0,result:{items:t.session.getItems(),lastSyncFinishedTs:p}}}})},Fd=()=>Date.now(),Bd={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},qd=(e,t)=>({status:e,determinedAt:Fd(),reason:t}),Kd=t=>t instanceof L&&(t.code===e.SERVER_BUSY||1103===t.code),Gd=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Kd(e)});class Vd{constructor(e){this.running=null,this.currentSession=null,this.activeFinish=null,this.cancelled=!1,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}cancel(){this.cancelForTeardown()?.()}cancelForTeardown(){this.cancelled=!0,this.currentSession?.cancel();const t=this.activeFinish;return this.activeFinish=null,t?()=>{t({dataType:"conversation",status:"failed",error:{dataType:"conversation",code:e.SESSION_LIST_CANCELLED,stage:"cancelled",message:"session-list sync cancelled",retryable:!1}})}:null}refresh(e){return this.cancelled?Promise.resolve([]):(this.running||(this.currentSession=new dd,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running)}async runRefresh(t,s){const n=this.client.getCacheManager();if(!n)return[];let r=!1;const i=e=>{r||(r=!0,this.client.emitSyncDataFinished(e))};this.activeFinish=i;try{this.client.emitSyncDataStart("conversation");const e=await this.tryDirectFallback(n);if(this.cancelled)return[];if(e)return this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"success"}),e;const r=n.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let a=0;const c=await async function(e,t,s={}){const n={...sd,...s};let r;for(let o=1;o<=n.maxAttempts;o++)try{return await e()}catch(i){if(r=i,!t(i))throw i;if(o>=n.maxAttempts)throw i;const e=nd(o,n);await rd(e)}throw r}(async()=>{if(this.cancelled)throw new L("session-list sync controller is cancelled");a+=1;const e=1===a?t:this.createRetrySession();e.start();try{return await xd({client:this.client,session:e,params:s})}catch(n){throw this.cancelled||e.fail(),n}},e=>!this.cancelled&&Kd(e),Bd);if(this.cancelled)return[];const d={result:c,syncStartedAt:t.getStartedAt()},l=d.result.items;this.capabilityState={status:"available",determinedAt:Fd()};const u={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Fd()};try{if(await n.commitSessionListSync({items:l,mode:r,checkpoint:u,syncStartedAt:d.syncStartedAt}),this.cancelled)return[]}catch(o){if(this.cancelled)return[];t.fail();const e=new J("Session-list final persistence failed",{details:{cause:o instanceof Error?o.message:String(o)}});return this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"failed",error:Gd(e)}),n.loadSessionList()}const h=n.loadSessionList();return n.updateConversationsFromServer(h.map(ss),{syncStartedAt:d.syncStartedAt}),await n.flushPending(),this.cancelled?[]:(this.client.emitConversationListUpdate("conversation","full"===r),i({dataType:"conversation",status:"success"}),h)}catch(o){if(this.cancelled)return[];const s=o instanceof L?o:new L(o instanceof Error?o.message:String(o));t.fail();const r=(t=>t.code===e.OPERATION_UNSUPPORTED||t.code===e.AUTH_UNAUTHORIZED?{capabilityState:qd("unsupported",t.message),shouldUseFallback:!0}:t.code===e.AUTH_TOKEN_EXPIRED||t.code===e.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:t.code===e.SERVER_BUSY||1103===t.code?{shouldUseFallback:!0,shouldRetry:!0}:t.code===e.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(s);r.capabilityState&&(this.capabilityState=r.capabilityState),r.shouldResetCheckpoint&&n.resetSessionListCheckpoint();const a=await this.buildFallbackSessionList(n);return this.cancelled?[]:(r.shouldUseFallback&&n.replaceSessionList(a),this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"failed",error:Gd(s)}),a)}finally{this.activeFinish===i&&(this.activeFinish=null)}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}var t;const s=this.client.hasSessionListSyncWsUrl(),n=this.client.isSessionListDnsProbeAvailable();if(!s&&!n){this.capabilityState=qd("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}return null}createRetrySession(){return new dd}async buildFallbackSessionList(e){return await(async(e,t)=>await cd(e,t))(e.loadConversationSummaries(),this.client)}}const Hd=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),zd=async t=>{if("string"==typeof t||Hd(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Hd(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength))(t);if((e=>"undefined"!=typeof Blob&&e instanceof Blob&&"function"==typeof e.arrayBuffer||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(t))return new Uint8Array(await t.arrayBuffer());throw new L("sync websocket frame payload type is invalid",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof t}})},jd=e=>{const t=Math.max(e-1,0),s=ne*Math.pow(re,t);return Math.min(s,se)},Wd=async e=>{await new Promise(t=>{setTimeout(t,e)})},Qd=e=>e instanceof Error?e:new Error(String(e));class $d{constructor(e){this.pending=/* @__PURE__ */new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(t){if(this.cancelled)throw new L("sync websocket session is cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:t.requestId}});if(this.pending.has(t.requestId))throw new L("sync websocket requestId is duplicated",e.VALIDATION_INVALID_FORMAT,{details:{stage:"request_send",requestId:t.requestId}});this.clearCompleteCloseTimer();const s=new Promise((e,s)=>{this.pending.set(t.requestId,{...t,resolve:e,reject:s})});s.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(t.requestId))}catch(n){this.rejectPending(t.requestId,Qd(n))}return await s}cancel(t="sync-websocket-cancelled"){this.cancelled=!0;const s=new L("sync websocket cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",reason:t}});this.rejectAll(s),this.closeSocket(4001,t),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle",this.attempt=0}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==o.OPEN){if(this.connectPromise)return await this.connectPromise;this.attempt=0,this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let t=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&c.warn("sync websocket retry started",this.buildLogContext({reason:t?.message}));try{return void(await this.openSocket())}catch(s){if(t=Qd(s),this.cancelled||0===this.pending.size)throw t;if(this.attempt>=3)throw c.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),t;const e=jd(this.attempt);c.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:e,reason:t.message})),await Wd(e)}}throw new I("sync websocket retry exhausted",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:t?.message??"unknown"}})}async openSocket(){const t=await this.getUrls();if(0===t.length)throw new I("sync websocket urls are unavailable",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const s=t[this.urlIndex%t.length];if(this.urlIndex+=1,!s)throw new I("sync websocket url is invalid",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=s,this.state="connecting",c.warn("sync websocket connect started",this.buildLogContext());const n=oi(this.socketAdapter);let r=null;try{const e=await Promise.race([n.connect({url:s}),new Promise((e,t)=>{r=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},X)})]);r&&clearTimeout(r),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),c.warn("sync websocket connected",this.buildLogContext())}catch(i){if(r&&clearTimeout(r),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),i instanceof I)throw i;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:i instanceof Error?i.message:String(i)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await zd(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Qd(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(t){const s=[];let n=null;for(const e of this.pending.values())try{const s=e.decode(t);if(s.requestId&&s.requestId===e.requestId){try{const t=await e.onFrame(s.frame,this.socket);t?.done&&(this.pending.delete(e.requestId),e.resolve(t.result),this.closeIfComplete())}catch(r){this.pending.delete(e.requestId),e.reject(Qd(r)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||n||(n={pending:e,frame:s.frame})}catch(r){s.push(Qd(r))}if(n)return await n.pending.onFrame(n.frame,this.socket),!0;if(this.pending.size>0&&s.length===this.pending.size)throw new L("sync websocket frame decode failed",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:s[0]?.message}});return c.warn("sync websocket frame ignored",this.buildLogContext({reason:s[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(c.warn("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(Qd(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===o.OPEN)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),c.warn("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const s=this.pending.get(e);s&&(this.pending.delete(e),s.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(c.warn("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},Z))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},ee))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const s=this.socket;this.socket=null,!s||s.readyState>=o.CLOSING||(this.state="closing",s.close(e,t))}buildConnectionError(t,s,n={}){return new I(t,{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:s,url:this.activeUrl,...n}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:te(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const Yd=async(t,s,n)=>{const{orgName:r,appName:i}=x(t.appKey),o=`/${r}/${i}/user/${encodeURIComponent(t.userId)}/roster/metadata/version`,a=new ie(t.restBaseUrl,{requestAdapter:n,includeRequestId:!0});a.setAuthToken(t.token);try{return((t,s)=>{const n=Date.now(),r=e=>{const t="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:t,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??t!==s,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:n}};if(os(t))return os(t.data)?r(t.data):r(t);throw new R("Invalid contact metadata response",{code:e.VALIDATION_INVALID_FORMAT,details:{payload:t}})})(await a.get(o),s)}catch(c){if(c instanceof R)throw c;const t=c instanceof L&&c.details?c.details:{};throw new oe("Contact metadata request failed",{code:e.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:c instanceof Error?c.message:String(c),httpStatus:"number"==typeof t.httpStatus?t.httpStatus:void 0,sourceCode:c instanceof L?c.code:void 0}})}},Jd=e=>as.string().regex(/^https?:\/\/\S+$/i,e),Xd=as.object({appKey:as.string().min(1,"appKey is required").optional(),appId:as.string().min(1,"appId is required").optional(),enableUserInfoSync:as.boolean().optional(),enableSyncData:as.array(as.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:as.boolean().optional(),deleteConversationOnGroupDestroyed:as.boolean().optional(),syncConversationListConfig:as.object({includeEmpty:as.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:as.boolean().optional(),useFixedDeviceId:as.boolean().optional(),deviceId:as.string().min(1,"deviceId is required").optional(),serviceConfig:as.object({dnsConfigUrls:as.array(Jd("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:as.object({restApiUrl:Jd("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(Zd="serviceConfig.serverUrls.wsUrl must be a valid URL",as.string().regex(/^wss?:\/\/\S+$/i,Zd)).optional()}).optional()}).optional(),useReplacedMessageContents:as.boolean().optional(),customDeviceName:as.string().min(1,"customDeviceName is required").optional(),customOSPlatform:as.number().int("customOSPlatform must be an integer").min(1,"customOSPlatform must be between 1 and 100").max(100,"customOSPlatform must be between 1 and 100").optional(),uiKitVersion:as.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:as.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:as.array(as.unknown()).optional(),platformAdapterOptions:as.object({prefer:as.enum(["web","wechat-miniapp","qq-miniapp","toutiao-miniapp","baidu-miniapp","alipay-miniapp","dingtalk-miniapp","lark-miniapp","kuaishou-miniapp","jd-miniapp","360-miniapp","harmony-miniapp","quickapp","uniapp","react-native","electron-renderer","electron-main","unknown"]).optional(),runtimeInput:as.custom(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:as.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:as.custom(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const s=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===s?t.addIssue({code:as.ZodIssueCode.custom,path:["appKey"],message:"appKey or appId is required"}):s>1&&t.addIssue({code:as.ZodIssueCode.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:as.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:as.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:as.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:as.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:as.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:as.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:as.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const n=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,r=n?.serverUrls&&"object"==typeof n.serverUrls?n.serverUrls:void 0;n?.dnsConfigUrls&&r&&t.addIssue({code:as.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),r&&(void 0!==e.appId&&t.addIssue({code:as.ZodIssueCode.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),r?.restApiUrl||t.addIssue({code:as.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),r?.wsUrl||t.addIssue({code:as.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var Zd;const el=as.object({userId:as.string().min(1,"userId is required"),token:as.string().min(1,"token is required")}),tl=as.object({timeoutMs:as.number().int("timeoutMs must be an integer").min(ae,`timeoutMs must be at least ${ae}`).max(ce,`timeoutMs must be at most ${ce}`).optional()}).strict(),sl=as.string().trim().min(1,"token is required"),nl=as.object({channelName:as.string().trim().min(1,"channelName is required").optional()}).optional(),rl=as.array(as.number({invalid_type_error:"rtcUid must be a number"}).int("rtcUid must be an integer").min(0,"rtcUid must be greater than or equal to 0").max(Number.MAX_SAFE_INTEGER,"rtcUid must be a safe integer")).nonempty("rtcUids is required").transform(e=>Array.from(new Set(e))),il=as.object({protocol:as.string(),domain:as.string().optional(),ip:as.string().optional(),port:as.union([as.string(),as.number()]).optional()}).passthrough(),ol=as.object({app_key:as.string().optional(),rest:as.object({hosts:as.array(il).nonempty()}),"msync-wx":as.object({hosts:as.array(il).nonempty()}),"sync-ws":as.object({hosts:as.array(il).nonempty()}).optional(),enableReportLogs:as.enum(["true","false"]).optional(),reportInterval:as.number().positive().finite().optional(),enableDataReport:as.enum(["true","false"]).optional(),enableMd5Check:as.enum(["true","false"]).optional(),uploadinparts_enable:as.enum(["true","false"]).optional()}).passthrough(),al="5.2.0",cl=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],dl=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function ll(e){return"object"==typeof e&&null!==e}function ul(e){return Array.isArray(e)?{hosts:e}:function(e){return ll(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function hl(e){if(!ll(e))return At.validateOrThrow(ol,e);const t=ul(e.rest),s=function(e,t,s){for(const n of t){const t=ul(e[n]);if(t)return{key:n,section:t}}for(const[n,r]of Object.entries(e)){if(!s(n))continue;const e=ul(r);if(e)return{key:n,section:e}}}(e,dl,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),n={...e,rest:t??e.rest,"msync-wx":s?.section},r="true"===(i=e.enableReportLogs)||!0===i?"true":"false"===i||!1===i?"false":void 0;var i;r&&(n.enableReportLogs=r);const o=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==o?n.reportInterval=o:delete n.reportInterval;const a=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);a?n.enableDataReport=a:delete n.enableDataReport;const d=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);d?n.enableMd5Check=d:delete n.enableMd5Check;const l=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return l?n.uploadinparts_enable=l:delete n.uploadinparts_enable,s&&"msync-wx"!==s.key&&c.warn("DNS config websocket section normalized",{sourceKey:s.key}),At.validateOrThrow(ol,n)}function pl(t,s){const n=t.domain||t.ip;if(!n)throw new R("DNS host missing domain/ip",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const r=void 0!==t.port?String(t.port):"";return`${"https"===s?"wss":"ws"}://${r&&"80"!==r&&"443"!==r?`${n}:${r}`:n}/websocket`}function ml(e,t){return"https"===e?"https":"http"===e?"http":t}function fl(t,s){const n=t.domain||t.ip;if(!n)throw new R("DNS rest host missing domain/ip",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const r=void 0!==t.port?String(t.port):"";return`${s}://${r&&"80"!==r&&"443"!==r?`${n}:${r}`:n}`}function gl(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function yl(e){const t=function(e){return e.filter(e=>Boolean(e.domain))}(e);return t.length>0?t:e.filter(e=>Boolean(e.domain||e.ip))}async function Il(e,t,s,n){const r=new ie(e,{requestAdapter:s,includeRequestId:!0});let i="/easemob/server.json",o=!0;try{const t=new URL(e),s=""!==t.pathname&&"/"!==t.pathname,n=""!==t.search;(s||n)&&(i="",o=!1)}catch{i="/easemob/server.json",o=!0}if(o){i=`${i}?${(void 0!==t.appId?cs({app_id:t.appId,sdk_version:al,file_version:"1"}):cs({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return hl(await r.get(i,{timeout:n}))}async function vl(t){const s=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:cl;if(0===s.length)throw new R("DNS_CONFIG list is empty",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const n=t.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let r;for(const a of s){const s=t.loginDeadline,i=s?.remainingMs();if(s&&void 0!==i&&i<=0)throw s.createTimeoutError();try{const s=void 0!==t.appId?{appId:t.appId}:{appKey:t.appKey},r=void 0===i?void 0:Math.min(de,i),o=await Il(a,s,t.requestAdapter,r),c=void 0!==t.appId?o.app_key:t.appKey;if("string"!=typeof c||0===c.length)throw new R("DNS app_key is required for appId initialization",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const d=yl(gl(o["msync-wx"].hosts,n));if(0===d.length)throw new R("DNS msync-wx hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const l=d[0];if(!l)throw new R("DNS msync-wx hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const u=gl(o.rest.hosts,n);if(0===u.length)throw new R("DNS rest hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const h=u[0];if(!h)throw new R("DNS rest hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const p=d.map(e=>pl(e,ml(e.protocol,n))),m=pl(l,ml(l.protocol,n));return{appKey:c,websocketUrl:m,websocketUrls:p,baseUrl:a,restBaseUrl:fl(h,ml(h.protocol,n)),dnsConfig:o}}catch(o){if(s&&s.remainingMs()<=0)throw s.createTimeoutError();c.warn("DNS config candidate failed",{baseUrl:a,reason:o instanceof Error?o.message:String(o),error:o instanceof Error&&"function"==typeof o.toJSON?o.toJSON():o}),r=o}}const i={stage:"dns"};throw r&&(i.reason=r.message,"code"in r&&"number"==typeof r.code&&(i.causeCode=r.code)),new I("DNS_CONFIG exhausted",{code:e.CONNECTION_DNSLIST_FAILED,details:i})}const Cl=e=>{const t=(e=>{const t=e.trim(),s=/^(https?):\/\//i.exec(t);if(!s?.[1])throw new R("REST API URL must use http or https protocol");const n=s[1].toLowerCase(),r=t.slice(s[0].length),i=r.search(/[/?#]/),o=i>=0?r.slice(0,i):r,a=o.lastIndexOf("@"),c=a>=0?o.slice(a+1):o;if(!c)throw new R("REST API URL host is required");let d,l;if(c.startsWith("[")){const e=c.indexOf("]");if(e<=1)throw new R("REST API URL IPv6 host is invalid");d=c.slice(0,e+1);const t=c.slice(e+1);if(t){if(!t.startsWith(":"))throw new R("REST API URL authority is invalid");l=t.slice(1)}}else{const e=c.lastIndexOf(":");if(e>=0){if(c.indexOf(":")!==e)throw new R("REST API URL IPv6 host must use brackets");d=c.slice(0,e),l=c.slice(e+1)}else d=c}if(!d)throw new R("REST API URL host is required");if(void 0!==l){const e=Number(l);if(!/^\d+$/.test(l)||e<1||e>65535)throw new R("REST API URL port is invalid")}return{protocol:n,host:d,port:l}})(e),s="http"===t.protocol&&"80"===t.port||"https"===t.protocol&&"443"===t.port,n="https"===t.protocol?"wss":"ws",r=t.port&&!s?`:${t.port}`:"";return`${n}://${t.host}${r}/ws`},El=t=>new R(t,{code:e.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),Sl=e=>{if(!os(e))throw El("Invalid REST response");return os(e.data)?e.data:e},Al=(e,t)=>{for(const s of t){const t=e[s];if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&t.trim().length>0){const e=Number(t);if(Number.isFinite(e))return e}}},Tl=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},bl=e=>{const{orgName:t,appName:s}=x(e.appKey);return`/${t}/${s}`},wl=async(e,t)=>{const s=await e.get((e=>`${bl(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Sl(e),s=Al(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw El("Invalid token expires response");return s})(s)},Nl=async(e,t,s)=>{const n=await e.get(((e,t)=>{const s=cs({channelName:t?.channelName??"*"});return`${bl(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${s.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=Sl(e);return{appId:Tl(t,["app_id","appId"])??"",rtcToken:Tl(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Tl(t,["channel_name","channelName"])??"",rtcUid:Al(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:Al(t,["expires_in","expire","expireAt"])??0}})(n)},Ml=async(e,t,s)=>{const n=await e.post((e=>`${bl(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Sl(e),s={};for(const[n,r]of Object.entries(t)){const e=Number(n);!Number.isSafeInteger(e)||e<0||"string"!=typeof r||(s[e]=r)}return s})(n)},Rl=async(e,t)=>{const s=await e.get((e=>`${bl(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=os(e)&&Array.isArray(e.data)?e.data:[],n=[];for(const r of s){if(!os(r))continue;const e=Tl(r,["res","resource","clientResource"]);e&&e!==t.clientResource&&n.push(`${t.userId}/${e}`)}return n})(s,t)};class _l{constructor(e){this.options=e,this.pendingGroups=/* @__PURE__ */new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=/* @__PURE__ */new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,s){if(!e||!t)return;const n=this.pendingGroups.get(e)??/* @__PURE__ */new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,n),this.pendingOrder.push(e));const r=n.get(t);n.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(r?.namecardUpdateTime,s)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const s=Array.from(t.values()),n=Math.max(1,this.options.maxBatchSize);for(let r=0;r<s.length;r+=n)this.readyGroups.push({groupId:e,targets:s.slice(r,r+n)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{c.warn("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),s=t-e;return s<=0?t:e+Math.floor(Math.random()*(s+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Dl{constructor(e){this.options=e,this.pendingTargets=/* @__PURE__ */new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let s=0;s<e.length;s+=t)this.readyBatches.push(e.slice(s,s+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const s=this.generation;this.activeCount+=1;const n=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let r;try{r=Promise.resolve(this.options.onFlush(n))}catch(t){r=Promise.reject(t instanceof Error?t:new Error(String(t)))}r.catch(t=>{const n=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(c.warn("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:n.length>0,error:t instanceof Error?t.message:String(t)}),s===this.generation&&0!==n.length){for(const e of n)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const s of this.readyBatches){const t=s.findIndex(t=>t.userId===e.userId);if(t>=0){const n=s[t];return void(n&&(s[t]=this.mergeTarget(n,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Ol{constructor(e,t,s=Date.now){this.attemptId=e,this.timeoutMs=t,this.now=s,this.timeoutId=null,this.status="active",this.expiresAt=this.now()+t,this.timeoutPromise=new Promise((e,s)=>{this.timeoutId=setTimeout(()=>{"active"===this.status&&(this.status="expired",this.timeoutId=null,s(this.createTimeoutError()))},t)}),this.timeoutPromise.catch(()=>{})}getStatus(){return this.status}remainingMs(){return"expired"===this.status?0:Math.max(0,this.expiresAt-this.now())}clamp(e){return Math.max(0,Math.min(e,this.remainingMs()))}race(e){return"expired"===this.status||0===this.remainingMs()?(e.catch(()=>{}),this.expire(),Promise.reject(this.createTimeoutError())):"active"!==this.status?e:Promise.race([e,this.timeoutPromise])}markProvisionReceived(){return"active"===this.status&&(this.status="provision-received",this.clearTimer(),!0)}expire(){"active"===this.status&&(this.status="expired",this.clearTimer())}dispose(){"active"===this.status&&(this.status="disposed"),this.clearTimer()}createTimeoutError(){return new I("Login timeout",{code:e.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",timeoutMs:this.timeoutMs,attemptId:this.attemptId,retryable:!0}})}clearTimer(){null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const Ul=_e(De,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Ll=class t{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=dt.DISCONNECTED,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=/* @__PURE__ */new Set,this.managerSessionGeneration=0,this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null,this.postLoginTaskContext=null,this.terminalSessionCleanupTask=null,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=ii(this.config.platformAdapterOptions)),this.managerRegistry=/* @__PURE__ */new Map,this.managerCapabilities=/* @__PURE__ */new Map,this.eventHub=new td,Le(e=>{this.eventHub.dispatch(Ft.LOG,e)}),this.managerEventContext={addEventHandler:(e,t)=>{this.eventHub.addEventHandler(e,t)},removeEventHandler:e=>{this.eventHub.removeEventHandler(e)},dispatch:(e,t)=>{this.eventHub.dispatch(e,t)}},this.userInfoHydrationQueue=new Dl({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:ue,maxRetries:le,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new _l({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:pe,maxBatchSize:he,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[lt.CONNECTING]:e=>{this.updateState(e.state)},[lt.CONNECTED]:e=>{this.updateState(e.state)},[lt.DISCONNECTED]:e=>{this.updateState(e.state),this.isTerminalManagerSessionDisconnect(e)&&this.startTerminalSessionCleanup(e)},[lt.RECONNECT_FAILED]:e=>{this.updateState(e.state)},[kt.MESSAGE]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[kt.MESSAGE_UPDATED]:e=>{this.patchConversationLastMessage(e,{...e.message,body:{...e.message.body}})},[kt.MESSAGE_READ_RECEIPTS]:e=>{const t=e.flatMap(e=>"singleChat"===e.conversationType?e.messageIds.map(t=>({conversationId:e.conversationId,conversationType:e.conversationType,messageId:t,patch:{isPeerRead:!0}})):e.receiptDetails.map(t=>({conversationId:e.conversationId,conversationType:e.conversationType,messageId:t.messageId,patch:{groupReadCount:t.count}})));this.cacheManager?.patchConversationLastMessages(t)&&this.emitConversationListUpdate("message")},[kt.REACTION_CHANGED]:e=>{this.patchConversationLastMessage(e,{reactions:[...e.reactions]})},[kt.STREAM_MESSAGE]:e=>{this.handleIncomingConversationStreamMessage(e)},[ht.MESSAGE_SENT]:e=>{this.handleOutgoingConversationMessage(e)},[kt.MULTI_DEVICE_CONTACT]:e=>{this.handleMultiDeviceContactEvent(e)},[kt.MULTI_DEVICE_CONVERSATION]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[Pt.ADDED]:e=>this.handleIncomingContactRosterEvent("add",e),[Pt.AGREED]:e=>this.handleIncomingContactRosterEvent("add",e),[Pt.INVITED]:e=>this.handleIncomingContactRosterEvent("none",e),[Pt.REFUSE]:e=>this.handleIncomingContactRosterEvent("none",e),[Pt.DELETED]:e=>this.handleIncomingContactRosterEvent("remove",e),[ht.GROUP_NOTIFY]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===Lt.GROUP_DESTROYED&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[ht.CHATROOM_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[ht.CHAT_THREAD_NOTIFY]:e=>{const t=((e,t,s,n=!1)=>{const r=t.find(t=>"groupChat"===t.conversationType&&t.conversationId===e.muc_parent_id&&t.lastMessage&&(e.msg_parent_id?t.lastMessage.msgServerId===e.msg_parent_id:t.lastMessage.chatThreadOverview?.chatThreadId===e.id)),i=r?.lastMessage;if(!r||!i||!e.id)return null;const o={conversationId:r.conversationId,conversationType:"groupChat",messageId:i.msgServerId};if("delete"===e.operation)return i.chatThreadOverview?.chatThreadId===e.id?{...o,patch:{chatThreadOverview:void 0}}:null;if(!["create","update","update_msg"].includes(e.operation))return null;const a=new He(s,n).resolveChatThreadOverview({thread_overview:{id:e.id,muc_parent_id:e.muc_parent_id,name:e.name,message_count:e.message_count,update_timestamp:e.timestamp,last_message:e.last_message}});return a?(Object.prototype.hasOwnProperty.call(e,"last_message")||Reflect.deleteProperty(a,"lastMessage"),{...o,patch:{chatThreadOverview:{...i.chatThreadOverview?.chatThreadId===e.id?i.chatThreadOverview:{},...a}}}):null})(e.payload,this.cacheManager?.loadSessionList()??[],this.getCurrentUserId()??"",this.config.useCustomAttachmentUpload);return t&&this.patchConversationLastMessage(t,t.patch),this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e})},[ht.USER_INFO_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(s){const n=At.validateOrThrow(Xd,s),r=n.customOSPlatform,i=t.normalizeServiceConfig(n.serviceConfig),o={appKey:n.appKey,appId:n.appId,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:t.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==r?n.customDeviceName:void 0,customOSPlatform:r,uiKitVersion:n.uiKitVersion,loginExtensionInfo:n.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:ye,userInfoBatchSize:ge,groupNamecardWindowMs:fe,groupNamecardMaxConcurrency:me},platformAdapterOptions:n.platformAdapterOptions},a=s.managers??[];if(t.instance){if(!t.isSameConfig(t.instance.config,o))throw new R("ChatClient already initialized with different config",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:t.instance.config,next:o}});return a.length>0&&t.instance.registerManagers(a),t.instance.validateOptionalCapabilityDependencies(),t.instance}return t.instance=new t(o),a.length>0&&t.instance.registerManagers(a),t.instance.validateOptionalCapabilityDependencies(),t.instance}async login(s,n){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const r=At.validateOrThrow(el,s),i=At.validateOrThrow(tl,n??{});if(await this.waitForTerminalSessionCleanup(),this.state===dt.CONNECTING||this.state===dt.CONNECTED){const t=this.currentUserId&&this.currentUserId!==r.userId;throw new I(t?"Another user is already logged in":"ChatClient is already connecting or connected",{code:t?e.USER_ALREADY_LOGIN_ANOTHER:e.AUTH_ALREADY_LOGIN,details:{stage:"auth",...t?{currentUserId:this.currentUserId,nextUserId:r.userId}:{}}})}const o=++this.loginAttempt,a=new Ol(o,i.timeoutMs??Ie);try{let t=this.config.appKey??null;this.activeAppKey=t,c.warn("Login started",{userId:r.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const s=this.platformAdapter??ii(this.config.platformAdapterOptions);this.platformAdapter=s,ve({requestAdapter:s.request,onDiagnostic:(e,t)=>{c.warn(e,t)}});const n=Ce({appKey:t??"default#appkey",uid:r.userId,sdkVersion:al,platform:s.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),i=s.runtime.getNetworkType?.();i&&i.then(e=>{Ee(e)}).catch(()=>{Ee("unknown")});const l=C({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:r.userId});let u,h,p;this.updateState(dt.CONNECTING),this.logReportEnabled=!1,Se("unknown");let m,f=!1,g=!1,y=!0;if("dns"===this.config.serviceConfig.mode){const e=l?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const n=await a.race(vl(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:a}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:a}));t=n.appKey,this.activeAppKey=t,Ae({appKey:t}),c.warn("DNS resolved for login",{baseUrl:n.baseUrl,websocketUrl:n.websocketUrl,restBaseUrl:n.restBaseUrl,syncWebSocketSource:"rest"}),u=n.websocketUrl,h=n.websocketUrls;const r=Cl(n.restBaseUrl);this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!0,p=n.restBaseUrl,f="true"===n.dnsConfig.enableReportLogs,m=n.dnsConfig.reportInterval,g="true"===n.dnsConfig.enableMd5Check,y="false"!==n.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),Te(n.dnsConfig.enableDataReport),c.debug("DNS report switch resolved",{enabled:f})}catch(d){const t=d instanceof L?d.code:-1,s=d instanceof Error?d.message:String(d);throw e?.finish({code:t,success:!1,description:s}),l?.finish({code:t,success:!1,description:s}),Te(void 0),Se("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(dt.DISCONNECTED),a.dispose(),d}}else{const t=this.config.serviceConfig.serverUrls;if(!t?.wsUrl||!t.restApiUrl){const t=new R("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw l?.finish({code:t.code,success:!1,description:t.message}),Te(void 0),this.updateState(dt.DISCONNECTED),a.dispose(),t}u=t.wsUrl,p=t.restApiUrl;const s=Cl(p);g=this.config.enableMd5Check,this.contactSyncWsUrls=[s],this.syncConversationListConfigWsUrls=[s],this.contactSyncDnsResolved=!1,Te(void 0)}if(!t){const t=new R("appKey is unavailable after service discovery",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(dt.DISCONNECTED),be(),a.dispose(),t}we({restBaseUrl:p,appKey:t,userId:r.userId,token:r.token,requestAdapter:s.request}),Ne(m),this.logReportEnabled=f,Se(f?"enabled":"disabled");const v=this.resetCore();if(v?.(),o!==this.loginAttempt){const t=new I("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}});throw l?.finish({code:e.CONNECTION_CANCELLED,success:!1,description:t.message}),this.updateState(dt.DISCONNECTED),this.activeAppKey=this.config.appKey??null,be(),a.dispose(),t}const E=new cc({serverUrl:u,serverUrls:h,userId:r.userId,token:r.token,appKey:t,restBaseUrl:p,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:g,enableMultipartUpload:y,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:n,platformAdapter:s,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub);this.core=E,we({resource:E.getClientResource()});const S=l?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:u});try{c.warn("Connecting core websocket",{serverUrl:u,restBaseUrl:p,userId:r.userId});try{await a.race(E.connect(a))}finally{a.dispose()}this.throwIfLoginSessionCancelled(o,E),S?.finish({code:200,success:!0}),l?.finish({code:0,success:!0}),c.warn("Core websocket connected",{userId:r.userId,resource:E.getClientResource()}),this.currentUserId=r.userId,Ae({uid:r.userId}),this.restBaseUrl=p??null,this.authToken=r.token,this.clientResource=E.getClientResource(),await this.initCacheManager(r.userId),this.throwIfLoginSessionCancelled(o,E),c.warn("Cache initialized after login",{userId:r.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),this.notifyManagersSessionReady(r.userId,this.clientResource),this.startPostLoginTasks(r.userId,o)}catch(d){const e=d instanceof L?d.code:-1,t=d instanceof Error?d.message:String(d);if(S?.finish({code:e,success:!1,description:t}),l?.finish({code:e,success:!1,description:t}),this.core===E){const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(dt.DISCONNECTED),be()}finally{e?.()}}throw d}}finally{a.dispose()}}startPostLoginTasks(e,t){this.cancelPostLoginTasks();const s={attemptId:t,userId:e,cancelled:!1};this.postLoginTaskContext=s,this.runPostLoginTasks(s).catch(e=>{this.isPostLoginTaskActive(s)&&c.warn("Unexpected post-login task failure",{userId:s.userId,reason:e instanceof Error?e.message:String(e)})}).finally(()=>{this.postLoginTaskContext===s&&(this.postLoginTaskContext=null)})}cancelPostLoginTasks(){this.postLoginTaskContext&&(this.postLoginTaskContext.cancelled=!0,this.postLoginTaskContext=null)}isPostLoginTaskActive(e){return!e.cancelled&&this.postLoginTaskContext===e&&e.attemptId===this.loginAttempt&&this.currentUserId===e.userId}async runPostLoginTasks(e){if(!this.isPostLoginTaskActive(e))return;if(await this.runPostLoginTask(e,"self-user-info",async()=>{await this.syncSelfUserInfoAfterLogin()}),!this.isPostLoginTaskActive(e))return;if(this.config.enableSyncData.includes("conversation")&&await this.runPostLoginTask(e,"conversation",async()=>{await this.refreshSessionList(this.config.syncConversationListConfig)}),!this.isPostLoginTaskActive(e))return;const t=this.triggerConfiguredSyncDataAfterLogin(e.userId,e),s=this.logReportEnabled?this.runPostLoginTask(e,"log-report",async()=>{await Me()}):Promise.resolve();await Promise.all([t,s])}async runPostLoginTask(e,t,s){if(this.isPostLoginTaskActive(e))try{await s()}catch(n){if(!this.isPostLoginTaskActive(e))return;c.warn("Post-login synchronization step failed",{userId:e.userId,task:t,reason:n instanceof Error?n.message:String(n)})}}async logout(){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});for(this.loginAttempt+=1,this.cancelPostLoginTasks();this.terminalSessionCleanupTask;)await this.terminalSessionCleanupTask;if(this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("logout"),!this.core){const e=this.detachSessionListSyncController();try{this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.resetManagerSessionRuntimes(),Se("disabled"),Re(),be()}finally{this.contactSyncController=null,this.groupSyncController=null,this.syncWebSocketSession=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.activeAppKey=this.config.appKey??null,this.updateState(dt.DISCONNECTED),this.logReportEnabled=!1,e?.()}return}try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await Me()}catch(s){c.warn("Report logs on logout failed",s)}await this.core.disconnect()}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(dt.DISCONNECTED),this.logReportEnabled=!1,Se("disabled"),Re(),be()}finally{e?.()}}}getConnectionState(){return this.state}getVersion(){return al}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new R("restBaseUrl is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new R("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new R("userId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const t=this.clientResource??this.core?.getClientResource();if(!t)throw new R("clientResource is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(t){const s=At.validateOrThrow(sl,t);if(!this.core||!this.currentUserId||this.state!==dt.CONNECTED)throw new I("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const n=this.getRestContext(),r={...n},i=new ie(r.restBaseUrl,{errorMap:Ul,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(s),c.warn("Renew token started",{userId:n.userId});const o=await wl(i,r);if(o<=Date.now())throw new I("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const a=this.core.renewToken(s,o);return this.authToken=s,we({token:s}),c.warn("Renew token succeeded",{userId:n.userId,expireAt:o}),a}async getRTCTokenInfo(e){const t=At.validateOrThrow(nl,e),s=this.getRestContext(),n=new ie(s.restBaseUrl,{errorMap:Ul,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return n.setAuthToken(s.token),c.warn("Get RTC token info started",{userId:s.userId,hasChannelName:Boolean(t?.channelName)}),Nl(n,s,t)}async getUserIdsWithRTCUids(e){const t=At.validateOrThrow(rl,e),s=this.getRestContext(),n=new ie(s.restBaseUrl,{errorMap:Ul,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return n.setAuthToken(s.token),c.warn("Get userIds with RTC UIDs started",{userId:s.userId,count:t.length}),Ml(n,s,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new ie(e.restBaseUrl,{errorMap:Ul,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),c.warn("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),Rl(t,e)}getCacheManager(){return this.cacheManager}getManagerByCapability(e){return this.managerCapabilities.get(e)}getUploadAdapter(){return this.platformAdapter?.upload??null}getRequestAdapter(){return this.platformAdapter?.request}addInternalEvent(e,t){this.eventHub.dispatch(e,t)}refreshSessionList(e){return this.cacheManager&&this.currentUserId?this.ensureSessionListSyncController().refresh({includeEmpty:e?.includeEmpty??this.config.syncConversationListConfig.includeEmpty,includeMark:!0}).then(e=>(this.enqueueMissingGroupSessionSenderUserInfos(e),e.map(e=>({...e})))):Promise.resolve([])}getServerUrlsConfig(){return this.config.serviceConfig.serverUrls}getSessionListSyncWsUrls(){return this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}hasSessionListSyncWsUrl(){return this.syncConversationListConfigWsUrls.length>0}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new $d({socketAdapter:this.platformAdapter?.socket,getUrls:async()=>{const e=this.getSessionListSyncWsUrls();return e.length>0?e:await this.resolveContactSyncUrls()}})),this.syncWebSocketSession}isSessionListDnsProbeAvailable(){return"dns"===this.config.serviceConfig.mode}getSessionListSyncCapabilityState(){return this.syncConversationListConfigController?.getCapabilityState()??null}markConversationAccess(e){this.cacheManager?.markConversationAccess(e)}patchConversationLastMessage(e,t){const s=this.cacheManager?.patchConversationLastMessages([{...e,patch:t}]);s&&this.emitConversationListUpdate("message")}handleIncomingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleIncomingConversationStreamMessage(e){if(!this.cacheManager)return;const t=e.msgServerId||e.msgLocalId,s=e.stream.status===it.START_COMPLETED||e.stream.status===it.FULL||e.stream.status===it.COMPLETED||e.stream.status===it.ERROR;if(!this.activeIncomingStreamMessageIds.has(t))return this.applyIncomingConversationMessagePatch(e),void(s||this.activeIncomingStreamMessageIds.add(t));if(!s)return;this.activeIncomingStreamMessageIds.delete(t);this.cacheManager.loadSessionList().some(e=>e.lastMessage?.msgServerId===t)&&this.applyIncomingConversationMessagePatch(e)}applyIncomingConversationMessagePatch(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleOutgoingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}async handleMultiDeviceConversationEvent(e){if("CONVERSATION_DELETED"!==e.operation||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e.conversationId,type:e.conversationType??"singleChat",deletedAt:e.timestamp??Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}async handleGroupDestroyedConversation(e){if(!this.config.deleteConversationOnGroupDestroyed||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e,type:"groupChat",deletedAt:Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}handleMultiDeviceContactEvent(e){if("CONTACT_REMOVE"!==e.operation||!this.cacheManager)return;this.cacheManager.applyContactRosterNotice({action:"remove",userId:e.targetUserId,rosterVersion:e.rosterVersion}).changed&&this.cacheManager.flushPending()}getContactSnapshot(){return this.cacheManager?this.cacheManager.loadContactSnapshot("cache"):null}handleIncomingContactRosterEvent(e,t){const s=this.resolveContactRosterTargetUserId(t);if(s)return this.cacheManager&&this.currentUserId&&"none"!==e&&this.cacheManager.applyContactRosterNotice({action:e,userId:s,rosterVersion:Ki(t)}),this.hydrateContactRosterPayload(t,s,"remove"!==e)}resolveContactRosterTargetUserId(e){const t=this.currentUserId;return t?e.from===t&&e.to!==t?e.to:e.to===t&&e.from!==t||e.from&&e.from!==t?e.from:e.to&&e.to!==t?e.to:null:null}async hydrateContactRosterPayload(e,t,s){const n=await ds(t,{cacheManager:this.cacheManager,fetchUserInfos:s?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=n}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(s){return c.warn("Contact roster event user info fetch failed",{userIds:e,error:s}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&c.warn("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){c.warn("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=Fi(e),s=e.sender.userId;if(!s||!this.cacheManager)return;const n=this.cacheManager.getUserInfoSummaries([s],!1)[0];if(n&&(e.sender={userId:s,nickname:n.nickname??e.sender.nickname,avatarUrl:n.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(n?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(s,t.userInfoUpdateTime):n||this.userInfoHydrationQueue.enqueue(s),"groupChat"!==e.conversationType)return;const r=this.cacheManager.getGroupNamecard(e.conversationId,s,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(r?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,s,t.namecardUpdateTime):r||this.groupNamecardHydrationQueue.enqueue(e.conversationId,s)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{Pi.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};xi(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const s=e.map(e=>e.userId);let n;try{n=await t.getUserInfoByUserId({userIds:s})}catch(l){throw c.warn("User info hydration failed",{userIds:s,error:l}),l}const r=this.currentUserId,i=r?n.find(e=>e.userId===r):void 0,o=n.filter(e=>e.userId!==r);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),n.length>0&&this.refreshConversationDisplayFromUserInfos(n.map(e=>({userId:e.userId})),"profile");const a=new Set(n.map(e=>e.userId)),d=s.filter(e=>!a.has(e));d.length>0&&c.warn("User info hydration returned partial result",{requestedUserIds:s,missingUserIds:d})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(s){c.warn("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:s})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(s){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(s),this}async sendMessage(s,n){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!s?.sender?.userId)throw new R("sender.userId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&s.sender.userId!==this.currentUserId)throw new R("sender.userId does not match current user",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(rt(s))throw new E("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:s.msgLocalId,retryable:!1}});if(this.core&&this.state!==dt.CONNECTED&&await this.waitForSendConnectionRecovery(this.core),!this.core||this.state!==dt.CONNECTED)throw new E("ChatClient is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:s.msgLocalId,state:this.state,retryable:!0}});return"text"===s.type&&"targetLanguages"in s.body?this.sendTranslatedMessage(this.core,s,n):(this.attachOutgoingMessageProfileVersions(s),this.core.sendMessage(s,n))}async sendTranslatedMessage(t,s,n){const r=this.loginAttempt;let i;try{if(i=await Tt(s,async e=>{const t=this.getRestContext(),s=new ie(t.restBaseUrl,{errorMap:_e(De,bt),requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(t.token),wt(s,t,e)}),this.core!==t||this.loginAttempt!==r||this.state!==dt.CONNECTED)throw new E("Connection changed before message send",{code:e.MESSAGE_NOT_CONNECTED})}catch(o){const t=o instanceof oe?new U(o.message,{code:o.code,details:o.details}):o instanceof Error?o:new L(String(o),e.UNKNOWN);throw n?.onFailed?.({...s,sendStatus:"failed"},t),t}return this.attachOutgoingMessageProfileVersions(i),t.sendMessage(i,n)}async waitForSendConnectionRecovery(e){let t=null;const s=e.recoverConnectionForSend().then(()=>!0).catch(e=>(c.warn("Send connection recovery failed",{error:e instanceof Error?e.message:String(e)}),!1)),n=new Promise(e=>{t=setTimeout(()=>{e(!1)},Oe)}),r=await Promise.race([s,n]);t&&clearTimeout(t),r||c.warn("Send connection recovery wait timed out",{timeoutMs:Oe,state:this.state})}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",s){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),s).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=/* @__PURE__ */new Set;for(const r of e){const e="groupChat"===r.conversationType?r.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const s=this.cacheManager.getUserInfoSummaries([...t],!1),n=new Set(s.map(e=>e.userId));for(const r of t)n.has(r)||this.userInfoHydrationQueue.enqueue(r)}dispatchUserGroupNamecardUpdated(e,t,s){e&&t&&this.eventHub.dispatch(Lt.USER_GROUP_NAMECARD_UPDATED,{groupId:e,userId:t,namecard:s})}async downloadAndParseCombinePayload(s){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new R("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(s)}async sendMessageAction(s,n){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new R("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendMessageAction(s,n)}async sendChatRoomOperation(s,n){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new R("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(s,n)}async downloadAttachment(s){if(t.instance!==this)throw new R("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new R("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.downloadAttachment(s)}decodeServerMessageMeta(t){if(!this.core)throw new R("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.decodeServerMessageMeta(t)}registerManagers(t){if(0===t.length)return;const s=/* @__PURE__ */new Set;for(const n of t){const t=this.resolveManagerKey(n);if(s.has(t))throw this.buildManagerValidationError(`Manager key duplicated: ${t}`,e.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t});s.add(t)}for(const e of t)this.registerManagerInput(e)}registerManagerInput(e){return t.isManagerConstructor(e)?this.registerManagerConstructor(e):this.registerManagerInstance(e)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),s=this.managerRegistry.get(t);if(s){if(s.constructor===e)return s;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const n=new e;return n.bind(this,this.managerEventContext),this.managerRegistry.set(t,n),this.registerManagerCapabilities(n),this.attachManager(t,n),this.notifyManagerSessionReady(n),n}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),s=this.managerRegistry.get(t);if(s){if(s===e)return e;if(s.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),this.notifyManagerSessionReady(e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const s=this.getManagerByCapability(e);return s?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(t,s,n){return new R(`${t} requires explicit manager capability: ${s}`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} requires explicit manager capability: ${s}`,rule:"dependency"}],capability:s,requiredManagers:n}})}resolveManagerKey(s){if(t.isManagerConstructor(s))return this.getManagerKeyFromConstructor(s);if("object"!=typeof s||null===s)throw this.buildManagerValidationError("Manager must be constructor or instance",e.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof s});return this.getManagerKeyFromInstance(s)}getManagerKeyFromConstructor(t){const s=t.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.VALIDATION_REQUIRED,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(t)});return s}getManagerKeyFromInstance(t){const s=t.constructor.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.VALIDATION_REQUIRED,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(t)});return s}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,s,n,r){return new R(e,{code:t,details:{fields:[{path:s,message:e,rule:n}],...r}})}buildManagerConflictError(t,s,n,r){return this.buildManagerValidationError("Manager key conflict",e.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t,existingName:s,incomingName:n,reason:r})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}throwIfLoginSessionCancelled(t,s){if(t!==this.loginAttempt||this.core!==s)throw new I("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}})}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new ed({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const s=this.cacheManager.loadSessionList().map(ns),n=this.buildConversationListPatch(this.conversationListSnapshot,s,t);(n.reset||0!==n.upserted.length||0!==n.removed.length||n.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=s,this.eventHub.dispatch(kt.CONVERSATION_LIST_UPDATE,{version:this.conversationListVersion,items:s,reason:e,patch:n}))}buildConversationListPatch(e,t,s){const n=new Map(e.map(e=>[this.buildConversationListKey(e),e])),r=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=/* @__PURE__ */new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=n.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);r.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:s,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,s)=>e===t.marks[s])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}async triggerConfiguredSyncDataAfterLogin(e,t){const s=[];this.config.enableSyncData.includes("contact")&&(c.warn("Triggering automatic contact sync after login",{userId:e}),s.push(this.runPostLoginTask(t,"contact",async()=>{await this.triggerContactSync()}))),this.config.enableSyncData.includes("group")&&(c.warn("Triggering automatic group sync after login",{userId:e}),s.push(this.runPostLoginTask(t,"group",async()=>{await this.triggerGroupSync()}))),await Promise.all(s)}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new Vd(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const t=this.managerRegistry.get("contactManager");if(!t?.createSyncController)throw new R("ContactManager is required for contact sync",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"contactManager",message:"ContactManager must be registered for enableSyncData: ['contact']",rule:"required"}]}});return this.contactSyncController=t.createSyncController({getContextState:()=>{const e=this.requireCacheManager();return{cacheMeta:e.loadContactCacheMeta(),versionState:e.loadContactVersionState(),cachedSnapshot:e.loadContactSnapshot("cache")}},queryMetadata:async e=>await Yd(this.getRestContext(),e,this.platformAdapter?.request),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),buildRosterRequest:({version:e})=>this.buildContactRosterRequest(e),applySyncResult:e=>{const t=this.requireCacheManager().applyContactSync(e);return this.refreshConversationDisplayFromUserInfos(t.snapshot.items.map(e=>({userId:e.userId})),"profile"),t},onStart:()=>{this.emitSyncDataStart("contact")},onFinish:e=>{this.emitSyncDataFinished({dataType:"contact",status:e?.error?"failed":"success",error:e?.error?{dataType:"contact",code:e.error.code,stage:e.error.stage,message:e.error.message,retryable:e.error.retryable}:void 0})}}),this.contactSyncController}ensureGroupSyncController(){if(this.groupSyncController)return this.groupSyncController;const t=this.managerRegistry.get("groupManager");if(!t?.createSyncController)throw new R("GroupManager is required for group sync",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"groupManager",message:"GroupManager must be registered for enableSyncData: ['group']",rule:"required"}]}});return this.groupSyncController=t.createSyncController({getRestContext:()=>this.getRestContext(),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),getCacheManager:()=>this.requireCacheManager(),applyRuntimeSnapshot:e=>{const t=this.managerRegistry.get("groupManager");t?.applyJoinedGroupSnapshot?.(e),this.refreshConversationDisplayFromJoinedGroups(e.items,"profile")},getRuntimeSnapshot:()=>{const e=this.managerRegistry.get("groupManager");return e?.getJoinedGroupSnapshotForSync?.()??null},onStart:()=>{this.emitSyncDataStart("group")},onFinish:e=>{this.emitSyncDataFinished({dataType:"group",status:e.status,error:e.error})}}),this.groupSyncController}emitSyncDataStart(e){this.eventHub.dispatch(kt.SYNC_DATA_START,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(kt.SYNC_DATA_FINISHED,e)}requireCacheManager(){if(!this.cacheManager)throw new R("cacheManager is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw c.warn("Derived contact sync websocket is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new L("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw c.warn("Derived contact sync websocket is unavailable for fixed service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new L("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await vl(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=[Cl(e.restBaseUrl)],this.contactSyncDnsResolved=!0}catch(t){throw c.warn("Automatic contact sync REST endpoint DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new L("Contact sync websocket dns resolve failed",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:t instanceof Error?t.message:String(t)}})}return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new R("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const s=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(s))throw new R("sync websocket URL must use ws or wss protocol");const n=s.indexOf("#"),r=n>=0?s.slice(n):"",i=n>=0?s.slice(0,n):s,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,l=a.indexOf("/",d),u=l<0||"/"===a.slice(l)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${u}?${h.join("&")}${r}`}shuffleContactSyncUrls(e){const t=[...e];for(let s=t.length-1;s>0;s-=1){const e=Math.floor(Math.random()*(s+1)),n=t[s],r=t[e];n&&r&&(t[s]=r,t[e]=n)}return t}buildContactRosterRequest(e){const t=this.getRestContext(),{orgName:s,appName:n}=x(t.appKey);return{type:ls.REQUEST,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:s,app:n,username:t.userId,version:e,cursor:0}}detachSessionListSyncController(){const e=this.syncConversationListConfigController;return this.syncConversationListConfigController=null,e?.cancelForTeardown()??null}resetCore(){const e=this.detachSessionListSyncController();try{return this.cancelPostLoginTasks(),this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core?(this.core.destroy(),this.clearCoreSessionState(),this.resetManagerSessionRuntimes(),e):e}catch(t){throw this.clearCoreSessionState(),this.updateState(dt.DISCONNECTED),e?.(),t}}clearCoreSessionState(){this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new R("appKey is unavailable before DNSConfig resolution",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new R("appKey is unavailable for the current session",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){for(const t of this.managerRegistry.values())try{t.resetSessionRuntime?.()}catch(e){c.warn("Manager session runtime reset failed",{manager:this.getManagerNameFromInstance(t),error:e instanceof Error?e.message:"unknown"})}this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null}notifyManagersSessionReady(e,t){const s={generation:++this.managerSessionGeneration,userId:e,clientResource:t};this.activeManagerSessionContext=s,this.managerSessionEndingPromise=null;for(const n of this.managerRegistry.values())this.notifyManagerSessionReady(n)}notifyManagerSessionReady(e){const t=this.activeManagerSessionContext;if(t&&e.onSessionReady)try{e.onSessionReady(t)}catch(s){c.warn("Manager session ready hook failed",{manager:this.getManagerNameFromInstance(e),error:s instanceof Error?s.message:"unknown"})}}notifyManagersSessionEnding(e){const t=this.activeManagerSessionContext;if(!t)return Promise.resolve();if(this.managerSessionEndingPromise)return this.managerSessionEndingPromise;const s={...t,reason:e},n=Array.from(this.managerRegistry.values(),e=>{if(!e.onSessionEnding)return Promise.resolve();try{return Promise.resolve(e.onSessionEnding(s)).catch(t=>{c.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"})})}catch(t){return c.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"}),Promise.resolve()}}),r=Promise.all(n).then(()=>{});let i=null;const o=new Promise(t=>{i=setTimeout(()=>{c.warn("Manager session ending hooks timed out",{timeoutMs:Ue,reason:e}),t()},Ue)});return this.managerSessionEndingPromise=Promise.race([r,o]).then(()=>{null!==i&&clearTimeout(i),this.activeManagerSessionContext?.generation===t.generation&&(this.activeManagerSessionContext=null)}),this.managerSessionEndingPromise}isTerminalManagerSessionDisconnect(t){return t.reason===pt.TOKEN_EXPIRED||[e.AUTH_TOKEN_EXPIRED,e.AUTH_BIND_ANOTHER_DEVICE,e.AUTH_LOGIN_TOO_MANY_DEVICES,e.USER_LOGIN_ANOTHER_DEVICE,e.USER_REMOVED,e.USER_KICKED_BY_CHANGE_PASSWORD,e.USER_KICKED_BY_OTHER_DEVICE].includes(t.errorCode??-1)}startTerminalSessionCleanup(e){if(this.terminalSessionCleanupTask)return;c.warn("Terminal session cleanup started",{errorCode:e.errorCode,errorMessage:e.errorMessage,reason:e.reason});const t=this.finishTerminalSessionCleanup().catch(e=>{c.error("Terminal session cleanup failed",e instanceof Error?e:new Error(String(e)))}).finally(()=>{this.terminalSessionCleanupTask===t&&(this.terminalSessionCleanupTask=null)});this.terminalSessionCleanupTask=t}async waitForTerminalSessionCleanup(){await(this.terminalSessionCleanupTask??Promise.resolve())}async finishTerminalSessionCleanup(){this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("terminal-disconnect");try{try{await(this.cacheManager?.flushPending())}catch(e){c.warn("Cache flush on terminal disconnect failed",{error:e instanceof Error?e.message:String(e)})}if(this.logReportEnabled)try{await Me()}catch(e){c.warn("Report logs on terminal disconnect failed",e)}}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(dt.DISCONNECTED),this.logReportEnabled=!1,Se("disabled"),Re(),be()}finally{e?.()}}c.warn("Terminal session cleanup finished")}static isSameConfig(e,s){return e.appKey===s.appKey&&(e.appId===s.appId&&(!!t.isSameStringArray(e.enableSyncData,s.enableSyncData)&&(e.useCustomAttachmentUpload===s.useCustomAttachmentUpload&&(e.enableMd5Check===s.enableMd5Check&&(!!t.isSameServiceConfig(e.serviceConfig,s.serviceConfig)&&(e.useFixedDeviceId===s.useFixedDeviceId&&(e.deviceId===s.deviceId&&(e.useReplacedMessageContents===s.useReplacedMessageContents&&(e.customDeviceName===s.customDeviceName&&(e.customOSPlatform===s.customOSPlatform&&(e.platformAdapterOptions?.prefer===s.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===s.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.transportAdapter===s.platformAdapterOptions?.transportAdapter&&(e.platformAdapterOptions?.overrides===s.platformAdapterOptions?.overrides&&(e.uiKitVersion===s.uiKitVersion&&(e.cacheEncryptionMode===s.cacheEncryptionMode&&(e.enableUserInfoSync===s.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===s.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===s.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===s.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===s.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===s.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===s.profileSync.groupNamecardMaxConcurrency))))))))))))))))))))}static normalizeServiceConfig(e){const s=e?.serverUrls;return{mode:s?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??cl,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:s?{restApiUrl:s.restApiUrl,wsUrl:s.wsUrl?t.normalizeFixedWebSocketUrl(s.wsUrl):void 0}:void 0}}static normalizeFixedWebSocketUrl(e){const t=e.search(/[?#]/),s=-1===t?e:e.slice(0,t),n=-1===t?"":e.slice(t),r=s.indexOf("://")+3,i=s.indexOf("/",r);if(-1===i)return`${s}/websocket${n}`;const o=s.slice(i);return/^\/+$/u.test(o)?`${s.slice(0,i)}/websocket${n}`:e}static normalizeSyncDataTypes(e){const t=[];for(const s of e)t.includes(s)||t.push(s);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}static isSameServiceConfig(e,s){if(e.mode!==s.mode)return!1;if(e.dnsConfigUrls.length!==s.dnsConfigUrls.length)return!1;for(let t=0;t<e.dnsConfigUrls.length;t+=1)if(e.dnsConfigUrls[t]!==s.dnsConfigUrls[t])return!1;return t.isSameServerUrls(e.serverUrls,s.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl)}};Ll.instance=null;let kl=Ll;function Pl(e){Pe(e)}function xl(e){ke(e)}export{O as AuthenticationError,Hi as CONVERSATION_MARK,ed as CacheManager,kl as ChatClient,Nt as ChatManager,hs as ChatRoom,ps as ChatRoomManager,ot as ChatThread,at as ChatThreadManager,I as ConnectionError,us as ContactManager,Gt as Group,Vt as GroupManager,ct as ImageType,Ft as LogEventName,S as MessageReceiveError,E as MessageSendError,U as NetworkError,ms as PresenceManager,Bt as PushEventName,fs as PushManager,s as RUNTIME_PLATFORMS,xe as RestBusinessError,oe as RestTransportError,L as SDKError,J as StorageError,it as StreamMessageStatus,P as UploadError,gs as UserInfoManager,R as ValidationError,ii as createPlatformAdapter,ri as detectRuntimePlatform,Fe as isSDKError,xl as setConsoleLogEnabled,Pl as setLogLevel};
|