easemob-websdk 5.0.0 → 5.0.1

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.
Files changed (53) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-manager.d.ts +3 -0
  3. package/cache/cache-store.d.ts +6 -4
  4. package/cache/cache-utils.d.ts +1 -1
  5. package/chunks/cache-utils-B99glc0H.js +1 -0
  6. package/chunks/cache-utils-gowrxNr8.cjs +1 -0
  7. package/chunks/chat-manager-5wHx7UeW.cjs +1 -0
  8. package/chunks/chat-manager-DdAnJpcH.js +2 -0
  9. package/chunks/common-BIpcR2uQ.cjs +1 -0
  10. package/chunks/common-BW2KLpvb.js +1 -0
  11. package/chunks/{group-user-info-resolver-FNRqDg18.js → group-user-info-resolver-Diqjmjyj.js} +1 -1
  12. package/chunks/{group-user-info-resolver-C5pdiqox.cjs → group-user-info-resolver-Ds35Z1Uf.cjs} +1 -1
  13. package/chunks/index-BItCF8E7.cjs +1 -0
  14. package/chunks/{index-uKWbjx-u.js → index-DKksD5YM.js} +1 -1
  15. package/chunks/{index-BKg4EGcI.cjs → index-DKmdsV1-.cjs} +1 -1
  16. package/chunks/index-VEUtqiDw.js +1 -0
  17. package/chunks/query-params-BHyPuD2k.cjs +1 -0
  18. package/chunks/query-params-Bu3Xq4b6.js +1 -0
  19. package/chunks/{session-list-query-B6dh-b4Y.cjs → session-list-query-C4OQMvPf.cjs} +1 -1
  20. package/chunks/{session-list-query-Dnp2HbpW.js → session-list-query-DtoToipt.js} +1 -1
  21. package/chunks/{user-info-BfRwS4ZA.js → user-info-22jZtcSi.js} +1 -1
  22. package/chunks/{user-info-icpL0Eaw.cjs → user-info-DsDDTJrw.cjs} +1 -1
  23. package/index.cjs +1 -1
  24. package/index.js +2 -2
  25. package/managers/chat/index.cjs +1 -1
  26. package/managers/chat/index.js +1 -1
  27. package/managers/chat-thread/index.cjs +1 -1
  28. package/managers/chat-thread/index.js +1 -1
  29. package/managers/chatroom/index.cjs +1 -1
  30. package/managers/chatroom/index.js +1 -1
  31. package/managers/contact/index.cjs +1 -1
  32. package/managers/contact/index.js +1 -1
  33. package/managers/group/index.cjs +1 -1
  34. package/managers/group/index.js +1 -1
  35. package/managers/presence/index.cjs +1 -1
  36. package/managers/presence/index.js +1 -1
  37. package/managers/push/index.cjs +1 -1
  38. package/managers/push/index.js +1 -1
  39. package/managers/user-info/index.cjs +1 -1
  40. package/managers/user-info/index.js +1 -1
  41. package/package.json +1 -1
  42. package/platform/env.d.ts +1 -0
  43. package/utils/query-params.d.ts +16 -0
  44. package/utils/runtime-global.d.ts +13 -0
  45. package/utils/storage-error.d.ts +8 -0
  46. package/chunks/cache-utils-BwRPIZ7n.js +0 -1
  47. package/chunks/cache-utils-CKbcYPlM.cjs +0 -1
  48. package/chunks/chat-manager-ChdK26ck.cjs +0 -1
  49. package/chunks/chat-manager-DH8a6Qj9.js +0 -2
  50. package/chunks/common-CfAlncj9.cjs +0 -1
  51. package/chunks/common-DN_g4O3n.js +0 -1
  52. package/chunks/index-CK3GHdGU.cjs +0 -1
  53. package/chunks/index-CjofwvEQ.js +0 -1
package/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import{E as e,l as t,e as s,t as n,i as r,I as i,d as o,j as a,H as c,k as d,o as l,q as u,r as h,C as p,P as m,u as f,M as g,v as y,w as I,D as v,V as C,a as S,b as E,A as b,N as A,S as T,x as w,U as N,p as M,y as R,z as _,B as U,F as D,G as L,J as O,K as k,L as P,O as x,Q as F,T as B,W as q,X as G,Y as K,Z as V,_ as H,$ as z,a0 as j,a1 as W,a2 as Q,a3 as $,a4 as Y,f as J,g as X,a5 as Z,a6 as ee,a7 as te,a8 as se,a9 as ne,aa as re,ab as ie,ac as oe,ad as ae,ae as ce,af as de,ag as le,ah as ue,ai as he,aj as pe,ak as me,al as fe,am as ge,an as ye,m as Ie,h as ve}from"./chunks/common-DN_g4O3n.js";import{R as Ce,ao as Se,ap as Ee}from"./chunks/common-DN_g4O3n.js";import{a as be,b as Ae,g as Te,c as we,I as Ne,d as Me,v as Re,e as _e,f as Ue,h as De,i as Le,j as Oe,M as ke,k as Pe,l as xe,V as Fe}from"./chunks/chat-manager-DH8a6Qj9.js";import{C as Be}from"./chunks/chat-manager-DH8a6Qj9.js";import{R as qe,c as Ge,P as Ke,a as Ve,S as He,m as ze}from"./chunks/group-user-info-resolver-FNRqDg18.js";import{i as je,a as We,l as Qe,L as $e,e as Ye,b as Je}from"./chunks/reflection-proto-codec-64ocOTHU.js";import{G as Xe,C as Ze,a as et,P as tt}from"./chunks/event-system-D6IJA0C4.js";import{n as st,J as nt}from"./chunks/index-CjofwvEQ.js";import{G as rt,a as it}from"./chunks/index-CjofwvEQ.js";import{n as ot}from"./chunks/profile-version-DLMz8lqW.js";import{a as at,t as ct}from"./chunks/session-list-query-Dnp2HbpW.js";import{s as dt,a as lt,b as ut,i as ht}from"./chunks/cache-utils-BwRPIZ7n.js";import{z as pt}from"zod";import{r as mt,R as ft}from"./chunks/index-uKWbjx-u.js";import{C as gt}from"./chunks/index-uKWbjx-u.js";import{ChatThread as yt,ChatThreadManager as It}from"./managers/chat-thread/index.js";import{ChatRoom as vt,ChatRoomManager as Ct}from"./managers/chatroom/index.js";import{PresenceManager as St}from"./managers/presence/index.js";import{PushManager as Et}from"./managers/push/index.js";import{UserInfoManager as bt}from"./managers/user-info/index.js";const At="onChatRoomDestroyed",Tt="onMembersJoined",wt="onMembersExited",Nt="onRemovedFromChatRoom",Mt="onMuteListAdded",Rt="onMuteListRemoved",_t="onAllowListAdded",Ut="onAllowListRemoved",Dt="onAllMemberMuteStateChanged",Lt="onAdminAdded",Ot="onAdminRemoved",kt="onOwnerChanged",Pt="onAnnouncementChanged",xt="onChatRoomInfoChanged",Ft="onAttributesUpdate",Bt="onAttributesRemoved",qt={ORIGINAL:"original",LARGE:"large"},Gt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function Kt(e){return"object"==typeof e.stream&&null!==e.stream}const Vt=0,Ht=1,zt=2,jt=3,Wt=4,Qt=0,$t=1,Yt=2,Jt=3,Xt=4,Zt=5,es=6,ts=7,ss=8,ns=0,rs=1,is=2,os=3,as=4,cs=5,ds=6,ls=7,us=8,hs=0,ps=1,ms=2,fs=3,gs=4,ys=0,Is=1,vs=2,Cs=3,Ss=5,Es=0,bs=1,As=2,Ts=0,ws=0,Ns=2,Ms=0,Rs=1,_s=2,Us=3,Ds=4,Ls=5,Os=6,ks=7,Ps=8,xs=9,Fs=10,Bs=11,qs=12,Gs=13,Ks=14,Vs=15,Hs=16,zs=17,js=18,Ws=19,Qs=20,$s=1,Ys=2,Js=3,Xs=4,Zs=5,en=6,tn=7,sn=8,nn="Sorry, user register limit",rn="Sorry, user register rate limit",on="Sorry, token expired",an="Sorry, token or password does not match login info",cn="Sorry, user not found",dn="Sorry, the app month live count limit",ln="Sorry, the app day live count limit",un="Sorry, the app online count limit",hn={[Rs]:e.AUTH_UNAUTHORIZED,[_s]:e.AUTH_UNAUTHORIZED,[Us]:e.VALIDATION_REQUIRED,[Ds]:e.VALIDATION_INVALID_FORMAT,[Ls]:e.CONNECTION_WEBSOCKET_ERROR,[Os]:e.AUTH_TOKEN_EXPIRED,[ks]:e.AUTH_FORBIDDEN,[Ws]:e.AUTH_FORBIDDEN,[Ps]:e.CONNECTION_WEBSOCKET_ERROR,[xs]:e.UNKNOWN,[Fs]:e.UNKNOWN,[Bs]:e.AUTH_BIND_ANOTHER_DEVICE,[qs]:e.AUTH_FORBIDDEN,[Gs]:e.AUTH_LOGIN_TOO_MANY_DEVICES,[Ks]:e.SERVICE_LIMIT_EXCEEDED,[Vs]:e.AUTH_USER_MUTED,[Hs]:e.UNKNOWN,[zs]:e.UNKNOWN,[js]:e.MESSAGE_DECODE_FAILED,[Qs]:e.USER_DEVICE_CHANGED},pn=/* @__PURE__ */new Set([Rs,_s,Us,Ds,Os,ks,Ws,xs,Fs,Bs,qs,Gs,Ks,Vs,Hs,zs,js,Qs]),mn={[nn]:e.SERVICE_LIMIT_EXCEEDED,[rn]:e.SERVICE_LIMIT_EXCEEDED,[on]:e.AUTH_TOKEN_EXPIRED,[an]:e.AUTH_UNAUTHORIZED,[cn]: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},fn=[["limit directed users",e.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.AUTH_FORBIDDEN]],gn={[dn]:e.SERVICE_LIMIT_EXCEEDED,[ln]:e.SERVICE_LIMIT_EXCEEDED,[un]: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},yn=(t,s)=>{if("number"!=typeof t)return{code:e.UNKNOWN,retryable:!0};const n=((t,s)=>{if(s){if(t===Rs){const t=mn[s];if(void 0!==t)return t;for(const[e,n]of fn)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===ks?gn[s]:t===Ws?e.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===Vs?e.AUTH_USER_MUTED:void 0}})(t,s),r=hn[t]??e.UNKNOWN;return{code:n??r,retryable:!pn.has(t)}},In={[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"},vn=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)},Cn=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 Sn{constructor(){this.lastEventKey=null}normalize(e,t){const s=(e=>{switch(e){case be.CONNECTING:case be.RECONNECTING:return Ae.CONNECTING;case be.CONNECTED:return Ae.CONNECTED;case be.DISCONNECTED:return Ae.DISCONNECTED;case be.RECONNECT_FAILED:return Ae.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 En={web:qe.WEB,"mp-weixin":qe.WECHAT_MINIAPP,"mp-alipay":qe.ALIPAY_MINIAPP,"mp-baidu":qe.BAIDU_MINIAPP,"mp-toutiao":qe.TOUTIAO_MINIAPP,"mp-lark":qe.LARK_MINIAPP,"mp-qq":qe.QQ_MINIAPP,"mp-kuaishou":qe.KUAISHOU_MINIAPP,"mp-jd":qe.JD_MINIAPP,"mp-360":qe.MINIAPP_360,"mp-harmony":qe.HARMONY_MINIAPP,"quickapp-webview":qe.QUICKAPP,"quickapp-webview-union":qe.QUICKAPP,"quickapp-webview-huawei":qe.QUICKAPP},bn=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},An=e=>(e=>bn(e,"canIUse")&&bn(e,"getSystemInfo"))(e)||(e=>bn(e,"request")&&bn(e,"connectSocket"))(e),Tn=(e,t)=>t===qe.WECHAT_MINIAPP?e.wx:t===qe.QQ_MINIAPP?e.qq:t===qe.TOUTIAO_MINIAPP?e.tt:t===qe.BAIDU_MINIAPP?e.swan:t===qe.ALIPAY_MINIAPP?e.my:t===qe.DINGTALK_MINIAPP?e.dd:t===qe.JD_MINIAPP?e.jd:t===qe.KUAISHOU_MINIAPP?e.ks:t===qe.UNIAPP?e.uni:void 0,wn=e=>{const t=e?.miniGlobal;return An(t)?t:e},Nn=e=>void 0!==e.window&&void 0!==e.document,Mn=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;try{if(!bn(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},_n=e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;if("string"==typeof s)return En[s]??qe.UNIAPP}catch{return qe.UNIAPP}return Nn(e)?qe.WEB:qe.UNIAPP},Un=(e,t)=>{const s=e??Te();if(t){const e=t===qe.UNIAPP||Rn(s);return{platform:t,hostPlatform:e?_n(s):t,framework:e?"uniapp":Nn(s)?"web":"native",global:e&&s.uni?s.uni:wn(Tn(s,t))??s}}return Rn(s)?{platform:qe.UNIAPP,hostPlatform:_n(s),framework:"uniapp",global:s.uni??s}:An(s.swan)?{platform:qe.BAIDU_MINIAPP,hostPlatform:qe.BAIDU_MINIAPP,framework:"native",global:wn(s.swan)??s.swan}:An(s.tt)?{platform:qe.TOUTIAO_MINIAPP,hostPlatform:qe.TOUTIAO_MINIAPP,framework:"native",global:wn(s.tt)??s.tt}:An(s.dd)?{platform:qe.DINGTALK_MINIAPP,hostPlatform:qe.DINGTALK_MINIAPP,framework:"native",global:wn(s.dd)??s.dd}:An(s.my)?{platform:qe.ALIPAY_MINIAPP,hostPlatform:qe.ALIPAY_MINIAPP,framework:"native",global:wn(s.my)??s.my}:An(s.wx)?{platform:qe.WECHAT_MINIAPP,hostPlatform:qe.WECHAT_MINIAPP,framework:"native",global:wn(s.wx)??s.wx}:An(s.qq)?{platform:qe.QQ_MINIAPP,hostPlatform:qe.QQ_MINIAPP,framework:"native",global:wn(s.qq)??s.qq}:An(s.jd)?{platform:qe.JD_MINIAPP,hostPlatform:qe.JD_MINIAPP,framework:"native",global:wn(s.jd)??s.jd}:An(s.ks)?{platform:qe.KUAISHOU_MINIAPP,hostPlatform:qe.KUAISHOU_MINIAPP,framework:"native",global:wn(s.ks)??s.ks}:(e=>"ReactNative"===e.navigator?.product)(s)?{platform:qe.REACT_NATIVE,hostPlatform:qe.REACT_NATIVE,framework:"react-native",global:s}:(e=>"string"==typeof e.process?.versions?.electron)(s)?{platform:Nn(s)?qe.ELECTRON_RENDERER:qe.ELECTRON_MAIN,hostPlatform:Nn(s)?qe.ELECTRON_RENDERER:qe.ELECTRON_MAIN,framework:"electron",global:s}:Mn(s)||Nn(s)?{platform:qe.WEB,hostPlatform:qe.WEB,framework:Mn(s)?"worker":"web",global:s}:{platform:qe.UNKNOWN,hostPlatform:qe.UNKNOWN,framework:"native",global:s}},Dn=e=>e===qe.WECHAT_MINIAPP||e===qe.QQ_MINIAPP||e===qe.TOUTIAO_MINIAPP||e===qe.BAIDU_MINIAPP||e===qe.ALIPAY_MINIAPP||e===qe.DINGTALK_MINIAPP||e===qe.LARK_MINIAPP||e===qe.KUAISHOU_MINIAPP||e===qe.JD_MINIAPP||e===qe.MINIAPP_360||e===qe.HARMONY_MINIAPP||e===qe.QUICKAPP||e===qe.UNIAPP,Ln=["request","upload","socket","proto"],On=(e,t=Ln)=>{const s=((e,t=Ln)=>t.filter(t=>!e[t]))(e,t);if(0!==s.length)throw Ge("Platform missing required capabilities.",{code:Ke.MISSING_CAPABILITY,stage:Ve.INIT,retryable:!1,details:{required:[...t],missing:s}})},kn={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}}}}}}}}}},Pn=e=>{if(!e||0===e.trim().length)throw Ge("Proto type name is required.",{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:e}})};class xn{constructor(){this.codecMap=/* @__PURE__ */new Map}register(e,t){Pn(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:s=>{const n=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw Ge("Proto payload must be an object.",{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(s,e),r=t.fromObject(n);return t.encode(r).finish()},decode:e=>{const s=t.decode(e);return t.toObject(s,{longs:String,enums:Number,defaults:!1})}})}get(e){return Pn(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Ge("Proto codec not found.",{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:e}})}}let Fn=!1,Bn=null,qn=null,Gn=null;const Kn=e=>e.startsWith(".")?e.slice(1):e,Vn=e=>e instanceof Qe.Namespace,Hn=e=>e instanceof Qe.Type,zn=e=>{for(const t of e.nestedArray)Hn(t)?je(t):Vn(t)&&zn(t)},jn=()=>{Fn||(Qe.util.Long=$e,Qe.configure(),Fn=!0),We();const e=Qe.Root.fromJSON(kn);return zn(e),e},Wn=(e,t)=>{const s=e.nestedArray;for(const n of s){if(Hn(n)){const e=Kn(n.fullName);je(n),t.registerType(e,n);continue}Vn(n)&&Wn(n,t)}},Qn=(e,t,s)=>{const n=t instanceof Error?t.message:String(t);return Ge(`Static proto ${s} failed.`,{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:e,operation:s,cause:n}})},$n=()=>Bn||(Bn=jn(),Bn),Yn=()=>{if(Gn)return Gn;const e=(()=>{if(qn)return qn;const e=new xn,t=$n();return Wn(t,e),qn=e,e})();return Gn={encode(t,s){try{return e.getOrThrow(Kn(t)).encode(s)}catch(n){throw Qn(t,n,"encode")}},decode(t,s){try{return e.getOrThrow(Kn(t)).decode(s)}catch(n){throw Qn(t,n,"decode")}}},Gn},Jn=e=>{const t={};if("function"==typeof e.forEach)return e.forEach((e,s)=>{t[s]=e}),t;const s=e.get?.("content-type");return s&&(t["content-type"]=s),t},Xn=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(s){const n=s.method??"GET",r={...s.headers??{}},i=new AbortController,o=s.timeoutMs??e?.timeoutMs??15e3,a=setTimeout(()=>{i.abort()},o),c=((e,t,s)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==s)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(s,r,n);try{const e=await t(s.url,{method:n,headers:r,body:c,signal:s.signal??i.signal});let o;if("arraybuffer"===s.responseType)o=await e.arrayBuffer();else if("text"===s.responseType)o=await e.text();else{const t=e.headers.get("content-type")??"",s=await e.text();o=t.includes("application/json")&&s?JSON.parse(s):s}return{status:e.status,headers:Jn(e.headers),data:o}}catch(d){throw Ge("Request adapter execution failed.",{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!0,details:{url:s.url,method:n,cause:d instanceof Error?d.message:String(d)}})}finally{clearTimeout(a)}}}},Zn=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,er=e=>"function"==typeof e.on&&"function"==typeof e.off,tr=(e,t,s)=>{if(Zn(e))return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)};if(er(e)){const n=e;return n.on(t,s),()=>{n.off(t,s)}}throw Ge("Socket event listener API is unsupported.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!1,details:{event:t}})},sr=(e,t,s)=>{if(Zn(e)){const n=(...r)=>{e.removeEventListener(t,n),s(...r)};return e.addEventListener(t,n),()=>{e.removeEventListener(t,n)}}if(er(e)){const n=e;if("function"==typeof n.once)return n.once?.(t,s),()=>{n.off(t,s)};let r=()=>{};return r=tr(e,t,(...e)=>{r(),s(...e)}),r}throw Ge("Socket one-time listener API is unsupported.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!1,details:{event:t}})},nr=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?nr(e.data):null;var t},rr=e=>{const t=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set,n=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set;return tr(e,"open",()=>{t.forEach(e=>{e()})}),tr(e,"message",(...e)=>{const t=nr(e[0]);null!==t&&s.forEach(e=>{e(t)})}),tr(e,"error",(...e)=>{const t=e[0];n.forEach(e=>{e(t)})}),tr(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);r.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==He.OPEN)throw Ge("Socket is not open.",{code:Ke.SOCKET_FAILED,stage:Ve.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=>(n.add(e),()=>{n.delete(e)}),onClose:e=>(r.add(e),()=>{r.delete(e)})}},ir=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((s,n)=>{let r;try{r=new t(e.url,e.protocols);try{r.binaryType="arraybuffer"}catch{}}catch(u){return void n(Ge("Socket creation failed.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{cause:u instanceof Error?u.message:String(u)}}))}let i,o=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},l=()=>{c||(c=!0,o(),a(),d(),r.close(),n(Ge("Socket connection timed out.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=sr(r,"open",()=>{c||(c=!0,o(),a(),d(),s(rr(r)))}),a=sr(r,"error",e=>{if(c)return;c=!0,o(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;n(Ge("Socket connection failed before open.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(l,e.timeoutMs))})}},or=(e,t)=>{throw Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.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 Ge("Web upload adapter only supports web-file source.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const s=t.source.file;if(!s)throw Ge("Upload source file is required for web-file uploads.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const n="undefined"!=typeof Blob&&s instanceof Blob,r=t.source.name??"upload.bin";n?e.append("file",s,r):e.append("file",s)})(t,e),t},cr=(e,t,s)=>new Promise((n,r)=>{const i=e(),o=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})})})(i,s),i.addEventListener("abort",()=>{try{or("abort",s)}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{or("timeout",s)}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{or("network",s)}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{n({status:i.status,body:i.responseText})});try{const e=ar(s);i.timeout=o,i.open("POST",s.url),((e,t)=>{Object.entries(t??{}).forEach(([t,s])=>{e.setRequestHeader(t,s)})})(i,s.headers),i.send(e)}catch(a){r(Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{url:s.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),dr=(e,t)=>e?"timeout":"abort",lr=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(n){if("function"==typeof t)return cr(t,e,n);if("function"==typeof s)return(async(e,t,s)=>{const n=s.timeoutMs??t?.timeoutMs??3e4;let r=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,o=i&&Number.isFinite(n)?setTimeout(()=>{r=!0,i.abort()},n):void 0,a=((e,t)=>e??t?.signal)(s.signal,i);try{const t=ar(s),n=await e(s.url,{method:"POST",headers:s.headers,body:t,signal:a}),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(c){const e=c instanceof Error&&"AbortError"===c.name;throw Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!e,details:{reason:e?dr(r):"network",url:s.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(s,e,n);throw Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{reason:"missing-upload-runtime",url:n.url}})}}},ur=(e,t)=>{const s=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{s.append(e,t)}),s.append("file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw Ge("React Native upload adapter only supports rn-uri source.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),s},hr=e=>{const t=e?.fetchImpl,s=e?.formDataCtor;if("function"==typeof t&&"function"==typeof s)return{async upload(n){const r=n.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let o=!1;const a=i&&Number.isFinite(r)?setTimeout(()=>{o=!0,i.abort()},r):void 0;try{const e=ur(s,n),r=await t(n.url,{method:"POST",headers:n.headers,body:e,signal:n.signal??i?.signal}),o=await r.text(),a=n.source.size;return"number"==typeof a&&n.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:r.status,body:o}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===Ke.UPLOAD_FAILED&&t.stage===Ve.UPLOAD})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw Ge("React Native upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!e||o,details:{url:n.url,reason:e?o?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},pr=(e,t)=>e+t&4294967295,mr=(e,t,s,n,r,i)=>{return pr((o=pr(pr(t,e),pr(n,i)))<<(a=r)|o>>>32-a,s);var o,a},fr=(e,t,s,n,r,i,o)=>mr(t&s|~t&n,e,t,r,i,o),gr=(e,t,s,n,r,i,o)=>mr(t&n|s&~n,e,t,r,i,o),yr=(e,t,s,n,r,i,o)=>mr(t^s^n,e,t,r,i,o),Ir=(e,t,s,n,r,i,o)=>mr(s^(t|~n),e,t,r,i,o),vr=(e,t)=>{let[s,n,r,i]=e;s=fr(s,n,r,i,t[0]??0,7,-680876936),i=fr(i,s,n,r,t[1]??0,12,-389564586),r=fr(r,i,s,n,t[2]??0,17,606105819),n=fr(n,r,i,s,t[3]??0,22,-1044525330),s=fr(s,n,r,i,t[4]??0,7,-176418897),i=fr(i,s,n,r,t[5]??0,12,1200080426),r=fr(r,i,s,n,t[6]??0,17,-1473231341),n=fr(n,r,i,s,t[7]??0,22,-45705983),s=fr(s,n,r,i,t[8]??0,7,1770035416),i=fr(i,s,n,r,t[9]??0,12,-1958414417),r=fr(r,i,s,n,t[10]??0,17,-42063),n=fr(n,r,i,s,t[11]??0,22,-1990404162),s=fr(s,n,r,i,t[12]??0,7,1804603682),i=fr(i,s,n,r,t[13]??0,12,-40341101),r=fr(r,i,s,n,t[14]??0,17,-1502002290),n=fr(n,r,i,s,t[15]??0,22,1236535329),s=gr(s,n,r,i,t[1]??0,5,-165796510),i=gr(i,s,n,r,t[6]??0,9,-1069501632),r=gr(r,i,s,n,t[11]??0,14,643717713),n=gr(n,r,i,s,t[0]??0,20,-373897302),s=gr(s,n,r,i,t[5]??0,5,-701558691),i=gr(i,s,n,r,t[10]??0,9,38016083),r=gr(r,i,s,n,t[15]??0,14,-660478335),n=gr(n,r,i,s,t[4]??0,20,-405537848),s=gr(s,n,r,i,t[9]??0,5,568446438),i=gr(i,s,n,r,t[14]??0,9,-1019803690),r=gr(r,i,s,n,t[3]??0,14,-187363961),n=gr(n,r,i,s,t[8]??0,20,1163531501),s=gr(s,n,r,i,t[13]??0,5,-1444681467),i=gr(i,s,n,r,t[2]??0,9,-51403784),r=gr(r,i,s,n,t[7]??0,14,1735328473),n=gr(n,r,i,s,t[12]??0,20,-1926607734),s=yr(s,n,r,i,t[5]??0,4,-378558),i=yr(i,s,n,r,t[8]??0,11,-2022574463),r=yr(r,i,s,n,t[11]??0,16,1839030562),n=yr(n,r,i,s,t[14]??0,23,-35309556),s=yr(s,n,r,i,t[1]??0,4,-1530992060),i=yr(i,s,n,r,t[4]??0,11,1272893353),r=yr(r,i,s,n,t[7]??0,16,-155497632),n=yr(n,r,i,s,t[10]??0,23,-1094730640),s=yr(s,n,r,i,t[13]??0,4,681279174),i=yr(i,s,n,r,t[0]??0,11,-358537222),r=yr(r,i,s,n,t[3]??0,16,-722521979),n=yr(n,r,i,s,t[6]??0,23,76029189),s=yr(s,n,r,i,t[9]??0,4,-640364487),i=yr(i,s,n,r,t[12]??0,11,-421815835),r=yr(r,i,s,n,t[15]??0,16,530742520),n=yr(n,r,i,s,t[2]??0,23,-995338651),s=Ir(s,n,r,i,t[0]??0,6,-198630844),i=Ir(i,s,n,r,t[7]??0,10,1126891415),r=Ir(r,i,s,n,t[14]??0,15,-1416354905),n=Ir(n,r,i,s,t[5]??0,21,-57434055),s=Ir(s,n,r,i,t[12]??0,6,1700485571),i=Ir(i,s,n,r,t[3]??0,10,-1894986606),r=Ir(r,i,s,n,t[10]??0,15,-1051523),n=Ir(n,r,i,s,t[1]??0,21,-2054922799),s=Ir(s,n,r,i,t[8]??0,6,1873313359),i=Ir(i,s,n,r,t[15]??0,10,-30611744),r=Ir(r,i,s,n,t[6]??0,15,-1560198380),n=Ir(n,r,i,s,t[13]??0,21,1309151649),s=Ir(s,n,r,i,t[4]??0,6,-145523070),i=Ir(i,s,n,r,t[11]??0,10,-1120210379),r=Ir(r,i,s,n,t[2]??0,15,718787259),n=Ir(n,r,i,s,t[9]??0,21,-343485551),e[0]=pr(s,e[0]),e[1]=pr(n,e[1]),e[2]=pr(r,e[2]),e[3]=pr(i,e[3])},Cr=(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},Sr=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},Er=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)vr(t,Cr(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&&(vr(t,n),n.fill(0));const o=8*e.length;return n[14]=4294967295&o,n[15]=Math.floor(o/4294967296),vr(t,n),t.map(Sr).join("")},br=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 Ge("Image decode capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,s)=>{const n=new Image;n.onload=()=>{e({image:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,cleanup:()=>{URL.revokeObjectURL(t)}})},n.onerror=()=>{URL.revokeObjectURL(t),s(Ge("Image decode failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{reason:"image load error"}}))},n.src=t})},Ar=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw Ge("Web image processor only supports web file source",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.file},Tr=()=>({async getImageInfo(e){const t=Ar(e),s=await br(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=Ar(e),n=await br(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))}})(n.width,n.height,t.maxShortEdge),i=((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 Ge("Canvas capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(s.width,s.height),o=i.getContext("2d");if(!o)throw Ge("Canvas 2d context is missing",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1});o.drawImage(n.image,0,0,s.width,s.height);const a="image/png"===(r=e.mimeType)||"image/webp"===r?r:"image/jpeg",c=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((n,r)=>{e.toBlob(e=>{e?n(e):r(Ge("Image encode failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,s)});throw Ge("Canvas encode capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,a,t.quality),d=(e=>e.name??"image")(e),l="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:l??c,name:d,mimeType:a,size:l?.size??c.size},width:s.width,height:s.height,fileName:d,fileType:a,fileSize:l?.size??c.size,webFile:l}}finally{n.cleanup()}var r},async computeMd5(e){const t=Ar(e),s=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw Ge("Binary read capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>{s(Ge("Binary read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1}))},n.onload=()=>{n.result instanceof ArrayBuffer?t(n.result):s(Ge("Binary read returned invalid result",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1}))},n.readAsArrayBuffer(e)})})(t);return Er(new Uint8Array(s))}}),wr=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)},Nr=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw Ge("Miniapp image processor only supports miniapp path source",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.path},Mr=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw Ge("Miniapp file system capability is missing",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{capability:"getFileSystemManager"}})},Rr=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},_r=async(e,t)=>new Promise((s,n)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{n(e instanceof Error?e:new Error(wr(e)))}})}).catch(e=>{throw Ge("Miniapp image info read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{src:t,cause:wr(e)}})}),Ur=(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 _r(e,t);return Ur(t,s)},Lr=e=>({async getImageInfo(t){const s=Nr(t),n=await _r(e,s),r=Rr(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 n=Nr(t);if("function"!=typeof e.compressImage)throw Ge("Miniapp image compress capability is missing",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{capability:"compressImage"}});const r=await _r(e,n),i=Ur(n,r),o=((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))}})(r.width,r.height,s.maxShortEdge),a=await new Promise((t,n)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*s.quality))),compressedWidth:o.width,compressedHeight:o.height,success:e=>{e.tempFilePath?t(e.tempFilePath):n(new Error("compressImage missing tempFilePath"))},fail:e=>{n(e instanceof Error?e:new Error(wr(e)))}})}).catch(e=>{throw Ge("Miniapp image compress failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{src:i,cause:wr(e)}})}),c=await Dr(e,a),d=await _r(e,c),l=Rr(d.type)??t.mimeType,u=await(async(e,t,s)=>{const n=Mr(e);return n.getFileInfo?new Promise((e,s)=>{n.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{s(e instanceof Error?e:new Error(wr(e)))}})}).catch(e=>{throw Ge("Miniapp file info read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{filePath:t,cause:wr(e)}})}):s})(e,c,t.size);return{source:{sourceType:"miniapp-path",path:c,name:t.name,mimeType:l,size:u},width:d.width,height:d.height,fileName:t.name,fileType:l,fileSize:u}},async computeMd5(t){const s=Nr(t),n=await Dr(e,s),r=await(async(e,t)=>{const s=Mr(e),n=await new Promise((e,n)=>{s.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{n(e instanceof Error?e:new Error(wr(e)))}})}).catch(e=>{throw Ge("Miniapp file read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{filePath:t,cause:wr(e)}})});return n instanceof ArrayBuffer?new Uint8Array(n):"function"==typeof TextEncoder?(new TextEncoder).encode(n):Uint8Array.from(Array.from(n).map(e=>255&e.charCodeAt(0)))})(e,n);return Er(r)}}),Or="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",kr=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Pr=e=>e===qe.ALIPAY_MINIAPP||e===qe.DINGTALK_MINIAPP,xr=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=Or.indexOf(t[o]??""),s=Or.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:Or.indexOf(a),l="="===c?0:Or.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},Fr=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Br=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},qr=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Fr(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?qr(s.data,t+1):e},Gr=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Br(e);if(Fr(e))try{return Br(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Br(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=Gr(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=Gr(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)}},Kr=(e,s)=>{if("string"==typeof e)return e;const n=e instanceof Uint8Array?e:new Uint8Array(e);if(Pr(s)){const r=(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+=Or[o>>18&63],t+=Or[o>>12&63],t+=void 0===r?"=":Or[o>>6&63],t+=void 0===i?"=":Or[63&o]}return t})(n);return t.warn("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:s,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:n.byteLength,encodedCharacters:r.length,sourcePrefixHex:kr(n.subarray(0,8))}),r}const r=new ArrayBuffer(n.byteLength);return new Uint8Array(r).set(n),r},Vr=(e,s)=>{const n=qr(e.data);if("string"==typeof n){if(!Pr(s))return n;const r=xr(n),i=new Uint8Array(r);return t.warn("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:s,sourceType:n===e.data?"string":"wrapped-string",sourceCharacters:n.length,decodedBytes:r.byteLength,decodedPrefixHex:kr(i.subarray(0,8)),decodedSuffixHex:kr(i.subarray(Math.max(0,i.length-8)))}),r}const r=Gr(n);if(!r){const r="object"==typeof e.data&&null!==e.data?e.data:void 0;return void t.warn("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:s,sourceType:typeof n,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:r?Object.keys(r).slice(0,10):[],isBuffer:e.isBuffer})}if(!Pr(s))return r.buffer;const i=(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})(r);if(!i)return t.warn("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:s,sourceType:Object.prototype.toString.call(n),sourceBytes:r.byteLength,sourcePrefixHex:kr(r.subarray(0,8))}),r.buffer;const o=xr(i),a=new Uint8Array(o);return t.warn("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:s,sourceType:Object.prototype.toString.call(n),sourceBytes:r.byteLength,decodedBytes:o.byteLength,decodedPrefixHex:kr(a.subarray(0,8)),decodedSuffixHex:kr(a.subarray(Math.max(0,a.length-8)))}),o},Hr=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),zr=(e,t)=>Hr(e)&&"function"==typeof e[t],jr=e=>e instanceof Error?e.message:Hr(e)&&"string"==typeof e.errMsg?e.errMsg:Hr(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),Wr=e=>e?{...e}:{},Qr=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},$r=e=>{try{e.close()}catch{}},Yr=(e,s)=>new Promise((n,r)=>{let i=!1,o=()=>{};const a=(e,t,n)=>{i||(i=!0,o(),r(Ge(e,{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:n,details:{url:s.url,method:"GET",cause:jr(t)}})))},c=e.downloadFile?.({url:s.url,header:Wr(s.headers),timeout:s.timeoutMs??15e3,success:r=>{const c=r.tempFilePath??r.apFilePath;c?((e,t)=>new Promise((s,n)=>{const r=e.getFileSystemManager?.();r?r.readFile({filePath:t,success:e=>{const t=Gr(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,c).then(e=>{i||(i=!0,o(),t.warn("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:s.url,filePathType:r.apFilePath?"apFilePath":"tempFilePath",status:r.statusCode??200,bytes:e.byteLength}),n({status:r.statusCode??200,headers:r.header??{},data:e}))}).catch(e=>{a("Mini program downloaded file read failed.",e,!1)}):a("Mini program download did not return a file path.",r,!1)},fail:e=>{a("Mini program file download failed.",e,!0)}});o=Qr(s.signal,()=>{c?.abort(),a("Mini program file download aborted.","abort",!1)})}),Jr=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,n)=>{let r=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:Wr(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{r(),s({status:e.statusCode,headers:e.header??{},data:e.data})},fail:e=>{r(),n(Ge("Mini program request failed.",{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:jr(e)}}))}});r=Qr(t.signal,()=>{i.abort(),n(Ge("Mini program request aborted.",{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Yr(e,t)}),Xr=(e,t)=>({connect:s=>new Promise((n,r)=>{let i,o,a=!1;const c=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},d=(e,t,n)=>{a||(a=!0,c(),i&&$r(i),r(Ge(t,{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:n,details:{url:s.url,cause:jr(e)}})))},l=e=>{if(!(zr(s=e,"send")&&zr(s,"close")&&zr(s,"onOpen")&&zr(s,"onMessage")&&zr(s,"onError")&&zr(s,"onClose")))return void d(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var s;const r=e;if(a)return void $r(r);i=r;const o=()=>{r.offOpen?.(l),r.offError?.(u)},l=()=>{a?$r(r):(a=!0,c(),o(),n(((e,t,s=He.CONNECTING)=>{const n=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set,o=/* @__PURE__ */new Set;let a=s;return e.onOpen(()=>{a=He.OPEN,n.forEach(e=>{e()})}),e.onMessage(e=>{const s=Vr(e,t);void 0!==s&&r.forEach(e=>{e(s)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=He.CLOSED,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(s){if(a!==He.OPEN)throw Ge("Mini program socket is not open.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{readyState:a}});return new Promise((n,r)=>{e.send({data:Kr(s,t),success:n,fail:e=>{r(Ge("Mini program socket send failed.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{cause:jr(e)}}))}})})},close(t,s){a=He.CLOSING,e.close({code:t,reason:s})},onOpen:e=>(n.add(e),()=>{n.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}})(r,t,He.OPEN)))},u=e=>{o(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};r.onOpen(l),r.onError(u)};let u;"number"==typeof s.timeoutMs&&s.timeoutMs>0&&(o=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},s.timeoutMs));try{u=e.connectSocket({url:s.url,...t===qe.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(s.protocols)?[...s.protocols]:"string"==typeof s.protocols?[s.protocols]:void 0,fail:e=>{d(e,"Mini program socket connect failed.",!0)}})}catch(p){return void d(p,"Mini program socket creation failed.",!0)}var h;"object"!=typeof(h=u)||null===h||"function"!=typeof h.then?l(u):Promise.resolve(u).then(e=>l(e),e=>d(e,"Mini program socket connect failed.",!0))})}),Zr=e=>({upload:t=>new Promise((s,n)=>{const r=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw Ge("Mini program upload only supports miniapp-path source.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:r.path,name:"file",header:Wr(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i(),s({status:e.statusCode,body:e.data})},fail:e=>{i(),n(Ge("Mini program upload failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!0,details:{url:t.url,path:r.path,cause:jr(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=Qr(t.signal,()=>{o.abort(),n(Ge("Mini program upload aborted.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{url:t.url,path:r.path,reason:"abort"}}))})})}),ei=e=>({async getItem(t){if(zr(e,"getStorageSync"))try{const s=e.getStorageSync(t);return"string"==typeof s&&s.length>0?s:null}catch{return null}return zr(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(zr(e,"setStorageSync"))e.setStorageSync(t,s);else if(zr(e,"setStorage"))return new Promise((n,r)=>{e.setStorage({key:t,data:s,success:n,fail:e=>{r(e instanceof Error?e:new Error(jr(e)))}})})},async removeItem(t){if(zr(e,"removeStorageSync"))e.removeStorageSync(t);else if(zr(e,"removeStorage"))return new Promise((s,n)=>{e.removeStorage({key:t,success:s,fail:e=>{n(e instanceof Error?e:new Error(jr(e)))}})})}}),ti=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>zr(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 zr(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),zr(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{zr(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},n=()=>{t(!1)};return zr(e,"onAppShow")&&e.onAppShow(s),zr(e,"onAppHide")&&e.onAppHide(n),t(!0),()=>{zr(e,"offAppShow")&&e.offAppShow(s),zr(e,"offAppHide")&&e.offAppHide(n)}}}),si=(e,t=qe.WECHAT_MINIAPP,s=t)=>{const n=(e=>{if(zr(e,"request")&&zr(e,"connectSocket")&&zr(e,"uploadFile"))return e;throw Ge("Mini program platform capability is missing.",{code:Ke.MISSING_CAPABILITY,stage:Ve.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),r="function"==typeof n.getImageInfo?Lr(n):void 0;return{request:Jr(n),socket:Xr(n,s),upload:Zr(n),runtime:ti(n,t),storage:ei(n),imageProcessor:r}},ni=[qe.WEB,qe.ELECTRON_RENDERER,qe.REACT_NATIVE],ri=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},ii=e=>ni.includes(e),oi=(e,t)=>(e!==qe.UNIAPP||!ci(t))&&(ii(e)||e===qe.UNIAPP&&Nn(t)),ai=e=>ri(e,"getImageInfo")&&ri(e,"getFileSystemManager"),ci=e=>"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),di=(e,t)=>{if(ii(e)&&e!==qe.REACT_NATIVE)return Tr();if(Dn(e)&&ai(t))return Lr(t);if(e===qe.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Nn(e))return Tr();if(ai(e.uni))return Lr(e.uni);if(ai(e.wx))return Lr(e.wx)}},li=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())}},ui=(e,t,s,n)=>{if(e===qe.UNIAPP&&ci(s)&&void 0!==s.uni&&An(s.uni))return{...si(s.uni,e,t),proto:Yn()};if(((e,t)=>!oi(e,t)&&Dn(e))(e,s)&&An(n))return{...si(n,e,t),proto:Yn()};const r=s.XMLHttpRequest,i=oi(e,s),o=i?Xn({fetchImpl:s.fetch}):void 0,a=i?ir({webSocketCtor:s.WebSocket}):void 0,c=e===qe.REACT_NATIVE?hr({fetchImpl:s.fetch,formDataCtor:s.FormData}):i?lr({xhrFactory:"function"==typeof r?()=>new r:void 0,fetchImpl:s.fetch}):void 0,d=i&&e!==qe.REACT_NATIVE?(l={platform:e,windowRef:s.window,documentRef:s.document,navigatorRef:s.navigator},{getPlatform:()=>l.platform,getNetworkType:()=>!1===l.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(l.navigatorRef?.connection?.type??l.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=l.windowRef;if(!t)return()=>{};const s=()=>{e(!0)},n=()=>{e(!1)};return t.addEventListener("online",s),t.addEventListener("offline",n),"boolean"==typeof l.navigatorRef?.onLine&&e(l.navigatorRef.onLine),()=>{t.removeEventListener("online",s),t.removeEventListener("offline",n)}},onAppVisibilityChange(e){const t=l.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 l;return{request:o,upload:c,socket:a,runtime:d,proto:Yn(),storage:li(s),imageProcessor:i&&e!==qe.REACT_NATIVE?Tr():di(e,n)}},hi=(e,t)=>{if(void 0!==e)return e;throw Ge("Platform adapter initialization failed.",{code:Ke.INIT_FAILED,stage:Ve.INIT,retryable:!1,details:{capability:t}})},pi=(e,t)=>Un(t,e).platform,mi=e=>{const t=Te(e?.runtimeInput),s=Un(t,e?.prefer),n=s.platform,r=ui(n,s.hostPlatform,t,s.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,r),o={...r,...i},a=(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}))(o);On(a);return{platform:n,platformId:n,capability:a,request:hi(o.request,"request"),upload:hi(o.upload,"upload"),socket:hi(o.socket,"socket"),runtime:hi(o.runtime,"runtime"),proto:hi(o.proto,"proto"),storage:hi(o.storage,"storage"),imageProcessor:o.imageProcessor}},fi={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class gi{constructor(e={}){this.attemptCount=0,this.config={...fi,...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 t.debug(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const yi={interval:3e4,timeout:6e4},Ii="function"==typeof TextDecoder?new TextDecoder:null;class vi{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 s=this.extractMessageText(e);if(!s)return;const n=this.parseJson(s);if(!vi.isRecord(n))return;"pong"===vi.readString(n.type)&&(this.markAlive(),t.debug("Pong received"))},this.config={...yi,...e}}start(e,s,n){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=s||null,this.sendPing=n??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),t.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),t.debug("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===He.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=>{t.error("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),t.debug("Ping sent")}catch(e){t.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)?Ii?.decode(t)??Cn(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(()=>{t.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,s){try{if(e.readyState!==He.OPEN)return!1;this.attachWebSocket(e);const t=s??this.config.timeout;return await new Promise(e=>{const s=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},t);this.probeResolvers.push(t=>{clearTimeout(s),e(t)}),this.sendPingInternal()})}catch(n){return t.warn("Heartbeat probe failed",n),!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 Ci=null;function Si(){return Ci||(Ci=$n()),Ci}const Ei="websdk2:device-info",bi="webim",Ai="web",Ti=e=>{const t=Date.now(),s=e.deviceId,n=e.customOSPlatform,r=void 0!==n?e.customDeviceName:void 0,i=Te().localStorage,o=()=>{if(!i)return null;try{const t=i.getItem(Ei);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},a=e=>{if(i)try{i.setItem(Ei,JSON.stringify(e))}catch{}},c=e=>void 0===n?e:{deviceId:`custom${n}_${e.deviceUuid}`,deviceName:r??s,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=o();if(e)return c(e);if(s===bi){const e=`${Ai}_${t}`,n=c({deviceId:`${s}_${e}`,deviceName:s,deviceUuid:e});return a(n),n}if(void 0!==n){const e=c({deviceId:`webim_${Ai}_${s}`,deviceName:s,deviceUuid:`${Ai}_${t}`});return a(e),e}const r={deviceId:`webim_${Ai}_${s}`,deviceName:`webim_${Ai}_${s}`,deviceUuid:`webim_${Ai}_${s}`};return a(r),r}if(s===bi){const e=`random_${Ai}_${t}`;return c({deviceId:`${s}_${e}`,deviceName:s,deviceUuid:e})}if(void 0!==n){return c({deviceId:`webim_${Ai}_${s}`,deviceName:s,deviceUuid:`random_${Ai}_${t}`})}return{deviceId:`webim_${Ai}_${s}`,deviceName:`webim_${Ai}_${s}`,deviceUuid:`webim_${Ai}_${s}`}},wi=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Ni=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 $e(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Mi=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:sn,stringValue:JSON.stringify(n)})}catch{t.push({key:s,type:tn,stringValue:Object.prototype.toString.call(n)})}else t.push({key:s,type:tn,stringValue:n});else Number.isInteger(n)?t.push({key:s,type:Ys,varintValue:n}):t.push({key:s,type:en,doubleValue:n});else t.push({key:s,type:$s,varintValue:n?1:0});return t},Ri=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:tn;if(n!==$s)if(n!==Ys&&n!==Js&&n!==Xs)if(n!==Zs)if(n!==en){if(n!==sn)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},_i=/* @__PURE__ */new Set(["mute"]),Ui={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},Di=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Li=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Oi=(e,t)=>{const s=e?.map(e=>Di(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},ki=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=Li(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},Pi=e=>{const t=Li(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=Ui[n];if(!e)continue;let t=r;if(_i.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},xi=e=>{const t=Li(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:Di(t.operator)??Di(t.username)}},Fi=(e,t)=>({eventName:e,payload:t}),Bi=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=Di(e.from?.name),n=(r=e.to,Di(r?.[0]?.name));var r;switch(e.operation){case 1:return Fi(At,t);case 10:return Fi(Nt,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:n??s});case 17:return Fi(Tt,{...t,memberIds:Oi(e.members,s),ext:e.ext??e.eventExt});case 18:return Fi(wt,{...t,memberIds:Oi(e.members,s)});case 20:return Fi(kt,{...t,oldOwnerId:s,newOwnerId:n});case 21:return Fi(Lt,{...t,adminId:n??s});case 22:return Fi(Ot,{...t,adminId:n??s});case 23:{const s=(e=>{const t=Li(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):Oi(e.members,n),i=46388736e5;return Fi(Mt,{...t,userIds:r,muteMembers:s??Object.fromEntries(r.map(e=>[e,i])),muteExpire:ki(e.reason,e.eventExt)??i})}case 24:return Fi(Rt,{...t,userIds:Oi(e.members,n)});case 25:return Fi(Pt,{...t,announcement:e.reason??""});case 26:return Fi(Pt,{...t,announcement:""});case 29:return Fi(_t,{...t,userIds:Oi(e.members,n)});case 30:return Fi(Ut,{...t,userIds:Oi(e.members,n)});case 31:return Fi(Dt,{...t,isMuted:!0});case 32:return Fi(Dt,{...t,isMuted:!1});case 14:return Fi(xt,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Pi(e.eventExt)});case 43:{const n=xi(e.eventExt);return Fi(Ft,{...t,attributes:n.attributes,from:n.from??s})}case 44:{const n=xi(e.eventExt);return Fi(Bt,{...t,keyList:n.keyList,from:n.from??s})}default:return null}},qi=/* @__PURE__ */new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Gi={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Ki=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Vi=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Hi=(e,t)=>{const s=e?.map(e=>Ki(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},zi=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=Vi(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},ji=e=>{const t=Vi(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(qi.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},Wi=(e,t)=>{const s=Vi(t)??Vi(e);return st(s??void 0)??void 0},Qi=(e,t)=>{const s=Vi(t)??Vi(e);return Ki(s?.fileId)??Ki(s?.file_id)??Ki(e)??""},$i=(e,t)=>({eventName:e,payload:t}),Yi=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=Ki(e.from?.name),n=(r=e.to,Ki(r?.[0]?.name));var r;switch(e.operation){case 4:return $i(Xe.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return $i(Xe.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return $i(Xe.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:n,reason:e.reason});case 7:return $i(Xe.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return $i(Xe.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return $i(Xe.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return $i(Xe.USER_REMOVED,t);case 1:return $i(Xe.GROUP_DESTROYED,t);case 19:return $i(Xe.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=Vi(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=Ki(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):Hi(e.members,n);return $i(Xe.MUTE_LIST_ADDED,{...t,userIds:r,muteExpire:r.map(e=>s?.[e]).find(e=>void 0!==e)??zi(e.reason,e.eventExt)})}case 24:return $i(Xe.MUTE_LIST_REMOVED,{...t,userIds:Hi(e.members,n)});case 29:return $i(Xe.ALLOW_LIST_ADDED,{...t,userIds:Hi(e.members,n)});case 30:return $i(Xe.ALLOW_LIST_REMOVED,{...t,userIds:Hi(e.members,n)});case 31:return $i(Xe.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return $i(Xe.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return $i(Xe.ADMIN_ADDED,{...t,administratorId:n??s});case 22:return $i(Xe.ADMIN_REMOVED,{...t,administratorId:n??s});case 20:return $i(Xe.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:n});case 17:{const n=Hi(e.members,s);return $i(Xe.MEMBERS_JOINED,{...t,memberIds:n})}case 18:{const n=Hi(e.members,s);return $i(Xe.MEMBERS_EXITED,{...t,memberIds:n})}case 25:return $i(Xe.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return $i(Xe.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return $i(Xe.SHARED_FILE_ADDED,{...t,sharedFile:Wi(e.reason,e.eventExt)});case 28:return $i(Xe.SHARED_FILE_DELETED,{...t,fileId:Qi(e.reason,e.eventExt)});case 14:return $i(Xe.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:ji(e.eventExt)});case 41:return $i(Xe.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return $i(Xe.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const n=(e=>{const t=Vi(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:Ki(t.username),attribute:n}})(e.eventExt);return $i(Xe.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:n.userId,attribute:n.attribute,from:s,source:e.source??"direct"})}default:return null}},Ji=/* @__PURE__ */new WeakMap,Xi=(e,t)=>{Ji.set(e,t)},Zi=e=>Ji.get(e)??null,eo=(e,t)=>{const s=Zi(e);s&&Xi(t,s)},to=/* @__PURE__ */new WeakMap,so=e=>to.get(e),no="singleChat",ro="groupChat",io={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},oo=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ao=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}},co=e=>{if(!Array.isArray(e))return;const t=e.map(e=>oo(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},lo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),uo=(...e)=>{for(const t of e){const e=oo(t);if(e)return e}},ho=(e,t)=>Boolean(e&&t&&e===t),po=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),mo=(e,t,s)=>{const n=co(e);if(n&&n.length>0)return n;const r=(t??[]).map(e=>oo(e.name)).filter(e=>"string"==typeof e);if(r.length>0)return r;const i=oo(s?.name);return i?[i]:[]},fo=e=>{const t=ao(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}}},go=(e,s)=>{const n=uo(e.to?.[0]?.clientResource);if(1!==e.to?.length||oo(e.to[0]?.name)!==s.userId||!po(s.userId,n,s))return null;const r=(i=e.from,oo(i?.name)??"");var i;if(!r)return t.warn("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const o=(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 t.warn("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"contact",operation:o,targetUserId:r,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:n,timestamp:e.timestamp,raw:e.raw}},yo=(e,s)=>{if(!e.groupId)return t.warn("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const n=uo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!po(oo(e.from?.name),n,s))return null;const r=(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 t.warn("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===r)return null;const i=mo(e.members,e.to,e.from);return{category:"group",operation:r,groupId:e.groupId,userIds:i.length>0?i:void 0,operatorId:oo(e.from?.name),groupName:e.groupName,deviceId:n,timestamp:e.timestamp,raw:e.raw}},Io=(e,s)=>{if(!e.threadId)return t.warn("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const n=uo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!po(oo(e.from?.name),n,s))return null;const r=(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 t.warn("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===r)return null;const i=mo(e.members,e.to,e.from);return{category:"thread",operation:r,threadId:e.threadId,parentId:e.parentId,userIds:i.length>0?i:void 0,operatorId:oo(e.from?.name),threadName:e.threadName,deviceId:n,timestamp:e.timestamp,raw:e.raw}},vo=(e,s)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const n=uo(e.res,e.raw?.resource,e.raw?.clientResource);if(ho(n,s.clientResource))return t.debug("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const r="chat"===(i=e.type)||"singleChat"===i?no:ro;var i;const o=oo(e.id)??(r===no?oo(e.from):void 0);if(!o)return t.warn("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const a=(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 t.warn("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===a?null:{category:"conversation",operation:a,conversationId:o,conversationType:r,mark:"mark"===e.operation||"mark_delete"===e.operation?fo(e.ext):void 0,operatorId:oo(e.from),deviceId:n,timestamp:ao(e.ts),raw:e.raw}},Co=(e,s)=>{const n=uo(e.resource,e.raw?.resource,e.raw?.clientResource);if(ho(n,s.clientResource))return t.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const r=oo(e.to);if(!r)return t.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const i=oo(e.lastMsgId),o=co(e.msgIdList)??(i?[i]:void 0),a=ao(e.deleteTime);if(!o&&void 0===a)return t.warn("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:r}),null;const c=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(t.warn("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===c?null:{category:"messageRemoved",operation:c,conversationId:r,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?ro:no,messageIds:o,beforeTimestamp:a,deviceId:n,raw:e.raw}},So=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var Eo=4096,bo=65547,Ao=15,To=2113929216,wo=65536,No=65536,Mo=10485760,Ro={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},_o={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Uo(e){if(!(e>0))return No;if(e<=No)return No;if(e>1073741823)return e;for(var t=No;t<e;)t*=2;return t}var Do={byU16:0,byU32:1},Lo=0,Oo=1,ko=2,Po=0,xo=1;function Fo(e,t){return e[t]|e[t+1]<<8}function Bo(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function qo(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var Go="fast";function Ko(e){return 2654435761*(e>>>0)>>>20&4095}function Vo(e){return 2654435761*(e>>>0)>>>19&8191}function Ho(e,t,s){if("fast"===Go){var n=Bo(e,t);return s===Do.byU16?Vo(n):Ko(n)}throw new Error("Unsupported hash strategy: "+Go)}function zo(e,t,s,n,r){s[t]=e-r}function jo(e,t,s,n,r){zo(t,Ho(e,t,n),s,0,r)}function Wo(e,t,s,n){return t[e]+n}function Qo(e,t,s,n,r){return Wo(Ho(e,t,n),s,0,r)}function $o(e,t,s,n){for(var r=t;t<n-3;){if(Bo(e,t)!==Bo(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 Yo(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,A=0,T=i>0?i:s.length,w=0;if(r>To)return 0;switch(c){case Lo:default:l=n,u=n;break;case Oo:l=n-e.currentOffset,u=n-e.dictSize;break;case ko:l=n-e.currentOffset,u=n}if(a===Do.byU16&&r>=bo)return 0;if(r<13)return Zo(t,s,C,S,A,T,o);jo(t,m,p,a,l),h=Ho(t,++m,a);e:for(;;){var N,M,R=m,_=1,U=64;do{var D=h;if(m=R,R+=_,_=U++>>>6,R>E)return Zo(t,s,C,S,A,T,o);N=Wo(D,p,0,l),c===ko&&(N<n?(w=v,u=y):(w=0,u=n)),h=Ho(t,R,a),zo(m,D,p,0,l)}while(d===xo&&N<f||a!==Do.byU16&&N+65535<m||!Jo(t,g,m,N,w,c,n));for(;m>C&&N+w>u;){var L=N+w-1;if(t[m-1]!==(c===ko&&N<n?g[L-y+e.dictionaryStart]:t[L]))break;m--,N--}var O=m-C;if(M=A++,o&&A+O+8+Math.floor(O/255)>T)return 0;if(O>=Ao){var k=O-Ao;for(s[M]=240;k>=255;)s[A++]=255,k-=255;s[A++]=k}else s[M]=O<<4;if(O>=16&&s.set&&t.subarray)s.set(t.subarray(C,C+O),A),A+=O;else for(var P=0;P<O;P++)s[A++]=t[C+P];t:for(;;){var x;if(qo(s,A,m-N),A+=2,c===ko&&N<n){var F=m+(I-(N+w));if(F>b&&(F=b),(m+=4+(x=Xo(t,g,m+4,N+w+4-y+e.dictionaryStart,F,I-y)))===F&&F<b){var B=$o(t,m,n,b);x+=B,m+=B}}else m+=4+(x=$o(t,m+4,N+4,b));if(o&&A+6+(x>>>8)>T)return 0;if(x>=15){for(s[M]+=15,x-=15;x>=510;)s[A++]=255,s[A++]=255,x-=510;x>=255&&(x-=255,s[A++]=255),s[A++]=x}else s[M]+=x;if(C=m,m>E)break e;if(jo(t,m-2,p,a,l),N=Qo(t,m,p,a,l),c===ko&&(N<n?(w=v,u=y):(w=0,u=n)),jo(t,m,p,a,l),!((d!==xo||N>=f)&&N+65535>=m&&Jo(t,g,m,N,w,c,n)))break t;s[M=A++]=0}h=Ho(t,++m,a)}return Zo(t,s,C,S,A,T,o)}function Jo(e,t,s,n,r,i,o){var a,c=Bo(e,s);i===ko&&n+r<o?a=Bo(t,n+r):a=Bo(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 Zo(e,t,s,n,r,i,o){var a=n-s;if(o&&r+a+1+Math.floor((a+255-Ao)/255)>i)return 0;if(a>=Ao){for(t[r++]=240,a-=Ao;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 ea(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 ta(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)===Ao){var A=ea(e,N={ip:p},m-Ao,!0);if(p=N.ip,-1===A)return-(p-s)-1;if(f+(S+=A)<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 T=0;T<S;T++)t[f+T]=e[p+T];p+=S,f+=S;break}if(S>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+S),f);else for(T=0;T<S;T++)t[f+T]=e[p+T];if(f=E,(p+=S)+2>m)return-(p-s)-1;var w=Fo(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;A=ea(e,N={ip:p},m-5+1,!1);if(p=N.ip,-1===A)return-(p-s)-1;if(f+(S+=A)<f)return-(p-s)-1}if(S+=4,d===ko&&b<l){if(f+S>g-5)return-(p-s)-1;if(S<=l-b){var M=I-(l-b);for(T=0;T<S;T++)t[f+T]=t[M+T];f+=S}else{var R=l-b;for(M=I-R,T=0;T<R;T++)t[f+T]=t[M+T];var _=S-R;if(_>(f+=R)-l)for(var U=l,D=f+_;f<D;)t[f++]=t[U++];else{for(T=0;T<_;T++)t[f+T]=t[l+T];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 sa(){return{hashTable:new Uint32Array(Eo),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function na(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function ra(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?xo:Po;return e.dictionary&&c===n?(l=Yo(e,t,s,n,r,o||0,a||!1,Do.byU32,Oo,h),e.dictSize+=r,e.currentOffset+=r,l):(l=Yo(e,t,s,n,r,o||0,a||!1,Do.byU32,ko,h),e.dictionary=t,e.dictionaryStart=n,e.dictSize=r,e.currentOffset+=r,l)}function ia(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 oa(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function aa(e,t,s,n){return e.prefixSize=n,e.prefixEnd=s+n,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function ca(e,t,s,n,r,i,o){var a;if(e.prefixEnd===i){if((a=ta(t,s,n,r,i,o,!0,0,0,ko,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=ta(t,s,n,r,i,o,!0,0,0,ko,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function da(e){var t=(e=e||{}).minWorkArea||No,s=e.maxWorkArea||Mo,n=e.shrinkThreshold||t;t<No&&(t=No),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=wo+t,this.maxBufferSize=wo+s,this.shrinkThreshold=wo+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ro.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=sa()}function la(e){var t=(e=e||{}).minWorkArea||No,s=e.maxWorkArea||Mo,n=e.shrinkThreshold||t;t<No&&(t=No),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=wo+t,this.maxBufferSize=wo+s,this.shrinkThreshold=wo+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ro.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}da.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<wo?this.offset:wo,r=this.offset>wo?this.offset-wo:0;t.set(this.ringBuffer.subarray(r,r+n),0),ia(this.stream,t,0,n),s=n}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},da.prototype.compress=function(e,t){var s=e.length;if(s<=0)return _o.PARAM_ERROR;if(s>this.maxBufferSize-wo)return _o.PARAM_ERROR;if(s>this.ringBufferSize-wo){var n=Uo(s),r=wo+n;if(r>this.maxBufferSize&&(r=this.maxBufferSize),!this._resizeBuffer(r))return _o.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(ia(this.stream,this.ringBuffer,0,wo),this.offset=wo);var i=this.offset;this.ringBuffer.set(e,i);var o=ra(this.stream,this.ringBuffer,t,i,s,0,t.length,!0);return o<=0?_o.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),o)},da.prototype.reset=function(){this.offset=0,na(this.stream)},da.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},da.prototype._tryAutoShrink=function(){this.shrinkMode!==Ro.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ro.AUTO_IMMEDIATE||this.shrinkMode===Ro.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},da.prototype.getWorkArea=function(){return this.ringBufferSize-wo},da.prototype.getRingBufferSize=function(){return this.ringBufferSize},da.prototype.getBaseBufferSize=function(){return this.minBufferSize},da.prototype.getMaxBufferSize=function(){return this.maxBufferSize},da.prototype.getCurrentOffset=function(){return this.offset},da.prototype.getShrinkMode=function(){return this.shrinkMode},da.prototype.setShrinkMode=function(e){this.shrinkMode=e},da.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},da.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-wo,s=this.maxBufferSize-wo;if(e<t||e>s)return _o.PARAM_ERROR;this.shrinkThreshold=wo+e},la.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<wo?this.offset:wo,r=this.offset>wo?this.offset-wo:0;t.set(this.ringBuffer.subarray(r,r+n),0),s=n,aa(this.streamDecode,0,0,n)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},la.prototype.decompress=function(e,t,s){var n=e.length;if(n<=0||s<=0)return _o.PARAM_ERROR;if(s>this.maxBufferSize-wo)return _o.PARAM_ERROR;if(s>this.ringBufferSize-wo){var r=Uo(s),i=wo+r;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return _o.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var o=this.offset-wo;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+wo),0),aa(this.streamDecode,this.ringBuffer,0,wo),this.offset=wo}var a=ca(this.streamDecode,e,this.ringBuffer,0,n,this.offset,s);return a<=0?_o.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},la.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},la.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},la.prototype._tryAutoShrink=function(){this.shrinkMode!==Ro.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ro.AUTO_IMMEDIATE||this.shrinkMode===Ro.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},la.prototype.getWorkArea=function(){return this.ringBufferSize-wo},la.prototype.getRingBufferSize=function(){return this.ringBufferSize},la.prototype.getBaseBufferSize=function(){return this.minBufferSize},la.prototype.getMaxBufferSize=function(){return this.maxBufferSize},la.prototype.getCurrentOffset=function(){return this.offset},la.prototype.getShrinkMode=function(){return this.shrinkMode},la.prototype.setShrinkMode=function(e){this.shrinkMode=e},la.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},la.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-wo,s=this.maxBufferSize-wo;if(e<t||e>s)return _o.PARAM_ERROR;this.shrinkThreshold=wo+e};const ua={LZ4_MAX_INPUT_SIZE:To,BLOCK_MAX_SIZE:65536,DICT_SIZE:wo,DEFAULT_WORK_AREA:No,DEFAULT_MAX_WORK:Mo,SHRINK_MODE:Ro,LZ4_ERROR:_o,alignToPowerOf2:Uo,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".');Go=e},getHashStrategy:function(){return Go},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>To)return 0;if(0===n)return t.length>r?(t[r]=0,1):0;var i=n<bo?Do.byU16:Do.byU32;return Yo({hashTable:new Uint32Array(i===Do.byU16?8192:Eo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,0,!1,i,Lo,Po)},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>To)return 0;if(i<1)return 0;if(0===n)return t[r]=0,1;var o=n<bo?Do.byU16:Do.byU32;return Yo({hashTable:new Uint32Array(o===Do.byU16?8192:Eo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,i,!0,o,Lo,Po)},compressBound:function(e){return e<0||e>To?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:ta(e,t,s,n,r,i,!0,0,0,Lo,r,null,0))},decompressFast:function(e,t,s,n,r){return ta(e,t,s=s||0,0,n=n||0,r,!1,0,0,Oo,n-65536,0,65536)},createStream:sa,resetStream:na,loadDict:function(e,t,s,n){if(e.initCheck&&na(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;)jo(t,i,e.hashTable,Do.byU32,r),i+=3;return n},compressContinue:ra,saveDict:ia,createStreamDecode:oa,setStreamDecode:aa,decompressSafeContinue:ca,RingBufferEncoder:da,RingBufferDecoder:la,_hashU16:Vo,_hashU32:Ko,_TABLE_TYPE:Do},ha=268435455,pa=new Uint32Array(256);let ma=!1;function fa(e){!function(){if(!ma){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;pa[e]=t>>>0}ma=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const n=e[s]??0;t=t>>>8^(pa[255&(t^255&n)]??0)}return(4294967295^t)>>>0}var ga=/* @__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))(ga||{});const ya=268435455;class Ia{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:ua.DEFAULT_WORK_AREA,maxWorkArea:ua.DEFAULT_MAX_WORK,shrinkMode:ua.SHRINK_MODE.MANUAL};this.encoder=new ua.RingBufferEncoder(e),this.decoder=new ua.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>ya)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=ua.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>ha)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=fa(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>ya)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=fa(o);if(c!==r)throw new Error(`CRC32 checksum mismatch: expected ${r}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const va=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ca=(e,t)=>Ye(e,t).finish();class Sa{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Ti({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:[Ts],compressType:[ws],sessionId:s,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.useCustomAttachmentUpload=e.useCustomAttachmentUpload??!1}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=Si(),t=e.lookupType("easemob.pb.Provision"),n=e.lookupType("easemob.pb.MSync"),r={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[ws],encryptType:[Ts],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,auth:`$t$${this.context.token}`,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}:{}},i=Ca(t,r),o={version:0,guid:wi({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),auth:`$t$${this.context.token}`,command:jt,deviceId:0,encryptType:[Ts],payload:i,traceId:s()};return Ca(n,o)}encodeHeartbeat(){const e=Si(),t=e.lookupType("easemob.pb.CommUnreadUL"),n=e.lookupType("easemob.pb.MSync"),r=Ca(t,{}),i={version:0,encryptType:[Ts],command:Ht,payload:r,traceId:s()};return Ca(n,i)}encodeStatisticRebuild(){const e=Si(),t=e.lookupType("easemob.pb.StatisticsBody"),n=e.lookupType("easemob.pb.Meta"),r=e.lookupType("easemob.pb.CommSyncUL"),i=e.lookupType("easemob.pb.MSync"),o=Ca(t,{operation:0}),a=n.decode(new Uint8Array);a.id=Date.now(),a.ns=ys,a.payload=o;const c=r.decode(new Uint8Array);c.meta=a;const d=Ca(r,c);return Ca(i,{version:0,encryptType:[Ts],command:Vt,payload:d,traceId:s()})}decodeProvision(e){const t=Si().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},n="number"==typeof s.errorCode?s.errorCode:Rs,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===Ms,statusCode:n,reason:r,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Si().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=Si().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=Si().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 s=Si(),n=s.lookupType("easemob.pb.CommSyncDL"),r=s.lookupType("easemob.pb.MessageBody"),i=n.decode(e);t.debug("decodeSync commSyncDl",{hasMetas:Array.isArray(i.metas)});const o=Array.isArray(i.metas)?i.metas:[],a=this.decodeAck(i);a?.ok&&(a.chatRoomInfo=this.decodeChatRoomJoinInfo(o));const c=Ni(i.metaId),d=Ni(i.nextKey),l=i.queue??void 0,u="boolean"==typeof i.isLast?i.isLast:void 0,h=[],p=[];if(c&&"0"!==c){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(o,r):void 0;for(const t of o){const e=this.decodeNotifyMeta(t);e.length>0&&p.push(...e)}return{ack:a,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u,replacedMessage:e}}for(const t of o){const e=this.decodeChatMeta(t,r);e&&h.push(e);const s=this.decodeChatActionMeta(t,r);s&&p.push(s);const n=this.decodeNotifyMeta(t);n.length>0&&p.push(...n)}return{ack:a,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)!==Is)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,s){if(!e||"object"!=typeof e)return null;const n=e,r=n.payload;let i=null;if(r instanceof Uint8Array?i=r:r instanceof ArrayBuffer?i=new Uint8Array(r):ArrayBuffer.isView(r)&&(i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!i)return null;if(("number"==typeof n.ns?n.ns:void 0)!==Is)return null;try{const e=s.decode(i);if(!e||"object"!=typeof e)return null;const r=e,o="number"==typeof r.type?r.type:Qt;if(o!==Xt&&o!==es&&o!==ts&&o!==ss&&o!==Zt)return null;const a=this.readJid(n.to),c=Number(Ni(n.timestamp))||Date.now(),d=this.resolveActionConversationType(a.domain,r.meta,r),{senderId:l,receiverId:u}=this.resolveIncomingMessageParties(n,r,d),h=this.resolveActionConversationId(l,u,d);if(o===ts)return!0===r.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(o===Xt){t.debug("Received READ_ACK MessageBody",r);const e=(Array.isArray(r.ackMessageIds)?r.ackMessageIds:[]).map(e=>Ni(e)).filter(e=>Boolean(e)),s=Ni(r.ackMessageId);if(0===e.length&&s&&e.push(s),0===e.length||!h)return null;const n=Ri(Array.isArray(r.ext)?r.ext.filter(va):void 0),i=va(n.group_ack_count)?n.group_ack_count:{},o=e.flatMap(e=>{const t=i[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:o}:{}}}}if(o===Zt){const e=Ni(r.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(o===es){const e=Ni(r.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=Ni(r.editMessageId),m=(Array.isArray(r.contents)?r.contents:[])[0],f=m?this.decodeContent(m):null;if(!p||!h||!f)return null;const g=this.resolveModifiedInfo(r.meta);return{type:"message_updated",data:{messageId:p,conversationId:h,conversationType:d,timestamp:c,message:{type:f.type,body:f.body,ext:Ri(r.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!==Ss&&s!==Cs&&s!==vs&&s!==ys)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===Cs?this.decodeRosterMeta(t,r):s===vs?this.decodeMucMeta(t,r):s===ys?this.decodeStatisticGroupReceiptNotifies(t,r):this.decodeNotifyPayload(r):[]}decodeStatisticGroupReceiptNotifies(e,s){try{const n=Si(),r=n.lookupType("easemob.pb.StatisticsBody").decode(s);if("string"!=typeof r.location||0===r.location.length)return[];const i=JSON.parse(r.location);if(!va(i)||!Array.isArray(i.group_ack))return[];const o=this.readMetaTimestamp(e)??Date.now(),a=/* @__PURE__ */new Map;for(const e of i.group_ack){if(!va(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||a.set(s,{conversationId:t,count:e})}}return t.debug("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(a,([e,{conversationId:t,count:s}])=>({messageId:e,conversationId:t,count:s}))}),Array.from(a,([e,{conversationId:t,count:s}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:o,receiptDetails:[{messageId:e,count:s}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==ys)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=Si(),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=Si(),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=go({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=Si(),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=Io({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=yo({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?Bi({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}):Yi({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&&to.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 s="";for(let t=0;t<e.length;t+=1){const n=e[t];if(void 0===n)return[];s+=`%${n.toString(16)}`}const n=decodeURIComponent(s),r=JSON.parse(n);t.debug("Decoded MSync notify payload",{payload:r});const i="string"==typeof r.type?r.type:"";if(!i)return[];if("thread"===i){return[{type:i,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:va(r.data)?r.data:r}}]}if("conv"===i){const e=va(r.data)?r.data:r,t=[],s="string"==typeof e.op?e.op:"";if("pin"===s||"pin_delete"===s)return[{type:i,eventName:"onPinnedMessageChanged",data:e}];const n=vo({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 n&&t.push(this.createMultiDeviceNotify(n)),t}if("roaming_delete"===i){const e=va(r.data)?r.data:r,t=Co({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"===i){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const s=[];for(const n of e){if(!lo(n))continue;const e=uo(n.operator_resource,n.resource,n.clientResource);if(ho(e,t.clientResource))continue;const r=oo(n.group)??oo(n.user);if(!r||!lo(n.data))continue;const i=oo(n.group)?ro:no,o=n.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:r,conversationType:i,remindType:oo(o.type),silentMode:o,deviceId:e,raw:n})}return s})(va(r.data)&&Array.isArray(r.data.values)?r.data.values:Array.isArray(r.values)?r.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:i,data:r.data??r}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,s=Number(Ni(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:So(e.category),data:e}}decodeNotice(e){const t=Si().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Si().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=Si(),n=t.lookupType("easemob.pb.CommSyncUL"),r=t.lookupType("easemob.pb.MSync"),i=Ca(n,{queue:e}),o={version:0,encryptType:[Ts],command:Vt,payload:i,traceId:s()};return Ca(r,o)}encodeLastSession(e,t){const n=Si(),r=n.lookupType("easemob.pb.CommSyncUL"),i=n.lookupType("easemob.pb.MSync"),o=Ca(r,{queue:e,key:t}),a={version:0,encryptType:[Ts],command:Vt,payload:o,traceId:s()};return Ca(i,a)}encodeChatMessage(e,t){const n=Si(),r=n.lookupType("easemob.pb.MessageBody"),i=n.lookupType("easemob.pb.CommSyncUL"),o=n.lookupType("easemob.pb.MSync"),a=this.buildContent(e),c=this.resolveMessageProfileVersionFields(e),d=this.buildMessageMeta(e),l=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),u={type:this.resolveChatType(e),from:{name:this.context.userId},to:{name:l.name},contents:[a],ext:Mi(e.ext??{}),...d?{meta:d}:{},...c,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},h=Ca(r,u),p="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",m=this.resolveDirectedUsers(e),f=this.resolveMetaExt(e),g={id:t,to:wi({appKey:this.context.appKey,name:l.name,domain:p,clientResource:l.clientResource}),ns:Is,payload:h,routetype:this.resolveRouteType(e),directedUsers:m,ext:f,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}},y=Ca(i,{meta:g}),I={version:0,encryptType:[Ts],command:Vt,payload:y,traceId:s()};return Ca(o,I)}encodeActionMessage(e,n){const r=Si(),i=r.lookupType("easemob.pb.MessageBody"),o=r.lookupType("easemob.pb.CommSyncUL"),a=r.lookupType("easemob.pb.MSync"),c=r.lookupEnum("easemob.pb.MessageBody.EditScope"),d=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),l=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:n,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:d.name},contents:l,ext:Mi(e.ext??{})};"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?c.values.BODY_AND_EXT:c.values.BODY);const h=Ca(i,u);if("clearAllConversationUnreadMessageCount"===e.kind){const e=i.decode(h),s=i.fields.clearAllUnreadMessageCount;t.debug("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:n,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:n,to:wi({appKey:this.context.appKey,name:d.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:d.clientResource}),ns:Is,payload:h,routetype:Es,directedUsers:[],ext:[]},m=Ca(o,{meta:p}),f={version:0,encryptType:[Ts],command:Vt,payload:m,traceId:s()};return Ca(a,f)}encodeChatRoomOperation(e,t){const n=Si(),r=n.lookupType("easemob.pb.MUCBody"),i=n.lookupType("easemob.pb.CommSyncUL"),o=n.lookupType("easemob.pb.MSync"),a={mucId:wi({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&&(a.ext=e.ext),void 0!==e.leaveOtherRooms&&(a.leaveOtherRooms=e.leaveOtherRooms));const c=Ca(r,a),d={id:t,from:wi({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:vs,payload:c},l=Ca(i,{meta:d}),u={version:0,encryptType:[Ts],command:Vt,payload:l,traceId:s()};return Ca(o,u)}decodeServerMessageMeta(e){const t=Si(),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?vn(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(e=>{if(/^\d+$/.test(e))return e;const t=$e.fromString("1099511628211",!0);let s=$e.fromString("1469598103934665603",!0);for(let n=0;n<e.length;n+=1)s=s.xor($e.fromInt(e.charCodeAt(n),!0)).multiply(t).toUnsigned();return s.isZero()?"1":s.toString()})(e)}decodeChatRoomJoinInfo(e){const s=Si().lookupType("easemob.pb.MUCBody");for(const r of e){if(!va(r)||r.ns!==vs)continue;const e=r.payload,i=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(i)try{const e=s.decode(i);if(!va(e)||!va(e.status))continue;const t=e.status.chatroomInfo;if("string"!=typeof t||""===t)continue;const n=JSON.parse(t);if(!va(n))continue;const r=n[this.context.userId];if(!va(r))continue;const o=r;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(n){t.error("Failed to decode chat room info from ACK",n)}}}decodeAck(e){const t=Ni(e.metaId);if(!t||"0"===t)return;const s=e.status??{},n="number"==typeof s.errorCode?s.errorCode:Rs,r="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:Ni(e.serverId),ok:n===Ms,statusCode:n,reason:r}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:$t;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=Ri(t.ext),h=Ri(e.ext),p=Number(Ni(e.timestamp))||Date.now(),m=Ni(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),I=this.resolveContentReplaced(y),v=this.resolveReactions(y),C=this.resolveModifiedInfo(y),S=this.resolveChatThreadMessageContext(y),E=this.resolveChatThreadOverview(y),b=this.resolveProfileVersionTime(t.userInfoUpdateTime),A=this.resolveProfileVersionTime(t.namecardUpdateTime),T={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)};Xi(T,{userInfoUpdateTime:b,namecardUpdateTime:A});const w=this.decodeStreamMeta(t.stream,n);w&&(T.type="text",T.body={content:w.fullText},T.stream=w),void 0!==f&&(T.isBroadcast=f),void 0!==g&&(T.priority=g),void 0!==I&&(T.isContentReplaced=I),v&&(T.reactions=v),C&&(T.modifiedInfo=C),S&&(T.isChatThread=!0,T.chatThread=S);const N=this.resolvePeerRead(y,r,c);void 0!==N&&(T.isPeerRead=N);const M=this.resolveGroupReadCount(y,r);void 0!==M&&(T.groupReadCount=M),E&&(T.chatThreadOverview=E);const R=t.msgConfig;return R?.allowGroupAck&&(T.needReadReceipt=!0),T}resolveMessageProfileVersionFields(e){const t=Zi(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 ot(Ni(e))}isPublicMessageType(e){return e===$t||e===Yt||e===Jt}resolveMessageIsOnline(e,t){if(e===Jt)return!0;const s=t.is_online;return"boolean"==typeof s?s:"number"==typeof s?0!==s:"string"!=typeof s||"0"!==s}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const s=e,n=Number(Ni(s.streamSeq));if(!Number.isFinite(n))return;const r="number"==typeof s.streamStatus?s.streamStatus:ms,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?Gt.ERROR:e===hs?Gt.START:e===ps?Gt.START_COMPLETED:e===fs?Gt.COMPLETED:e===gs?Gt.FULL:Gt.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(e){if("text"===e.type){const t=e.body;return{type:ns,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:ds,action:t.action}}if("custom"===e.type){const t=e.body;return{type:ls,customEvent:t.event,customExts:Mi(t.params??{})}}if("location"===e.type){const t=e.body;return{type:os,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:rs,displayName:t.filename,remotePath:t.originalImageUrl??"",imageType:n(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:is,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:as,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:ns,subType:0,text:we(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:cs,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,thumbnailDisplayName:t.filename}}decodeContent(e){const t="number"==typeof e.type?e.type:ns,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===us||t===ns&&(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===ns)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===ds)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===ls){const t=Ri(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===os)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===rs){const t=e.size??{},s="number"==typeof t.width?t.width:0,n="number"==typeof t.height?t.height:0,a=r(e.imageType)===i,c="string"==typeof e.remotePath?e.remotePath:"",d=o(c,{deriveVariants:!this.useCustomAttachmentUpload}),l="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:a,originalImageUrl:d.originalImageUrl,bigImageUrl:d.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:l??d.thumbnailUrl}}}if(t===is){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===as){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===cs){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}resolveChatType(e){switch(e.conversationType){case"groupChat":return Yt;case"chatRoom":return Jt;default:return $t}}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=this.readJid(t.from),o=this.readJid(t.to),a=i.name??n.name??"",c=o.name??r.name??"";if(!("singleChat"===s&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:n.clientResource&&n.clientResource!==this.context.clientResource?`${a}/${n.clientResource}`:a,receiverId:r.clientResource?`${c}/${r.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return ts;case"sendMessageReadReceipts":return Xt;case"deliveryAck":return Zt;case"recall":return es;case"update":return ss;default:return $t}}resolveConversationType(e){return e===Yt?"groupChat":e===Jt?"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?Mi({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?As:this.resolveDeliverOnlineOnly(e)?bs:Es}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"}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(!va(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(!va(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(!va(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(!va(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=va(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.context.userId?"SEND":"RECEIVE";return{msgServerId:s,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:h,conversationType:"groupChat",type:l,sendStatus:"sent",ext:va(r?.ext)?r.ext:{},timestamp:n,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(va(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=o(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:va(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(Cn(t));return va(e)?e:null}catch{return null}}if(va(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return va(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(va).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}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[Ns]}configureCompression(e,t){if(!e||!e.includes(Ns))return void this.disableCompression();this.compressor||(this.compressor=new Ia);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===ga.UPLINK_ONLY||s===ga.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===ga.DOWNLINK_ONLY||s===ga.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?ga.UPLINK_ONLY:1===e?ga.DOWNLINK_ONLY:2===e?ga.BIDIRECTIONAL:ga.NONE}disableCompression(){this.compressor&&(this.compressor.mode=ga.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}class Ea{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.reconnectInProgress=!1,this.reconnectPaused=!1,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.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:c,autoReconnectNumMax:10,connectTimeout:a,...e},this.eventHub=t,this.msyncCodec=new Sa({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 gi({maxAttempts:this.config.autoReconnectNumMax,initialDelay:u,maxDelay:l,backoffMultiplier:d}),this.heartbeatManager=new vi({interval:this.config.heartBeatWait,timeout:h}),this.connectionEventNormalizer=new Sn,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[Ne.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(s,n){const r=Date.now();if(n<=r)throw new p("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=s,this.connection.token=s,this.msyncCodec.updateToken(s),this.setupTokenLifecycle(s,n,r),t.warn("Connection token renewed",{userId:this.config.userId,expireAt:n}),{token:s,expireAt:n}}handleOnline(){t.warn("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0;const e=this.offlineRecoverPending?Me.OFFLINE_RECOVER:Me.ONLINE;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){t.warn("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.stopHeartbeat(),this.closeWebSocket(Me.OFFLINE,!0),t.warn("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void t.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(Me.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Me.HEARTBEAT_FAILED)}}catch(s){if(t.warn("Foreground heartbeat check failed",s),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(Me.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Me.HEARTBEAT_FAILED)}}resumeReconnect(e){this.isLoggedIn&&(this.reconnectInProgress?t.warn("Reconnect recovery skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.connection.status===be.CONNECTED&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),t.warn("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===Me.SEND_TIMEOUT&&t.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,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId}}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 p))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(Cn(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null)}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay();t.warn("Reconnect retry scheduled",{delayMs:Math.round(e),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise(t=>{this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,t()},e)})}buildConnectionEventPayload(e,t){const s=this.connection.error instanceof p?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,s,n,r=!1){const i=this.connection.status!==e;(i||r)&&(i&&(this.connection.status=e,this.connection.lastConnectedAt=e===be.CONNECTED?Date.now():void 0),n&&this.dispatchConnectionEvent(e,s),t.debug("Connection status updated",{status:e,reason:s,attempt:this.reconnectAttempts,forceEmit:r}))}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 s=JSON.parse(e);if(!s||"object"!=typeof s)return void t.warn("Provision auth token has invalid payload");const n=Number(s.expires_in);if(!Number.isFinite(n))return void t.warn("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,n)}catch(s){t.warn("Failed to parse provision auth token expiration",s)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,t.warn("Token will expire"),this.eventHub.dispatch(Ae.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,t.warn("Token expired"),this.eventHub.dispatch(Ae.TOKEN_EXPIRED,void 0))}isTokenExpiredConnectionError(t){return t instanceof p&&t.code===e.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(s){t.warn("Connection closing because token expired",{source:s}),this.connection.error=new p("Token expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:s,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(Me.TOKEN_EXPIRED,!0,!0),this.updateStatus(be.DISCONNECTED,Me.TOKEN_EXPIRED,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(Me.HEARTBEAT_FAILED)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,h)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(){if(!this.reconnectInProgress)if(this.connection.status!==be.CONNECTED&&this.connection.status!==be.CONNECTING){this.isLoginPhase=!0,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(Me.LOGIN,!0),this.isLoggedIn=!0}catch(e){throw this.isLoggedIn=!1,e}finally{this.isLoginPhase=!1}}else t.warn("Connection already established or connecting")}async connectWithRetry(s,n){if(t.warn("Reconnect flow requested",{reason:s,throwOnFailure:n,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void t.warn("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:s,...this.getReconnectDiagnostic()});if(this.connection.status===be.CONNECTED&&this.websocket)return;if(this.reconnectPaused)return void t.warn("Reconnect flow skipped",{guard:"reconnect-paused",reason:s,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let r=null,i=null;const o=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),t.warn("Reconnect flow started",{reason:s,throwOnFailure:n,maxAttempts:o,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<o;){this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const e=this.isLoginPhase?be.CONNECTING:be.RECONNECTING;t.warn("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:o,reason:s,nextStatus:e,...this.getReconnectDiagnostic()}),this.updateStatus(e,s,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(s)}catch(a){if(r=a,t.warn("Connection attempt failed",{attempt:this.reconnectAttempts,reason:s,error:r}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(r))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(r)){i=r;break}}if(this.connectionRetry.getAttemptCount()>=o)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){t.warn("Reconnect retry loop interrupted",{reason:s,attempt:this.reconnectAttempts,maxAttempts:o,...this.getReconnectDiagnostic()});break}await this.waitForReconnectDelay()}if(i){if(this.connection.error=i,n)throw this.updateStatus(be.DISCONNECTED,Me.ERROR,!1),i;return this.reconnectPaused=!0,void this.updateStatus(be.DISCONNECTED,Me.ERROR,!0)}if(n)throw this.updateStatus(be.DISCONNECTED,Me.ERROR,!1),r??new p("Connection failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,t.warn("Reconnect attempts exhausted",{reason:s,attempt:this.reconnectAttempts,maxAttempts:o,lastError:r,...this.getReconnectDiagnostic()}),this.updateStatus(be.RECONNECT_FAILED,Me.LIMIT,!0)}finally{this.reconnectInProgress=!1,t.warn("Reconnect flow finished",{reason:s,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(Me.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),t.warn("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}async triggerReconnect(e){t.warn("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.isLoggedIn?this.reconnectInProgress?t.warn("Reconnect trigger skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.reconnectPaused?t.warn("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}):(this.connection.status===be.CONNECTED&&this.websocket&&this.closeWebSocket(e,!0,!0),await this.connectWithRetry(e,!1)):t.warn("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()})}handleDisconnection(e){t.warn("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(be.DISCONNECTED,e,!0),e!==Me.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(){return new Promise((s,n)=>{const r=this.pickNextServerUrl();t.debug("WebSocket connecting",{url:r}),this.clearSocketListeners();let i=!1;const o=setTimeout(()=>{i=!0,t.warn("WebSocket connection attempt timed out",{url:r,connectTimeout:this.config.connectTimeout,...this.getReconnectDiagnostic()}),n(new p("Connection timeout",{code:e.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},this.config.connectTimeout);this.socketAdapter.connect({url:r,timeoutMs:this.config.connectTimeout}).then(e=>{if(clearTimeout(o),i||this.reconnectPaused)return t.warn("WebSocket connection result discarded",{url:r,cancelled:i,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void e.close();this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),this.startProvision().then(()=>{if(this.resetProvisionHandlers(),i||this.reconnectPaused)return t.warn("Provision result discarded",{url:r,cancelled:i,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void this.closeWebSocket(Me.ERROR,!1,!1);s()}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(Me.ERROR,!1,!1),n(e instanceof Error?e:new Error(String(e)))})}).catch(t=>{if(clearTimeout(o),i)return;const s=t instanceof p?t:new p("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});this.handleConnectionError(s,Me.ERROR),n(s)})}).catch(t=>{if(t instanceof p)throw t;const s=new p("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});throw this.handleConnectionError(s,Me.ERROR),s})}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(t.warn("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(Me.CLOSE))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new p("Provision interrupted",{code:e.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,s){if(t.error("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),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,s){if(t.warn("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,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,s,!0,!0)}async handleWebSocketMessage(s,n){try{if(n!==this.socketGeneration)return;t.debug("WebSocket message received",{dataType:typeof s});const i=await this.msyncCodec.normalizeIncoming(s);if(n!==this.socketGeneration)return;if(t.debug("handleWebSocketMessage data",{length:i.length}),!i.length)return;const o=this.msyncCodec.decompressIncoming(i);if(!o){const s=null!==this.provisionReject;return t.error("Failed to decompress mSync payload, closing connection",{stage:s?"provision":"connected"}),void(s?(this.rejectPendingProvision(new p("Failed to decompress Provision payload",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(Me.ERROR,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(o))return void t.debug("Ignore server normal close payload",{length:o.length});let a=null;try{a=this.msyncCodec.decodeMsync(o)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void t.warn("Discard invalid mSync payload",{length:o.length,message:e.message,prefixHex:Array.from(o.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(o.subarray(Math.max(0,o.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw t.warn("Invalid mSync payload signature",{length:o.length,prefixHex:Array.from(o.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),t.debug("handleWebSocketMessage decoded",{command:a.command}),a.command){case jt:this.handleProvisionMessage(a.payload);break;case Wt:this.handleLogoutMessage(a.payload);break;case zt:this.handleNoticeMessage(a.payload);break;case Ht:this.handleUnreadMessage(a.payload);break;case Vt:this.handleSyncMessage(a.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");t.error("Failed to handle mSync payload",e),this.handleConnectionError(e,Me.ERROR)}}startProvision(){this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(new p("Provision timeout",{code:e.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},m);try{const e=this.msyncCodec.encodeProvision();t.debug("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new p("Provision send failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(s){const n=this.msyncCodec.decodeProvision(s);if(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),n.ok)this.msyncCodec.updateResource(n.resource),this.setupTokenLifecycleFromProvision(n.authToken),this.provisionResolve?.();else{t.warn("Provision rejected",{statusCode:n.statusCode,reason:n.reason});const s=yn(n.statusCode,n.reason),r=s.code===e.UNKNOWN?e.CONNECTION_PROVISION_REJECTED:s.code;this.provisionReject?.(new p("Provision rejected",{code:r,details:{stage:"provision",reason:n.reason,statusCode:n.statusCode,retryable:s.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:s}=this.msyncCodec.decodeUnread(e),n=s.filter(e=>this.getQueueId(e));if(n.length){n.length!==s.length&&t.warn("Unread queues without usable identity were ignored",{ignoredCount:s.length-n.length}),this.startOfflineMessageSync(n);for(const e of n)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 s=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(s)return void this.handleTerminalConnectionError(s,Me.ERROR);if(!this.messageReceiver)return;const n=this.messageReceiver.handleSyncPayload(e);if(t.debug("handleSyncMessage result",{result:n}),!n)return;(void 0!==n.queue||void 0!==n.nextKey||void 0!==n.isLast)&&this.handleSyncQueueState(n)}handleSyncQueueState(e){t.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 s=this.resolveSyncQueueState(e);if(!s)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:n,queueId:r}=s;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(r)){const t=this.offlineMessageQueueCounts.get(r)??0;this.offlineMessageQueueCounts.set(r,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const i=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(r),this.removeQueueEntry(n),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(i){if(i!==this.nextKey||!this.isSameQueue(n,this.currentQueue))return this.nextKey=i,this.currentQueueId=r,this.currentQueue=n,void this.sendLastSession(n,i);this.removeQueueEntry(n),this.sendNextQueue()}}resolveSyncQueueState(e){const s=e.queue&&"object"==typeof e.queue?e.queue:void 0,n=s?this.getQueueName(s):null,r=s?this.getQueueId(s):null,i=void 0!==s&&null!==r&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,s)));if(s&&r&&i)return{queue:s,queueId:r};const o=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,a=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,c=o??a??this.queues[0],d=c?this.getQueueName(c):null,l=c?this.getQueueId(c):null;return c&&l?(t.warn("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:n,responseQueueId:r,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 s=this.msyncCodec.decodeLogout(e);t.warn("Logout message received",s)}resolveStatisticDisconnectError(t){for(const s of t)switch(s.operation){case 1:return new p("User has been removed",{code:e.USER_REMOVED,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 2:return new p("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 p("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 p("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.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.offlineRecoverPending=!1,this.closeWebSocket(Me.CLOSE,!0,!0),this.updateStatus(be.DISCONNECTED,Me.CLOSE,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),t.warn("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){if(e.socketAdapter)return e.socketAdapter;const t=ir({webSocketCtor:"function"==typeof WebSocket?WebSocket:void 0});if(t)return t;throw Ge("Socket capability is missing for current platform",{code:"PLATFORM_MISSING_CAPABILITY",stage:"socket",retryable:!1,details:{capability:"socket"}})}attachSocketListeners(s,n){this.clearSocketListeners(),this.socketDisposers=[s.onMessage(e=>{this.websocket===s&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(e,n)))}),s.onError(()=>{if(this.websocket!==s)return;t.warn("WebSocket error",{stage:"ws"});const n=new p("WebSocket connection error",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(n,Me.ERROR)}),s.onClose(e=>{this.websocket===s&&this.handleWebSocketClose(e)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===He.OPEN)try{const s=this.msyncCodec.prepareOutgoing(e);t.debug("WebSocket send payload",{length:s.length}),Promise.resolve(this.websocket.send(s)).catch(e=>{t.error("Failed to send mSync payload",e),this.websocket?.close()})}catch(s){t.error("Failed to send mSync payload",s),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const s=this.msyncCodec.encodeBackQueue(e);t.debug("sendBackqueue payload",{length:s.length}),this.sendMsyncPayload(s)}sendLastSession(e,s){t.debug("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:s});const n=this.msyncCodec.encodeLastSession(e,s);this.sendMsyncPayload(n)}sendNextQueue(){t.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=f({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(Ae.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(Ae.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 ba=new Uint8Array([99,109]),Aa=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ta=e=>Array.isArray(e)&&e.every(Aa),wa=e=>"string"==typeof e?e:void 0,Na=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Ma=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},Ra=(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 y("Combine payload length header is invalid",{code:e.COMBINE_PARSE_FAILED});return n<<24|r<<16|i<<8|o},_a=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},Ua=(e,t)=>{const s=Si().lookupType(e).decode(t);if(!Aa(s))throw new Error(`${e} decoded result is invalid`);return s},Da=e=>Aa(e)&&"string"==typeof e.name?e.name:"",La=(e,t,s)=>{const n=(Ta(e.contents)?e.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const a=(e=>{const t=Na(e.type)??ns,s=Boolean(wa(e.remotePath))||Boolean(wa(e.title))||Boolean(wa(e.summary))||(Na(e.combineLevel)??0)>0,n=t===ns&&0===e.subType&&s;if(t===us||n){const t=Na(e.combineLevel)??0;return{type:"combine",body:{title:wa(e.title)??"",summary:wa(e.summary)??"",filename:wa(e.displayName)??"combine",filetype:"application/octet-stream",url:wa(e.remotePath),secret:wa(e.secretKey),fileLength:Na(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ns)return{type:"text",body:{content:wa(e.text)??""}};if(t===ds)return{type:"cmd",body:{action:wa(e.action)??""}};if(t===ls){const t=Ri(Ta(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:wa(e.customEvent)??"",params:t}}}if(t===os)return{type:"location",body:{latitude:Na(e.latitude)??0,longitude:Na(e.longitude)??0,address:wa(e.address),buildingName:wa(e.buildingName)}};if(t===rs){const t=Aa(e.size)?e.size:{},s=wa(e.remotePath)??"",n=o(s),a=wa(e.thumbnailRemotePath),c=r(e.imageType)===i;return{type:"image",body:{localUrl:"",filename:wa(e.displayName)??"image",filetype:"application/octet-stream",width:Na(t.width)??0,height:Na(t.height)??0,isGif:1===e.subType,isOriginalImage:c,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:wa(e.secretKey),fileLength:Na(e.fileLength),thumbnailUrl:a??n.thumbnailUrl}}}if(t===is){const t=Aa(e.size)?e.size:{};return{type:"video",body:{url:wa(e.remotePath)??"",filename:wa(e.displayName)??"video",filetype:"application/octet-stream",duration:Na(e.duration)??0,width:Na(t.width),height:Na(t.height),secret:wa(e.secretKey),fileLength:Na(e.fileLength),thumbnailUrl:wa(e.thumbnailRemotePath)}}}if(t===as)return{type:"voice",body:{url:wa(e.remotePath)??"",filename:wa(e.displayName)??"voice",filetype:"application/octet-stream",duration:Na(e.duration)??0,secret:wa(e.secretKey),fileLength:Na(e.fileLength)}};if(t===cs)return{type:"file",body:{url:wa(e.remotePath)??"",filename:wa(e.displayName)??"file",filetype:"application/octet-stream",secret:wa(e.secretKey),fileLength:Na(e.fileLength)}};return null})(n);if(!a)throw new Error("MessageBody content type is unsupported");const c=Da(e.from)||Da(s?.from)||`unknown-${t}`,d=Da(e.to)||Da(s?.to)||`unknown-${t}`,l=(u=e.type)===Yt?"groupChat":u===Jt?"chatRoom":"singleChat";var u;const h=d||c,p=Number(Ni(s?.timestamp))||Date.now(),m=Ri(Ta(e.ext)?e.ext:void 0),f={msgServerId:Ni(s?.id),msgLocalId:"",type:a.type,sender:{userId:c},conversationId:h,conversationType:l,timestamp:p,body:a.body,ext:m};return"number"==typeof a.combineLevel&&(f.body.combineLevel=a.combineLevel),f},Oa=(e,t)=>{const s=[];try{const r=Ua("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=Ua("easemob.pb.MessageBody",i);return La(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=Ua("easemob.pb.MessageBody",e);return La(s,t)}catch(r){s.push(r instanceof Error?r.message:String(r))}try{const s=Ua("easemob.pb.MessageBody.Content",e);return La({type:$t,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("; "))},ka=(t,s)=>{const n=Cn(t);try{const t=JSON.parse(n);if(!Aa(t))throw new y("Combine payload item is invalid",{code:e.COMBINE_PARSE_FAILED,details:{index:s}});return t}catch(r){if(r instanceof y)throw r;try{return Oa(t,s)}catch(i){throw new y("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)}})}}},Pa=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class xa{constructor(e,t,s,n){this.websocket=null,this.pendingMessages=/* @__PURE__ */new Map,this.ackTimeout=I,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(s,n){const r=this.msyncCodec.toProtocolId(s.msgLocalId);if(Kt(s))throw new g("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:s.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==He.OPEN){const t=this.msyncCodec.toProtocolId(s.msgLocalId);throw new g("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:s.msgLocalId,protocolId:t,retryable:!0}})}let i={...s,sendStatus:"sending"};eo(s,i),t.debug("Message send queued",{msgLocalId:s.msgLocalId,protocolId:r,type:s.type,conversationType:s.conversationType,conversationId:s.conversationId});try{const e="combine"===i.type?this.prepareCombineMessage(i):i,t={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,n):e,sendStatus:"sending"};eo(i,t),i=t,n?.onSending?.(t);const s=await this.doSendMessage(t);return n?.onSuccess?.(s),s}catch(o){const e={...i,sendStatus:"failed"};throw eo(i,e),n?.onFailed?.(e,o instanceof Error?o:new Error(String(o))),o}}async sendAction(e,s){const n=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&t.debug("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:n,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const r=this.msyncCodec.encodeActionMessage(e,n);"clearAllConversationUnreadMessageCount"===e.kind&&t.debug("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:n,payloadBytes:r.byteLength});const i="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(n,r,s,this.createPendingDataReport({category:"message",operationName:i,operationType:"MESSAGE",requestName:i,msgId:e.messageId,messageType:Pa(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(s){const n=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:s.msgLocalId,messageType:Pa(s.conversationType)});return new Promise((r,i)=>{const o=this.msyncCodec.toProtocolId(s.msgLocalId),a=setTimeout(()=>{this.pendingMessages.delete(o),this.finishPendingDataReport(n,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),i(new g("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:s.msgLocalId,protocolId:o,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(o,{kind:"message",message:s,protocolId:o,timeoutId:a,resolve:e=>{clearTimeout(a),r(e)},reject:e=>{clearTimeout(a),i(e)},report:n});try{if(!this.websocket||this.websocket.readyState!==He.OPEN)throw new g("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:s.msgLocalId,protocolId:o,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(s,o),c=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(c)).catch(r=>{const c=r instanceof Error?r.message:String(r);this.pendingMessages.delete(o),clearTimeout(a),this.finishPendingDataReport(n,{code:-1,success:!1,description:c}),t.warn("Message send socket failure",{msgLocalId:s.msgLocalId,protocolId:o,websocketReadyState:this.websocket?.readyState??null,cause:c}),i(new g(`WebSocket send failed: ${c}`,{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:s.msgLocalId,protocolId:o,retryable:!0,cause:c}}))}),t.debug("Message sent",{msgLocalId:s.msgLocalId,protocolId:o})}catch(c){if(this.pendingMessages.delete(o),clearTimeout(a),this.finishPendingDataReport(n,{code:c instanceof g?c.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:c instanceof Error?c.message:String(c)}),c instanceof g)throw c;throw new g("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{msgLocalId:s.msgLocalId,protocolId:o,retryable:!0}})}})}async sendProtocolPayload(t,s,n,r){return new Promise((i,o)=>{const a=setTimeout(()=>{this.pendingMessages.delete(t),this.finishPendingDataReport(r,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),o(new g("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{protocolId:t,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(t,{kind:"action",protocolId:t,timeoutId:a,createAckError:n,resolve:i,reject:o,report:r});try{if(!this.websocket||this.websocket.readyState!==He.OPEN)throw new g("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(a),this.finishPendingDataReport(r,{code:-1,success:!1,description:n}),o(new g(`WebSocket action send failed: ${n}`,{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0,cause:n}}))})}catch(c){if(this.pendingMessages.delete(t),clearTimeout(a),this.finishPendingDataReport(r,{code:c instanceof g?c.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:c instanceof Error?c.message:String(c)}),c instanceof g)throw c;o(new g("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{protocolId:t,retryable:!1}}))}})}prepareCombineMessage(t){const s=t.body,n=s.messageList??[];Re(n);const r=_e(n);Ue(r);const i=(t=>{try{const s=t.map((t,s)=>{const n=JSON.stringify(t);if(!n)throw new g("Combine payload item encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{index:s}});return vn(n)}),n=ba.length+s.reduce((e,t)=>e+4+t.length,0)+1,r=new Uint8Array(n);let i=0;r.set(ba,i),i+=ba.length;for(const e of s){const t=Ma(e.length);r.set(t,i),i+=t.length,r.set(e,i),i+=e.length}const o=_a(r.subarray(0,r.length-1));return r[r.length-1]=o,r}catch(s){if(s instanceof g)throw s;throw new g("Combine payload encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{cause:s instanceof Error?s.message:String(s)}})}})(n),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=De(a);if(!c&&!this.attachmentUploader)throw new g("Combine payload local url generation failed",{code:e.COMBINE_ENCODE_FAILED});Le.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 eo(t,d),Oe(t,d),d}handleAck(e,s,n,r){const i=this.pendingMessages.get(e);if(!i)return void t.debug("Received ACK without a tracked pending message",{protocolId:e});if("action"===i.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(i.report,{code:200,success:!0}),void i.resolve({protocolId:e,serverId:s??"",statusCode:0,chatRoomInfo:r});const o={...i.message,...this.resolveReplacedMessage(i.message,n),sendStatus:"sent",msgServerId:s||n?.msgServerId||i.message.msgServerId};eo(i.message,o),this.pendingMessages.delete(e),this.finishPendingDataReport(i.report,{code:200,success:!0}),"image"!==o.type&&"video"!==o.type&&"voice"!==o.type&&"file"!==o.type&&"combine"!==o.type||Le.delete(o.msgLocalId),t.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(Ne.MESSAGE_SENT,o),i.resolve(o)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,s){const n=this.pendingMessages.get(e);if(!n)return;if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:s instanceof g?s.code:-1,success:!1,description:s.message}),void n.reject(s);const r={...n.message,sendStatus:"failed"};eo(n.message,r),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:s instanceof g?s.code:-1,success:!1,description:s.message}),t.warn("Message send failed after ACK/error",{protocolId:e,msgLocalId:r.msgLocalId,type:r.type,conversationType:r.conversationType,conversationId:r.conversationId,error:s.message}),n.reject(s)}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 g("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)>=v){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(t.warn("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const s=f({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(s)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:s,request:s.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<v&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<v&&(this.chatRoomReportSaturated=!1)))}}class Fa{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!==Gt.START&&t.stream.status!==Gt.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 Ba{constructor(e,t){this.completedIds=/* @__PURE__ */new Set,this.eventHub=e,this.cache=t??new Fa}handle(e){const s=this.resolveMessageId(e);if(!s)return void t.warn("stream message id missing, skip dispatch");if(this.completedIds.has(s))return void t.debug("stream message already completed, ignore",{msgId:s});if(e.stream.status===Gt.FULL)return void this.handleFullChunk(s,e);const n=this.cache.get(s);if(n?.completed)return void t.debug("stream session completed, ignore chunk",{msgId:s,seq:e.stream.seq});const{duplicate:r}=this.cache.addChunk(s,e);r?t.debug("stream duplicate chunk ignored",{msgId:s,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(s,e):this.dispatchSequentialChunks(s)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const s=this.cache.getSequentialChunks(e);if(0!==s.length)for(const t of s){const s=this.cache.get(e);if(!s)return;const n=s.fullText,r=t.stream.deltaText,i=`${n}${r}`,o=t.stream.errorType>0?Gt.ERROR:t.stream.status,a=this.buildDispatchMessage(t,{status:o,fullText:i,deltaText:r});if(this.eventHub.dispatch(Ze.STREAM_MESSAGE,a),this.cache.markDispatched(e,t,i),o===Gt.START_COMPLETED||o===Gt.COMPLETED||o===Gt.ERROR){const t=o===Gt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else t.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?Gt.ERROR:o?Gt.START_COMPLETED:Gt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:r,deltaText:i});this.eventHub.dispatch(Ze.STREAM_MESSAGE,c);const d=a===Gt.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:Gt.ERROR,fullText:r,deltaText:i});this.eventHub.dispatch(Ze.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 qa{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 Ga=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Ka{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new Ba(s),this.messageContexts=/* @__PURE__ */new Map,this.recentMessageIds=new qa(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{t.debug("handleSyncPayload payload",{length:e.length});const s=this.msyncCodec.decodeSync(e);t.debug("handleSyncPayload result",{ack:Boolean(s.ack),messageCount:s.messages.length});const{ack:n,messages:r}=s;s.notifies&&s.notifies.length>0&&this.handleNotifies(s.notifies),n&&(t.debug("Decoded sync ACK",{ok:n.ok,protocolId:n.protocolId,serverId:n.serverId??null,statusCode:n.statusCode??null,reason:n.reason??null,hasReplacedMessage:Boolean(s.replacedMessage)}),this.handleAck(n,s.replacedMessage));for(const e of r)this.dispatchMessage(e);return s}catch(s){t.error("Failed to decode sync payload",s)}return null}handleAck(s,n){if(s.ok)return t.debug("ACK accepted",{protocolId:s.protocolId,serverId:s.serverId??null,hasReplacedMessage:Boolean(n)}),void(s.chatRoomInfo?this.messageSender.handleAck(s.protocolId,s.serverId,n,s.chatRoomInfo):this.messageSender.handleAck(s.protocolId,s.serverId,n));t.warn("ACK rejected",{protocolId:s.protocolId,statusCode:s.statusCode,reason:s.reason,hasReplacedMessage:Boolean(n)});const r=((t,s)=>{const n=yn(t,s),r=n.code===e.UNKNOWN?e.MESSAGE_SEND_FAILED:n.code;return{code:r,message:In[r]??(s?`Message send failed: ${s}`:"Message send failed for an unknown reason"),retryable:n.retryable}})(s.statusCode,s.reason),i=new g(r.message,{code:r.code,details:{protocolId:s.protocolId,serverCode:s.statusCode,reason:s.reason,retryable:!1}});this.messageSender.handleAckFailure(s.protocolId,s.statusCode,s.reason,i)}dispatchMessage(e){if(Kt(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const s=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(s)?t.debug("Duplicate message ignored",{messageId:s}):(this.eventHub.dispatch(Ze.MESSAGE,e),t.debug("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const s=this.msyncCodec.getContext().userId;s&&e.from!==s&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{t.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(Ze.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(Ne.USER_INFO_NOTIFY,a)}handleContactNotify(e){if(t.debug("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==et.INVITED&&e.eventName!==et.DELETED&&e.eventName!==et.ADDED&&e.eventName!==et.REFUSE&&e.eventName!==et.AGREED)return;const s=e.data;if(!s||"object"!=typeof s)return;const n=s;"string"==typeof n.from&&n.from&&"string"==typeof n.to&&n.to&&"string"==typeof n.message&&this.eventHub.dispatch(e.eventName,n)}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(tt.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(Ne.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(Ne.CHATROOM_NOTIFY,s)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const s of t){if(!Ga(s)||"string"!=typeof s.messageId)continue;const e=this.resolveReactionConversationContext(s);e&&this.eventHub.dispatch(Ze.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(!Ga(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(Ze.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(!Ga(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(!Ga(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(!Ga(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(!Ga(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(Ze.MESSAGE_DELIVERED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!Ga(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(Ze.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(!Ga(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Ga(t.message)||"string"!=typeof t.message.type||!Ga(t.message.body)||!Ga(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Ga(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(Ze.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(Ne.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)Ga(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)!Ga(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 Va=e=>e instanceof Error?e.message:String(e);class Ha{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Xn({fetchImpl:fetch}):void 0))(e)}async downloadAndParse(t){const n=t.url.trim();if(!n)throw new C("Combine message url is required",{code:e.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof t.maxItems?t.maxItems:ke;Pe(1,r);const i=this.requestAdapter;if(!i)throw new y("Request adapter is required for combine message download",{code:e.COMBINE_DOWNLOAD_FAILED});const o=S(n,t.secret);try{const n=await i.request({url:o,method:"GET",responseType:"arraybuffer",timeoutMs:t.timeoutMs??15e3,headers:{[E]:s()}});if(401===n.status||403===n.status)throw new b(401===n.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===n.status?e.AUTH_UNAUTHORIZED:e.AUTH_FORBIDDEN,details:{url:o,httpStatus:n.status}});if(n.status>=400)throw new y("Combine payload download failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{status:n.status,url:o}});const a=(t=>{if(t.length<ba.length+1)throw new y("Combine payload is too short",{code:e.COMBINE_PARSE_FAILED});const s=t.subarray(0,ba.length);if(s[0]!==ba[0]||s[1]!==ba[1])throw new y("Combine payload header is invalid",{code:e.COMBINE_PARSE_FAILED});const n=t.subarray(0,t.length-1),r=_a(n),i=t[t.length-1]??0;if(i!==r)throw new y("Combine payload checksum failed",{code:e.COMBINE_PARSE_FAILED,details:{expectedChecksum:r,actualChecksum:i}});const o=[];let a=ba.length;const c=t.length-1;for(;a<c;){if(a+4>c)throw new y("Combine payload length header is incomplete",{code:e.COMBINE_PARSE_FAILED});const s=Ra(t,a);if(a+=4,s<=0||a+s>c)throw new y("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=ka(n,o.length);o.push(r)}if(a!==c)throw new y("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 vn(t);throw new y("Combine payload response type is invalid",{code:e.COMBINE_DOWNLOAD_FAILED})})(n.data));return Pe(a.length,r),Re(a),a.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(a){if(a instanceof C||a instanceof b||a instanceof y)throw a;throw new y("Combine payload download or parse failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{cause:Va(a),url:o}})}}}const za=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"}},ja=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 Wa{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Xn({fetchImpl:fetch}):void 0))(e)}async download(t,n=15e3){if("image"!==t.type&&"video"!==t.type&&"voice"!==t.type&&"file"!==t.type)throw new C("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:r,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(!r)throw new C("attachment url is required",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});if(!this.requestAdapter)throw new A("request adapter is required for attachment download");const o=await this.requestAdapter.request({url:S(r,i),method:"GET",responseType:"arraybuffer",timeoutMs:n,headers:{[E]:s()}});if(401===o.status)throw new b("attachment download unauthorized",{code:e.AUTH_UNAUTHORIZED,details:{url:r,httpStatus:o.status}});if(403===o.status)throw new b("attachment download forbidden",{code:e.AUTH_FORBIDDEN,details:{url:r,httpStatus:o.status}});if(404===o.status){const t=("string"==typeof o.data?o.data:"").includes("expired");throw new T(t?"attachment file is expired":"attachment not found",t?e.ATTACHMENT_EXPIRED:e.ATTACHMENT_NOT_FOUND)}if(429===o.status)throw new T("attachment download rate limited",e.SERVICE_LIMIT_EXCEEDED);if(o.status>=400)throw new T("attachment download failed",e.FILE_DOWNLOAD_FAILED,{details:{status:o.status,url:r}});return{filename:za(t),mimeType:ja(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:r}}}const Qa=(e,t,n)=>({Authorization:`Bearer ${e}`,Accept:t,[E]:s(),...n??{}}),$a=async s=>{const n=Qa(s.token,"application/json",s.headers),r=Date.now(),i="upload.multipart.init"===s.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===s.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",o=s.dataReportOperation?.startRequest({requestName:i,method:s.method,url:s.url});let a=0;if(t.debug("Upload request start",{operation:s.operation,method:s.method}),s.requestAdapter)try{const i=await s.requestAdapter.request({url:s.url,method:s.method,headers:n,responseType:"json",timeoutMs:L});a=i.status;const d=Date.now()-r;if(i.status<200||i.status>=300)throw t.warn("Upload response error",{operation:s.operation,method:s.method,status:i.status,duration:d}),new N("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:i.status}});t.debug("Upload response success",{operation:s.operation,method:s.method,status:i.status,duration:d});const l="string"==typeof(c=i.data)?JSON.parse(c):c;return o?.finish({code:i.status,success:!0}),l}catch(u){if(o?.finish({code:0!==a?a:u instanceof N?u.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:u instanceof Error?u.message:String(u)}),u instanceof N)throw u;throw t.warn("Upload request failed",{operation:s.operation,method:s.method}),new N("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url}})}var c;const d=new AbortController,l=setTimeout(()=>d.abort(),L);try{const i=await fetch(s.url,{method:s.method,headers:n,signal:d.signal});a=i.status;const c=Date.now()-r;if(!i.ok)throw t.warn("Upload response error",{operation:s.operation,method:s.method,status:i.status,duration:c}),new N("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:i.status}});return t.debug("Upload response success",{operation:s.operation,method:s.method,status:i.status,duration:c}),o?.finish({code:i.status,success:!0}),await i.json()}catch(u){if(o?.finish({code:0!==a?a:u instanceof N?u.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:u instanceof Error?u.message:String(u)}),u instanceof N)throw u;if(u instanceof Error&&"AbortError"===u.name)throw t.warn("Upload request timeout",{operation:s.operation,method:s.method,timeout:L}),new N("Upload timeout",{code:e.UPLOAD_TIMEOUT,details:{url:s.url,timeout:L}});throw t.warn("Upload request failed",{operation:s.operation,method:s.method}),new N("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url}})}finally{clearTimeout(l)}},Ya=(s,n,r,i,o,a)=>new Promise((c,d)=>{const l=new XMLHttpRequest,u=Date.now(),h=a?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:s});t.debug("Upload part start",{operation:"upload.multipart.part",partNumber:r}),l.upload&&o&&l.upload.addEventListener("progress",e=>{o(e.loaded)},!1),l.addEventListener("abort",()=>{h?.finish({code:e.UPLOAD_ABORTED,success:!1,description:"Upload aborted"}),t.warn("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),d(new N("Upload aborted",{code:e.UPLOAD_ABORTED,details:{url:s,partNumber:r}}))},!1),l.addEventListener("error",()=>{h?.finish({code:e.UPLOAD_REQUEST_FAILED,success:!1,description:"Upload part failed"}),t.warn("Upload part failed",{operation:"upload.multipart.part",partNumber:r}),d(new N("Upload part failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s,partNumber:r}}))},!1),l.addEventListener("timeout",()=>{h?.finish({code:e.UPLOAD_TIMEOUT,success:!1,description:"Upload timeout"}),t.warn("Upload part timeout",{operation:"upload.multipart.part",partNumber:r,timeout:L}),d(new N("Upload timeout",{code:e.UPLOAD_TIMEOUT,details:{url:s,partNumber:r}}))},!1),l.addEventListener("load",()=>{const n=Date.now()-u;if(200!==l.status)return h?.finish({code:l.status,success:!1,description:"Upload part failed"}),t.warn("Upload part error",{operation:"upload.multipart.part",partNumber:r,status:l.status,duration:n}),void d(new N("Upload part failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s,partNumber:r,status:l.status}}));t.debug("Upload part success",{operation:"upload.multipart.part",partNumber:r,duration:n}),h?.finish({code:l.status,success:!0}),c()},!1);const p=new FormData;p.append("part_file",i),p.append("part_number",r),l.timeout=L,l.open("PUT",s),Object.entries(Qa(n,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{l.setRequestHeader(e,t)}),l.send(p)}),Ja=async t=>{if(t.fileSize<=w)throw new N("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,{orgName:m,appName:f}=M(s.appKey),g=`${s.restBaseUrl}/${m}/${f}/sdk/chatfiles/part-upload`;let y;try{y=await $a({url:g,method:"POST",token:s.token,operation:"upload.multipart.init",requestAdapter:s.requestAdapter,dataReportOperation:t.dataReportOperation})}catch(F){throw new N("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:F,url:g}})}const I=(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:O,i="string"==typeof s?.uuid?s.uuid:"";if(!i)throw new N("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{fileMaxSize:n,partMinSize:r,uuid:i}})(y);if(I.fileMaxSize&&c>I.fileMaxSize)throw new N("File size exceeds limit",{code:e.UPLOAD_SIZE_EXCEEDED,details:{fileSize:c,maxSize:I.fileMaxSize}});const v=I.partMinSize||O,C=Math.ceil(c/v),S=Array.from({length:C},()=>0),E=`${s.restBaseUrl}/${m}/${f}/sdk/chatfiles/part-upload/${I.uuid}`,b=[],A=(e,s)=>{S[e]=s;const n=S.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<C;e+=1){const r=e*v,i=Math.min(c,r+v),o=n.slice(r,i),a=String(e+1),d=Ya(E,s.token,a,o,t=>A(e,t),t.dataReportOperation).finally(()=>{const e=b.indexOf(d);e>=0&&b.splice(e,1)});b.push(d),b.length>=R&&await Promise.race(b)}await Promise.all(b);const T=k(i),L=_(`${s.restBaseUrl}/${m}/${f}/sdk/chatfiles/part-upload/${I.uuid}`,{"restrict-access":"true","chat-type":T,"chat-target":r,"thumbnail-width":t.thumbnailWidth,"thumbnail-height":t.thumbnailHeight,md5:u??"",..."image"===d?{imageType:U(l),width:h,height:p}:{}}),P=await $a({url:L,method:"POST",token:s.token,operation:"upload.multipart.complete",requestAdapter:s.requestAdapter,dataReportOperation:t.dataReportOperation}),x=D({response:P,restBaseUrl:s.restBaseUrl,orgName:m,appName:f,fileType:a,fileName:o,fallbackSize:c,messageType:d,imageType:l,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(x),x},Xa=n=>new Promise((r,i)=>{const{config:o,file:a,conversationId:c,conversationType:d,messageType:l,imageType:u,md5:h,width:p,height:m,fileName:f,fileType:g,fileSize:y}=n,{orgName:I,appName:v}=M(o.appKey),C=k(d),S=_(`${o.restBaseUrl}/${I}/${v}/chatfiles`,{"chat-type":C,"chat-target":c,md5:h??"",..."image"===l?{imageType:U(u),width:p,height:m}:{}}),b=Date.now(),A=n.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:S});t.debug("Upload request start",{operation:"upload.simple",method:"POST",fileSize:y,messageType:l});const T=new XMLHttpRequest;T.upload&&n.callbacks?.onFileUploadProgress&&T.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void n.callbacks?.onFileUploadProgress?.({loaded:e.loaded});const t=e.total?e.loaded/e.total*100:void 0;n.callbacks?.onFileUploadProgress?.({loaded:e.loaded,total:e.total,percent:t})},!1),T.addEventListener("abort",()=>{A?.finish({code:e.UPLOAD_ABORTED,success:!1,description:"Upload canceled"}),t.warn("Upload request aborted",{operation:"upload.simple"}),n.callbacks?.onFileUploadCanceled?.(),i(new N("Upload canceled",{code:e.UPLOAD_ABORTED,details:{url:S}}))},!1),T.addEventListener("error",()=>{A?.finish({code:e.UPLOAD_REQUEST_FAILED,success:!1,description:"Upload failed"}),t.warn("Upload request failed",{operation:"upload.simple"}),i(new N("Upload failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:S}}))},!1),T.addEventListener("timeout",()=>{A?.finish({code:e.UPLOAD_TIMEOUT,success:!1,description:"Upload timeout"}),t.warn("Upload request timeout",{operation:"upload.simple",timeout:L}),i(new N("Upload timeout",{code:e.UPLOAD_TIMEOUT,details:{url:S,timeout:L}}))},!1),T.addEventListener("load",()=>{try{const s=Date.now()-b,i=JSON.parse(T.responseText);if(T.status>=400)throw A?.finish({code:T.status,success:!1,description:"Upload failed"}),t.warn("Upload response error",{operation:"upload.simple",status:T.status,duration:s}),new N("Upload failed",{code:e.UPLOAD_REQUEST_FAILED,details:{status:T.status,response:i}});t.debug("Upload response success",{operation:"upload.simple",status:T.status,duration:s});const a=D({response:i,restBaseUrl:o.restBaseUrl,orgName:I,appName:v,fileType:g,fileName:f,fallbackSize:y,messageType:l,imageType:u,useCustomAttachmentUpload:o.useCustomAttachmentUpload});n.callbacks?.onFileUploadComplete?.(a),A?.finish({code:T.status||200,success:!0}),r(a)}catch(s){A?.finish({code:s instanceof N?s.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:s instanceof Error?s.message:String(s)}),i(s instanceof Error?s:new Error(String(s)))}},!1),T.timeout=L,T.open("POST",S),T.setRequestHeader("restrict-access","true"),T.setRequestHeader("Accept","*/*"),T.setRequestHeader("Authorization",`Bearer ${o.token}`),T.setRequestHeader(E,s());const w=new FormData;w.append("file",a,f),void 0!==n.thumbnailWidth&&w.append("thumbnail-width",String(n.thumbnailWidth)),void 0!==n.thumbnailHeight&&w.append("thumbnail-height",String(n.thumbnailHeight)),T.send(w)}),Za=Tr(),ec=e=>Object.prototype.toString.call(e),tc=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:ec(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}},sc=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}),nc=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,rc=e=>"object"==typeof e&&null!==e,ic=(e,t)=>{const s=rc(t)?t:void 0,n=s?.code===Ke.MISSING_CAPABILITY&&s.stage===Ve.RUNTIME;return"miniapp-path"===e&&(e=>{if(!rc(e))return!1;const t=rc(e.details)?e.details:void 0;return e.code===Ke.MISSING_CAPABILITY&&e.stage===Ve.RUNTIME&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&n};class oc{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(s,n){if(!nc(s.type))return s;const r=s.body;if(this.hasUploadedRemoteResource(s.type,r))return s;const i=this.resolveUploadUrl(s.type,r),o=Le.get(s.msgLocalId),a=Boolean(o);if(t.warn("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:s.msgLocalId,messageType:s.type,conversationType:s.conversationType,hasFile:a,uploadUrl:i,cachedFile:tc(o),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}}),!P(i,a))return s;if(!o)throw new N("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:s.msgLocalId,url:i}});if(!this.config?.restBaseUrl)throw new N("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(s,r,o),c.precheck?.hit||(l=f({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:s.msgLocalId,messageType:s.type})),d=c.precheck?.hit?this.buildPrecheckedUploadResult(s,c,n):await this.uploadAttachment(s,c,n,l),l?.finish({code:0,success:!0})}catch(u){const t=ze(u);throw l?.finish({code:t.code,success:!1,description:t.message}),t.code===e.UPLOAD_ABORTED&&n?.onFileUploadCanceled?.(),n?.onFileUploadError?.(t),t}return this.buildPreparedMessage(s,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&&x(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&x(t.url)}async prepareAttachmentUpload(e,s,n){const r=F(n,s);if(t.warn("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:sc(r)}),"image"!==e.type){return{body:s,fileInfo:r,md5FileInfo:r,precheck:await this.maybePrecheck(e,r,r,void 0)}}const o=s,a=await this.resolveImageCandidate(o,r),c={...o,width:a.width,height:a.height,isOriginalImage:a.imagePolicy.resolvedImageType===i},d=await this.maybePrecheck(e,a.fileInfo,r,a.imagePolicy.resolvedImageType);return{body:c,fileInfo:a.fileInfo,md5FileInfo:r,imageType:a.imagePolicy.resolvedImageType,precheck:d,originalWidth:o.width,originalHeight:o.height}}async resolveImageCandidate(e,s){const n=B(e);if(t.warn("Image send policy resolved",{operation:"upload.image.policy",reason:n.reason,imageType:n.resolvedImageType,isGif:e.isGif,source:sc(s)}),n.resolvedImageType===i){let r=e.width,i=e.height;if(!r||!i){const e=this.resolveImageProcessor(s.source.sourceType);t.warn("Image original info resolving",{operation:"upload.image.info",processorSourceType:s.source.sourceType,source:sc(s)});const n=await e.getImageInfo(s.source);r=n.width,i=n.height}return{imagePolicy:n,sourceKind:"origin",fileInfo:s,width:r,height:i}}try{const e=this.resolveImageProcessor(s.source.sourceType);t.warn("Image big generation start",{operation:"upload.image.big.start",processorSourceType:s.source.sourceType,source:sc(s)});const r=await e.generateBigImage(s.source,{maxShortEdge:720,quality:.85});return{imagePolicy:n,sourceKind:"big",fileInfo:{source:r.source,fileName:r.fileName??s.fileName,fileType:r.fileType??s.fileType,fileSize:r.fileSize??s.fileSize,webFile:r.webFile},width:r.width,height:r.height}}catch(r){return t.warn("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:n.reason,error:r instanceof Error?r.message:String(r),source:sc(s)}),{imagePolicy:{resolvedImageType:i,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:s,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,s,n,r){if(!nc(e.type))return;if(!0!==this.config?.enableMd5Check)return void t.debug("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:r,fileSize:s.fileSize});const i=q({messageType:e.type,fileSize:s.fileSize,imageType:r});if(!i.shouldPrecheck)return void t.debug("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:r,fileSize:s.fileSize,thresholdBytes:i.thresholdBytes});let o;try{o=await this.computeMd5(n)}catch(c){if(ic(n.source.sourceType,c))return void t.warn("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:r,thresholdType:i.thresholdType,source:sc(n),error:c instanceof Error?c.message:String(c)});throw c}const a=await this.requestPrecheck(e,i.thresholdType,o,r);return t.debug(a.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:a.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:r,exists:a.exists,existsType:a.existsType,uuid:a.uuid,hasShareSecret:"string"==typeof a.shareSecret&&a.shareSecret.length>0}),{...a,md5:o}}async computeMd5(e){const s=this.resolveImageProcessor(e.source.sourceType);return t.warn("Attachment md5 compute start",{operation:"upload.md5.start",source:sc(e)}),s.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return t.warn("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return t.warn("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Za;throw t.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),Ge("Image processor capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(s,n,r,i){if(!this.config)throw new N("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:o,appName:a}=M(this.config.appKey),c=_(`${this.config.restBaseUrl}/${o}/${a}/chatfiles/exists`,{md5:r,..."image"===s.type?{imageType:U(i)}:{}}),d=await this.requestJson({url:c,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(e=>{t.warn("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:s.type,imageType:i,thresholdType:n,md5:r,error:e instanceof Error?e.message:String(e)})});return d?G(d):{exists:!1,hit:!1}}async requestJson(e){return this.config?.requestAdapter?this.requestByAdapter(this.config.requestAdapter,e):this.requestByFetch(e)}async requestByAdapter(t,s){const n=await t.request({url:s.url,method:s.method,headers:s.headers,responseType:"json",timeoutMs:L});if(n.status>=400)throw new N("Upload precheck request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:n.status,operation:s.operation}});return n.data}async requestByFetch(t){if("function"!=typeof fetch)throw Ge("Request capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.REQUEST,retryable:!1,details:{operation:t.operation}});const s=new AbortController,n=setTimeout(()=>s.abort(),L);try{const n=await fetch(t.url,{method:t.method,headers:t.headers,signal:s.signal});if(!n.ok)throw new N("Upload precheck request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:n.status,operation:t.operation}});return await n.json()}finally{clearTimeout(n)}}buildPrecheckedUploadResult(t,s,n){if(!this.config||!s.precheck)throw new N("Precheck result is required",{code:e.UPLOAD_REQUEST_FAILED});if(!s.precheck.uuid)throw new N("Precheck hit missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{precheck:s.precheck}});if(!nc(t.type))throw new N("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const{orgName:r,appName:o}=M(this.config.appKey),a="image"===t.type?s.precheck.existsType??s.imageType:void 0,c="image"===t.type&&a===i?s.md5FileInfo:s.fileInfo,d="image"===t.type&&a===i?s.originalWidth:"image"===t.type?s.body.width:void 0,l="image"===t.type&&a===i?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=D({response:u,restBaseUrl:this.config.restBaseUrl,orgName:r,appName:o,fileType:c.fileType,fileName:c.fileName,fallbackSize:c.fileSize,messageType:t.type,imageType:a,width:d,height:l,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(h),h}async uploadAttachment(s,n,r,i){if(!this.config)throw new N("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});if(!nc(s.type))throw new N("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:s.type}});const o=s.type,a=await this.resolveUploadMetadata(o,n);if(this.config.uploadAdapter)return t.warn("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:o,source:sc(n.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,s,n,a,r);if(!n.fileInfo.webFile)throw new N("Upload adapter is required for non-web file source",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:n.fileInfo.source.sourceType}});const c={message:s,file:n.fileInfo.webFile,conversationId:s.conversationId,conversationType:s.conversationType,messageType:o,imageType:n.imageType,md5:a.md5,width:a.width,height:a.height,fileName:n.fileInfo.fileName,fileType:n.fileInfo.fileType,fileSize:n.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(o,n.body),thumbnailHeight:this.resolveThumbnailHeight(o,n.body),callbacks:r,config:this.config,dataReportOperation:i},d=!1!==this.config?.enableMultipartUpload,l=d&&n.fileInfo.fileSize>w;if(t.warn("Attachment web upload selected",{operation:"upload.web.selected",messageType:o,source:sc(n.fileInfo),multipartEnabled:d,uploadMode:l?"multipart":"simple"}),l)try{return await Ja(c)}catch(u){const e=u instanceof N?u.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return Xa(c);throw u}return Xa(c)}async uploadByAdapter(n,r,i,o,a){if(!this.config)throw new N("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:c,appName:d}=M(this.config.appKey),l=k(r.conversationType);if(!nc(r.type))throw new N("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:r.type}});const u=r.type,h=_(`${this.config.restBaseUrl}/${c}/${d}/chatfiles`,{"chat-type":l,"chat-target":r.conversationId,md5:o.md5,..."image"===u?{imageType:U(i.imageType),width:o.width,height:o.height}:{}}),p={},m={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[E]:s()},f=this.resolveThumbnailWidth(u,i.body),g=this.resolveThumbnailHeight(u,i.body);void 0!==f&&(p["thumbnail-width"]=String(f)),void 0!==g&&(p["thumbnail-height"]=String(g)),t.warn("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:u,source:sc(i.fileInfo),uploadUrl:h,fields:p});const y=await n.upload({url:h,headers:m,source:i.fileInfo.source,fields:p,onProgress:e=>{a?.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 N("Upload failed",{code:s,details:{status:y.status,response:y.body}})}let I;try{I=JSON.parse(y.body)}catch(C){throw new N("Upload response parse failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:y.body,cause:C instanceof Error?C.message:String(C)}})}const v=D({response:I,restBaseUrl:this.config.restBaseUrl,orgName:c,appName:d,fileType:i.fileInfo.fileType,fileName:i.fileInfo.fileName,fallbackSize:i.fileInfo.fileSize,messageType:u,imageType:i.imageType,width:o.width,height:o.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return a?.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 eo(e,r),Oe(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 eo(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 eo(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 eo(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 eo(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,s){let n=s.precheck?.md5??"";if(!s.precheck)try{n=await this.computeMd5(s.md5FileInfo)}catch(i){if(!ic(s.md5FileInfo.source.sourceType,i))throw i;t.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:sc(s.md5FileInfo),error:i instanceof Error?i.message:String(i)})}const r=s.body;return{md5:n,width:"image"===e&&"number"==typeof r.width&&r.width>0?r.width:void 0,height:"image"===e&&"number"==typeof r.height&&r.height>0?r.height:void 0}}}class ac{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 cc="__internal:core";class dc{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 Ea({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),n=e.restBaseUrl?new oc({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 xa(s,null,this.eventHub,n),this.messageReceiver=new Ka(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Ha(e.platformAdapter?.request),this.attachmentDownloader=new Wa(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(cc,{[Ae.CONNECTED]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[Ae.DISCONNECTED]:e=>{this.messageSender.setWebSocket(null)},[Ae.RECONNECT_FAILED]:e=>{this.messageSender.setWebSocket(null)},[Ne.MESSAGE_SENT]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new ac(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(){return this.connectionManager.connect()}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}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(cc),Le.clear()}}const 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=atob(e),s=new Uint8Array(new ArrayBuffer(t.length));for(let n=0;n<t.length;n+=1)s[n]=t.charCodeAt(n);return s};class hc{getCrypto(){return Te().crypto}constructor(e,t){if(this.enabled=(()=>{const e=Te();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 t=Un(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==qe.ELECTRON_RENDERER)return!1;const s=e.crypto;return void 0!==s&&void 0!==s.subtle&&"function"==typeof s.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const s=`${e}:${t}`;this.keyPromise=this.deriveKey(s)}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",Sc="joinedGroupPreview",Ec="metadata",bc=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Ac{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 Tc=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=Te().localStorage;return t&&"function"==typeof t.getItem?t:null};class wc{constructor(e){this.available=wc.checkAvailable(),this.cryptoAdapter=e??null}static checkAvailable(){const e=Tc();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,s){if(!this.available)return s;const n=Tc();if(!n)return s;try{const t=n.getItem(e);if(!t)return s;let r=t;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(t);if(null===e)return s;r=e}return dt(r,s)}catch(r){return t.warn("CacheStore read failed",r),s}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,s,n){if(!this.available)return;const r=lt(s);if(null===r){if(n)throw new TypeError("CacheStore value cannot be serialized");return}const i=Tc();if(i)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(r):r;i.setItem(e,t)}catch(o){if(ut(o))throw o;if(n)throw o;t.warn("CacheStore write failed",o)}}remove(e){if(!this.available)return;const s=Tc();if(s)try{s.removeItem(e)}catch(n){t.warn("CacheStore remove failed",n)}}}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(!ht(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 ht(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 ht(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}},Uc=(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}},Dc=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 Lc{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=Uc(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:Dc(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(!ht(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=ht(e.body)?e.body:{},i="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,o="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:s,body:r,timestamp:n,userInfoUpdateTime:i,namecardUpdateTime:o}:null}}const Oc=(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(Oc(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,n){const r=Oc(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(Oc(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=Oc(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(Oc(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=>Oc(e.groupId,e.userId)));this.items.clear();for(const a of n)o.has(Oc(a.groupId,a.userId))||this.items.set(Oc(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=Uc(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>Oc(e.groupId,e.userId)));this.items.clear();for(const o of s)i.has(Oc(o.groupId,o.userId))||this.items.set(Oc(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||!ht(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=>{const t={...e};return delete t.type,t},Fc=e=>{if(!ht(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!ht(e.body))return null;const s=((e,t)=>{if(ht(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),r=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),i=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),o=(e=>{if(ht(e)&&"string"==typeof e.operatorId&&"number"==typeof e.operationCount&&"number"==typeof e.operationTime)return{operatorId:e.operatorId,operationCount:e.operationCount,operationTime:e.operationTime}})(e.modifiedInfo),a="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,c="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return{msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:s,body:xc(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...n?{conversationType:n}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...r?{sendStatus:r}:{},...i?{direct:i}:{},...o?{modifiedInfo:o}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Bc=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},qc=(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 Gc{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(qc)}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(qc)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!ht(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:Fc(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:Bc(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=Uc(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(!ht(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 Vc=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Hc=e=>e.lastMessageAt??e.updatedAt,zc=e=>[...e].sort((e,t)=>{const s=Vc(t)-Vc(e);if(0!==s)return s;const n=Hc(t)-Hc(e);return 0!==n?n:e.conversationId.localeCompare(t.conversationId)}),jc=e=>`${e.conversationType}:${e.conversationId}`,Wc=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Qc=(e,t)=>((e,t)=>Hc(t)>Hc(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Wc(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,$c=e=>{const t=/* @__PURE__ */new Map,s=/* @__PURE__ */new Set;for(const i of e.snapshot)s.add(jc(i));for(const i of e.existing)t.set(jc(i),i);const n=e.snapshot.map(e=>{const s=t.get(jc(e));return s?Qc(e,s):e}),r=e.existing.filter(t=>!s.has(jc(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return zc([...n,...r])},Yc=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Jc=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Xc=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 Zc{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,Yc.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 ed=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class td{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);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=bc(s,pc),this.userInfoKey=bc(s,mc),this.groupNamecardKey=bc(s,fc),this.sessionListKey=bc(s,vc),this.sessionListCheckpointKey=bc(s,Cc),this.joinedGroupPreviewKey=bc(s,Sc),this.contactRelationKey=bc(s,gc),this.contactVersionKey=bc(s,yc),this.contactMetaKey=bc(s,Ic),this.metadataKey=bc(s,Ec),this.metadataStore=new Ac(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Lc,this.userInfoCache=new Kc,this.groupNamecardCache=new kc,this.sessionListCache=new Gc,this.joinedGroupPreviewCache=new nt,this.contactCache=new Rc,this.userInfoRuntimeStore=new Zc,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 nt;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=$c({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?Jc(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Xc(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})}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=jc(e.nextRecord),s=e.existing.filter(e=>jc(e)!==t);return zc([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&&ht(r)&&Array.isArray(r.items)?r.items:[];this.sessionListCache.load(i,e);const o=(r&&ht(r)&&ht(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&&ht(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&ht(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(s){if(!ut(s))return this.restoreDirtyBatch(e),void t.warn("Cache flush failed",s);const n=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,n),"none"===n)return this.restoreDirtyBatch(e),void t.warn("Cache flush failed: no cache entry can be evicted",s)}t.warn("Cache flush failed after quota cleanup attempts"),this.restoreDirtyBatch(e)}finally{}}async writeDirtyDomains(e){for(const t of ed)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),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=>Vc(e)>0),s=/* @__PURE__ */new Map;for(const r of e.incoming)s.set(jc(r),r);const n=t.length>0?e.existing.filter(e=>!s.has(jc(e))&&0===Vc(e)):e.existing.filter(e=>!s.has(jc(e)));return zc([...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($c({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=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",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=Zi(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{msgId:e.msgServerId||e.msgLocalId,type:e.type,body:this.normalizeMessageBody(e.body),timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return e&&"object"==typeof e&&!Array.isArray(e)?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="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,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?{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}: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?Jc(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=t?`${t.msgServerId}:${t.from}:${t.to}:${t.conversationId}:${t.conversationType}:${t.type}:${t.sendStatus??""}:${t.direct??""}:${t.sender.userId}:${t.sender.nickname??""}:${t.sender.avatarUrl??""}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",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 sd{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,s,n){try{const r=n(s);return this.isPromiseLike(r)?Promise.resolve(r).then(()=>{}).catch(s=>{t.error(`Event handler error for ${e}`,s)}):null}catch(r){return t.error(`Event handler error for ${e}`,r),null}}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const nd={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function rd(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 id(e){return new Promise(t=>setTimeout(t,e))}const od=e=>{const t={...e};return delete t.type,t},ad=(e,t)=>{const s=e.lastMessage;if(!s)return null;const n=((e,t)=>{const s=t.getCurrentUserId?.()??"",n="singleChat"===e.type?e.conversationId:"";return{from:n,to:"singleChat"===e.type?s:e.conversationId,sender:{userId:n}}})(e,t);return{msgServerId:s.msgId,from:n.from,to:n.to,sender:n.sender,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof s.type&&s.type.length>0?s.type:"text",timestamp:s.timestamp,body:od(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},cd=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,l as s,e as n,t as r,j as i,I as o,d as a,k as c,H as d,o as l,q as u,r as h,u as p,C as m,P as f,v as g,M as y,w as I,x as v,D as C,V as S,a as E,b,A,N as T,S as w,y as N,U as M,p as R,z as _,B as U,F as D,G as O,J as L,K as k,L as P,O as x,Q as F,T as B,W as q,X as G,Y as K,Z as V,_ as H,$ as z,a0 as j,a1 as W,a2 as Q,a3 as $,a4 as Y,a5 as J,f as X,h as Z,a6 as ee,a7 as te,a8 as se,a9 as ne,aa as re,ab as ie,ac as oe,ad as ae,ae as ce,af as de,ag as le,ah as ue,ai as he,aj as pe,ak as me,al as fe,am as ge,an as ye,ao as Ie,m as ve,i as Ce}from"./chunks/common-BW2KLpvb.js";import{R as Se,ap as Ee,aq as be}from"./chunks/common-BW2KLpvb.js";import{a as Ae,b as Te,g as we,I as Ne,c as Me,v as Re,d as _e,e as Ue,f as De,h as Oe,i as Le,M as ke,j as Pe,k as xe,V as Fe}from"./chunks/chat-manager-DdAnJpcH.js";import{C as Be}from"./chunks/chat-manager-DdAnJpcH.js";import{R as qe,c as Ge,P as Ke,a as Ve,S as He,m as ze}from"./chunks/group-user-info-resolver-Diqjmjyj.js";import{i as je,a as We,l as Qe,L as $e,e as Ye,b as Je}from"./chunks/reflection-proto-codec-64ocOTHU.js";import{G as Xe,C as Ze,a as et,P as tt}from"./chunks/event-system-D6IJA0C4.js";import{n as st,J as nt}from"./chunks/index-VEUtqiDw.js";import{G as rt,a as it}from"./chunks/index-VEUtqiDw.js";import{n as ot}from"./chunks/profile-version-DLMz8lqW.js";import{a as at,t as ct}from"./chunks/session-list-query-DtoToipt.js";import{s as dt,a as lt,i as ut}from"./chunks/cache-utils-B99glc0H.js";import{z as ht}from"zod";import{c as pt}from"./chunks/query-params-Bu3Xq4b6.js";import{r as mt,R as ft}from"./chunks/index-DKksD5YM.js";import{C as gt}from"./chunks/index-DKksD5YM.js";import{ChatThread as yt,ChatThreadManager as It}from"./managers/chat-thread/index.js";import{ChatRoom as vt,ChatRoomManager as Ct}from"./managers/chatroom/index.js";import{PresenceManager as St}from"./managers/presence/index.js";import{PushManager as Et}from"./managers/push/index.js";import{UserInfoManager as bt}from"./managers/user-info/index.js";const At="onChatRoomDestroyed",Tt="onMembersJoined",wt="onMembersExited",Nt="onRemovedFromChatRoom",Mt="onMuteListAdded",Rt="onMuteListRemoved",_t="onAllowListAdded",Ut="onAllowListRemoved",Dt="onAllMemberMuteStateChanged",Ot="onAdminAdded",Lt="onAdminRemoved",kt="onOwnerChanged",Pt="onAnnouncementChanged",xt="onChatRoomInfoChanged",Ft="onAttributesUpdate",Bt="onAttributesRemoved",qt={ORIGINAL:"original",LARGE:"large"},Gt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function Kt(e){return"object"==typeof e.stream&&null!==e.stream}const Vt=0,Ht=1,zt=2,jt=3,Wt=4,Qt=0,$t=1,Yt=2,Jt=3,Xt=4,Zt=5,es=6,ts=7,ss=8,ns=0,rs=1,is=2,os=3,as=4,cs=5,ds=6,ls=7,us=8,hs=0,ps=1,ms=2,fs=3,gs=4,ys=0,Is=1,vs=2,Cs=3,Ss=5,Es=0,bs=1,As=2,Ts=0,ws=0,Ns=2,Ms=0,Rs=1,_s=2,Us=3,Ds=4,Os=5,Ls=6,ks=7,Ps=8,xs=9,Fs=10,Bs=11,qs=12,Gs=13,Ks=14,Vs=15,Hs=16,zs=17,js=18,Ws=19,Qs=20,$s=1,Ys=2,Js=3,Xs=4,Zs=5,en=6,tn=7,sn=8,nn="Sorry, user register limit",rn="Sorry, user register rate limit",on="Sorry, token expired",an="Sorry, token or password does not match login info",cn="Sorry, user not found",dn="Sorry, the app month live count limit",ln="Sorry, the app day live count limit",un="Sorry, the app online count limit",hn={[Rs]:e.AUTH_UNAUTHORIZED,[_s]:e.AUTH_UNAUTHORIZED,[Us]:e.VALIDATION_REQUIRED,[Ds]:e.VALIDATION_INVALID_FORMAT,[Os]:e.CONNECTION_WEBSOCKET_ERROR,[Ls]:e.AUTH_TOKEN_EXPIRED,[ks]:e.AUTH_FORBIDDEN,[Ws]:e.AUTH_FORBIDDEN,[Ps]:e.CONNECTION_WEBSOCKET_ERROR,[xs]:e.UNKNOWN,[Fs]:e.UNKNOWN,[Bs]:e.AUTH_BIND_ANOTHER_DEVICE,[qs]:e.AUTH_FORBIDDEN,[Gs]:e.AUTH_LOGIN_TOO_MANY_DEVICES,[Ks]:e.SERVICE_LIMIT_EXCEEDED,[Vs]:e.AUTH_USER_MUTED,[Hs]:e.UNKNOWN,[zs]:e.UNKNOWN,[js]:e.MESSAGE_DECODE_FAILED,[Qs]:e.USER_DEVICE_CHANGED},pn=/* @__PURE__ */new Set([Rs,_s,Us,Ds,Ls,ks,Ws,xs,Fs,Bs,qs,Gs,Ks,Vs,Hs,zs,js,Qs]),mn={[nn]:e.SERVICE_LIMIT_EXCEEDED,[rn]:e.SERVICE_LIMIT_EXCEEDED,[on]:e.AUTH_TOKEN_EXPIRED,[an]:e.AUTH_UNAUTHORIZED,[cn]: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},fn=[["limit directed users",e.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.AUTH_FORBIDDEN]],gn={[dn]:e.SERVICE_LIMIT_EXCEEDED,[ln]:e.SERVICE_LIMIT_EXCEEDED,[un]: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},yn=(t,s)=>{if("number"!=typeof t)return{code:e.UNKNOWN,retryable:!0};const n=((t,s)=>{if(s){if(t===Rs){const t=mn[s];if(void 0!==t)return t;for(const[e,n]of fn)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===ks?gn[s]:t===Ws?e.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===Vs?e.AUTH_USER_MUTED:void 0}})(t,s),r=hn[t]??e.UNKNOWN;return{code:n??r,retryable:!pn.has(t)}},In={[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"},vn=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)},Cn=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 Sn{constructor(){this.lastEventKey=null}normalize(e,t){const s=(e=>{switch(e){case Ae.CONNECTING:case Ae.RECONNECTING:return Te.CONNECTING;case Ae.CONNECTED:return Te.CONNECTED;case Ae.DISCONNECTED:return Te.DISCONNECTED;case Ae.RECONNECT_FAILED:return Te.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 En={web:qe.WEB,"mp-weixin":qe.WECHAT_MINIAPP,"mp-alipay":qe.ALIPAY_MINIAPP,"mp-baidu":qe.BAIDU_MINIAPP,"mp-toutiao":qe.TOUTIAO_MINIAPP,"mp-lark":qe.LARK_MINIAPP,"mp-qq":qe.QQ_MINIAPP,"mp-kuaishou":qe.KUAISHOU_MINIAPP,"mp-jd":qe.JD_MINIAPP,"mp-360":qe.MINIAPP_360,"mp-harmony":qe.HARMONY_MINIAPP,"quickapp-webview":qe.QUICKAPP,"quickapp-webview-union":qe.QUICKAPP,"quickapp-webview-huawei":qe.QUICKAPP},bn=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},An=e=>(e=>bn(e,"canIUse")&&bn(e,"getSystemInfo"))(e)||(e=>bn(e,"request")&&bn(e,"connectSocket"))(e),Tn=e=>bn(e,"request")&&bn(e,"connectSocket")&&bn(e,"uploadFile"),wn=(e,t)=>t===qe.WECHAT_MINIAPP?e.wx:t===qe.QQ_MINIAPP?e.qq:t===qe.TOUTIAO_MINIAPP?e.tt:t===qe.BAIDU_MINIAPP?e.swan:t===qe.ALIPAY_MINIAPP?e.my:t===qe.DINGTALK_MINIAPP?e.dd:t===qe.JD_MINIAPP?e.jd:t===qe.KUAISHOU_MINIAPP?e.ks:t===qe.UNIAPP?e.uni:void 0,Nn=e=>{const t=e?.miniGlobal;return An(t)?t:e},Mn=e=>{const t=Nn(e);return Tn(t)?t:void 0},Rn=e=>void 0!==e.window&&void 0!==e.document,_n=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),Un=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(An(t))return!0;try{if(!bn(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},Dn=e=>Tn(e.wx)?qe.WECHAT_MINIAPP:Tn(e.my)?qe.ALIPAY_MINIAPP:Tn(e.dd)?qe.DINGTALK_MINIAPP:Tn(e.swan)?qe.BAIDU_MINIAPP:Tn(e.tt)?qe.TOUTIAO_MINIAPP:Tn(e.qq)?qe.QQ_MINIAPP:Tn(e.jd)?qe.JD_MINIAPP:Tn(e.ks)?qe.KUAISHOU_MINIAPP:void 0,On=e=>void 0!==Dn(e),Ln=e=>{const t=Dn(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;if("string"==typeof s)return En[s]??qe.UNIAPP}catch{return qe.UNIAPP}return Rn(e)?qe.WEB:qe.UNIAPP},kn=(e,t)=>{const s=Mn(wn(e,t));if(s)return s;const n=Mn(e.uni);return n||(e.uni??e)},Pn=(e,s)=>{const n=e??t();if(s){const e=s===qe.UNIAPP||Un(n),t=e?Ln(n):s;return{platform:s,hostPlatform:t,framework:e?"uniapp":Rn(n)?"web":"native",global:e?kn(n,t):Nn(wn(n,s))??n}}if(Un(n)){const e=Ln(n);return{platform:qe.UNIAPP,hostPlatform:e,framework:"uniapp",global:kn(n,e)}}return An(n.swan)?{platform:qe.BAIDU_MINIAPP,hostPlatform:qe.BAIDU_MINIAPP,framework:"native",global:Nn(n.swan)??n.swan}:An(n.tt)?{platform:qe.TOUTIAO_MINIAPP,hostPlatform:qe.TOUTIAO_MINIAPP,framework:"native",global:Nn(n.tt)??n.tt}:An(n.dd)?{platform:qe.DINGTALK_MINIAPP,hostPlatform:qe.DINGTALK_MINIAPP,framework:"native",global:Nn(n.dd)??n.dd}:An(n.my)?{platform:qe.ALIPAY_MINIAPP,hostPlatform:qe.ALIPAY_MINIAPP,framework:"native",global:Nn(n.my)??n.my}:An(n.wx)?{platform:qe.WECHAT_MINIAPP,hostPlatform:qe.WECHAT_MINIAPP,framework:"native",global:Nn(n.wx)??n.wx}:An(n.qq)?{platform:qe.QQ_MINIAPP,hostPlatform:qe.QQ_MINIAPP,framework:"native",global:Nn(n.qq)??n.qq}:An(n.jd)?{platform:qe.JD_MINIAPP,hostPlatform:qe.JD_MINIAPP,framework:"native",global:Nn(n.jd)??n.jd}:An(n.ks)?{platform:qe.KUAISHOU_MINIAPP,hostPlatform:qe.KUAISHOU_MINIAPP,framework:"native",global:Nn(n.ks)??n.ks}:(e=>"ReactNative"===e.navigator?.product)(n)?{platform:qe.REACT_NATIVE,hostPlatform:qe.REACT_NATIVE,framework:"react-native",global:n}:(e=>"string"==typeof e.process?.versions?.electron)(n)?{platform:Rn(n)?qe.ELECTRON_RENDERER:qe.ELECTRON_MAIN,hostPlatform:Rn(n)?qe.ELECTRON_RENDERER:qe.ELECTRON_MAIN,framework:"electron",global:n}:_n(n)||Rn(n)?{platform:qe.WEB,hostPlatform:qe.WEB,framework:_n(n)?"worker":"web",global:n}:{platform:qe.UNKNOWN,hostPlatform:qe.UNKNOWN,framework:"native",global:n}},xn=e=>e===qe.WECHAT_MINIAPP||e===qe.QQ_MINIAPP||e===qe.TOUTIAO_MINIAPP||e===qe.BAIDU_MINIAPP||e===qe.ALIPAY_MINIAPP||e===qe.DINGTALK_MINIAPP||e===qe.LARK_MINIAPP||e===qe.KUAISHOU_MINIAPP||e===qe.JD_MINIAPP||e===qe.MINIAPP_360||e===qe.HARMONY_MINIAPP||e===qe.QUICKAPP||e===qe.UNIAPP,Fn=["request","upload","socket","proto"],Bn=(e,t=Fn)=>{const s=((e,t=Fn)=>t.filter(t=>!e[t]))(e,t);if(0!==s.length)throw Ge("Platform missing required capabilities.",{code:Ke.MISSING_CAPABILITY,stage:Ve.INIT,retryable:!1,details:{required:[...t],missing:s}})},qn={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}}}}}}}}}},Gn=e=>{if(!e||0===e.trim().length)throw Ge("Proto type name is required.",{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:e}})};class Kn{constructor(){this.codecMap=/* @__PURE__ */new Map}register(e,t){Gn(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:s=>{const n=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw Ge("Proto payload must be an object.",{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(s,e),r=t.fromObject(n);return t.encode(r).finish()},decode:e=>{const s=t.decode(e);return t.toObject(s,{longs:String,enums:Number,defaults:!1})}})}get(e){return Gn(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Ge("Proto codec not found.",{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:e}})}}let Vn=!1,Hn=null,zn=null,jn=null;const Wn=e=>e.startsWith(".")?e.slice(1):e,Qn=e=>e instanceof Qe.Namespace,$n=e=>e instanceof Qe.Type,Yn=e=>{for(const t of e.nestedArray)$n(t)?je(t):Qn(t)&&Yn(t)},Jn=()=>{Vn||(Qe.util.Long=$e,Qe.configure(),Vn=!0),We();const e=Qe.Root.fromJSON(qn);return Yn(e),e},Xn=(e,t)=>{const s=e.nestedArray;for(const n of s){if($n(n)){const e=Wn(n.fullName);je(n),t.registerType(e,n);continue}Qn(n)&&Xn(n,t)}},Zn=(e,t,s)=>{const n=t instanceof Error?t.message:String(t);return Ge(`Static proto ${s} failed.`,{code:Ke.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:e,operation:s,cause:n}})},er=()=>Hn||(Hn=Jn(),Hn),tr=()=>{if(jn)return jn;const e=(()=>{if(zn)return zn;const e=new Kn,t=er();return Xn(t,e),zn=e,e})();return jn={encode(t,s){try{return e.getOrThrow(Wn(t)).encode(s)}catch(n){throw Zn(t,n,"encode")}},decode(t,s){try{return e.getOrThrow(Wn(t)).decode(s)}catch(n){throw Zn(t,n,"decode")}}},jn},sr=e=>{const t={};if("function"==typeof e.forEach)return e.forEach((e,s)=>{t[s]=e}),t;const s=e.get?.("content-type");return s&&(t["content-type"]=s),t},nr=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(s){const n=s.method??"GET",r={...s.headers??{}},i=new AbortController,o=s.timeoutMs??e?.timeoutMs??15e3,a=setTimeout(()=>{i.abort()},o),c=((e,t,s)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==s)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(s,r,n);try{const e=await t(s.url,{method:n,headers:r,body:c,signal:s.signal??i.signal});let o;if("arraybuffer"===s.responseType)o=await e.arrayBuffer();else if("text"===s.responseType)o=await e.text();else{const t=e.headers.get("content-type")??"",s=await e.text();o=t.includes("application/json")&&s?JSON.parse(s):s}return{status:e.status,headers:sr(e.headers),data:o}}catch(d){throw Ge("Request adapter execution failed.",{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!0,details:{url:s.url,method:n,cause:d instanceof Error?d.message:String(d)}})}finally{clearTimeout(a)}}}},rr=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,ir=e=>"function"==typeof e.on&&"function"==typeof e.off,or=(e,t,s)=>{if(rr(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 Ge("Socket event listener API is unsupported.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!1,details:{event:t}})},ar=(e,t,s)=>{if(rr(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=or(e,t,(...e)=>{r(),s(...e)}),r}throw Ge("Socket one-time listener API is unsupported.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!1,details:{event:t}})},cr=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?cr(e.data):null;var t},dr=e=>{const t=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set,n=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set;return or(e,"open",()=>{t.forEach(e=>{e()})}),or(e,"message",(...e)=>{const t=cr(e[0]);null!==t&&s.forEach(e=>{e(t)})}),or(e,"error",(...e)=>{const t=e[0];n.forEach(e=>{e(t)})}),or(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);r.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==He.OPEN)throw Ge("Socket is not open.",{code:Ke.SOCKET_FAILED,stage:Ve.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=>(n.add(e),()=>{n.delete(e)}),onClose:e=>(r.add(e),()=>{r.delete(e)})}},lr=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((s,n)=>{let r;try{r=new t(e.url,e.protocols);try{r.binaryType="arraybuffer"}catch{}}catch(u){return void n(Ge("Socket creation failed.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{cause:u instanceof Error?u.message:String(u)}}))}let i,o=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},l=()=>{c||(c=!0,o(),a(),d(),r.close(),n(Ge("Socket connection timed out.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=ar(r,"open",()=>{c||(c=!0,o(),a(),d(),s(dr(r)))}),a=ar(r,"error",e=>{if(c)return;c=!0,o(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;n(Ge("Socket connection failed before open.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(l,e.timeoutMs))})}},ur=(e,t)=>{throw Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:"abort"!==e,details:{reason:e,url:t.url}})},hr=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 Ge("Web upload adapter only supports web-file source.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const s=t.source.file;if(!s)throw Ge("Upload source file is required for web-file uploads.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const n="undefined"!=typeof Blob&&s instanceof Blob,r=t.source.name??"upload.bin";n?e.append("file",s,r):e.append("file",s)})(t,e),t},pr=(e,t,s)=>new Promise((n,r)=>{const i=e(),o=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})})})(i,s),i.addEventListener("abort",()=>{try{ur("abort",s)}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{ur("timeout",s)}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{ur("network",s)}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{n({status:i.status,body:i.responseText})});try{const e=hr(s);i.timeout=o,i.open("POST",s.url),((e,t)=>{Object.entries(t??{}).forEach(([t,s])=>{e.setRequestHeader(t,s)})})(i,s.headers),i.send(e)}catch(a){r(Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{url:s.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),mr=(e,t)=>e?"timeout":"abort",fr=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(n){if("function"==typeof t)return pr(t,e,n);if("function"==typeof s)return(async(e,t,s)=>{const n=s.timeoutMs??t?.timeoutMs??3e4;let r=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,o=i&&Number.isFinite(n)?setTimeout(()=>{r=!0,i.abort()},n):void 0,a=((e,t)=>e??t?.signal)(s.signal,i);try{const t=hr(s),n=await e(s.url,{method:"POST",headers:s.headers,body:t,signal:a}),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(c){const e=c instanceof Error&&"AbortError"===c.name;throw Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!e,details:{reason:e?mr(r):"network",url:s.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(s,e,n);throw Ge("Upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{reason:"missing-upload-runtime",url:n.url}})}}},gr=(e,t)=>{const s=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{s.append(e,t)}),s.append("file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw Ge("React Native upload adapter only supports rn-uri source.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),s},yr=e=>{const t=e?.fetchImpl,s=e?.formDataCtor;if("function"==typeof t&&"function"==typeof s)return{async upload(n){const r=n.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let o=!1;const a=i&&Number.isFinite(r)?setTimeout(()=>{o=!0,i.abort()},r):void 0;try{const e=gr(s,n),r=await t(n.url,{method:"POST",headers:n.headers,body:e,signal:n.signal??i?.signal}),o=await r.text(),a=n.source.size;return"number"==typeof a&&n.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:r.status,body:o}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===Ke.UPLOAD_FAILED&&t.stage===Ve.UPLOAD})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw Ge("React Native upload adapter execution failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!e||o,details:{url:n.url,reason:e?o?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},Ir=(e,t)=>e+t&4294967295,vr=(e,t,s,n,r,i)=>{return Ir((o=Ir(Ir(t,e),Ir(n,i)))<<(a=r)|o>>>32-a,s);var o,a},Cr=(e,t,s,n,r,i,o)=>vr(t&s|~t&n,e,t,r,i,o),Sr=(e,t,s,n,r,i,o)=>vr(t&n|s&~n,e,t,r,i,o),Er=(e,t,s,n,r,i,o)=>vr(t^s^n,e,t,r,i,o),br=(e,t,s,n,r,i,o)=>vr(s^(t|~n),e,t,r,i,o),Ar=(e,t)=>{let[s,n,r,i]=e;s=Cr(s,n,r,i,t[0]??0,7,-680876936),i=Cr(i,s,n,r,t[1]??0,12,-389564586),r=Cr(r,i,s,n,t[2]??0,17,606105819),n=Cr(n,r,i,s,t[3]??0,22,-1044525330),s=Cr(s,n,r,i,t[4]??0,7,-176418897),i=Cr(i,s,n,r,t[5]??0,12,1200080426),r=Cr(r,i,s,n,t[6]??0,17,-1473231341),n=Cr(n,r,i,s,t[7]??0,22,-45705983),s=Cr(s,n,r,i,t[8]??0,7,1770035416),i=Cr(i,s,n,r,t[9]??0,12,-1958414417),r=Cr(r,i,s,n,t[10]??0,17,-42063),n=Cr(n,r,i,s,t[11]??0,22,-1990404162),s=Cr(s,n,r,i,t[12]??0,7,1804603682),i=Cr(i,s,n,r,t[13]??0,12,-40341101),r=Cr(r,i,s,n,t[14]??0,17,-1502002290),n=Cr(n,r,i,s,t[15]??0,22,1236535329),s=Sr(s,n,r,i,t[1]??0,5,-165796510),i=Sr(i,s,n,r,t[6]??0,9,-1069501632),r=Sr(r,i,s,n,t[11]??0,14,643717713),n=Sr(n,r,i,s,t[0]??0,20,-373897302),s=Sr(s,n,r,i,t[5]??0,5,-701558691),i=Sr(i,s,n,r,t[10]??0,9,38016083),r=Sr(r,i,s,n,t[15]??0,14,-660478335),n=Sr(n,r,i,s,t[4]??0,20,-405537848),s=Sr(s,n,r,i,t[9]??0,5,568446438),i=Sr(i,s,n,r,t[14]??0,9,-1019803690),r=Sr(r,i,s,n,t[3]??0,14,-187363961),n=Sr(n,r,i,s,t[8]??0,20,1163531501),s=Sr(s,n,r,i,t[13]??0,5,-1444681467),i=Sr(i,s,n,r,t[2]??0,9,-51403784),r=Sr(r,i,s,n,t[7]??0,14,1735328473),n=Sr(n,r,i,s,t[12]??0,20,-1926607734),s=Er(s,n,r,i,t[5]??0,4,-378558),i=Er(i,s,n,r,t[8]??0,11,-2022574463),r=Er(r,i,s,n,t[11]??0,16,1839030562),n=Er(n,r,i,s,t[14]??0,23,-35309556),s=Er(s,n,r,i,t[1]??0,4,-1530992060),i=Er(i,s,n,r,t[4]??0,11,1272893353),r=Er(r,i,s,n,t[7]??0,16,-155497632),n=Er(n,r,i,s,t[10]??0,23,-1094730640),s=Er(s,n,r,i,t[13]??0,4,681279174),i=Er(i,s,n,r,t[0]??0,11,-358537222),r=Er(r,i,s,n,t[3]??0,16,-722521979),n=Er(n,r,i,s,t[6]??0,23,76029189),s=Er(s,n,r,i,t[9]??0,4,-640364487),i=Er(i,s,n,r,t[12]??0,11,-421815835),r=Er(r,i,s,n,t[15]??0,16,530742520),n=Er(n,r,i,s,t[2]??0,23,-995338651),s=br(s,n,r,i,t[0]??0,6,-198630844),i=br(i,s,n,r,t[7]??0,10,1126891415),r=br(r,i,s,n,t[14]??0,15,-1416354905),n=br(n,r,i,s,t[5]??0,21,-57434055),s=br(s,n,r,i,t[12]??0,6,1700485571),i=br(i,s,n,r,t[3]??0,10,-1894986606),r=br(r,i,s,n,t[10]??0,15,-1051523),n=br(n,r,i,s,t[1]??0,21,-2054922799),s=br(s,n,r,i,t[8]??0,6,1873313359),i=br(i,s,n,r,t[15]??0,10,-30611744),r=br(r,i,s,n,t[6]??0,15,-1560198380),n=br(n,r,i,s,t[13]??0,21,1309151649),s=br(s,n,r,i,t[4]??0,6,-145523070),i=br(i,s,n,r,t[11]??0,10,-1120210379),r=br(r,i,s,n,t[2]??0,15,718787259),n=br(n,r,i,s,t[9]??0,21,-343485551),e[0]=Ir(s,e[0]),e[1]=Ir(n,e[1]),e[2]=Ir(r,e[2]),e[3]=Ir(i,e[3])},Tr=(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},wr=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},Nr=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)Ar(t,Tr(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&&(Ar(t,n),n.fill(0));const o=8*e.length;return n[14]=4294967295&o,n[15]=Math.floor(o/4294967296),Ar(t,n),t.map(wr).join("")},Mr=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 Ge("Image decode capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,s)=>{const n=new Image;n.onload=()=>{e({image:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,cleanup:()=>{URL.revokeObjectURL(t)}})},n.onerror=()=>{URL.revokeObjectURL(t),s(Ge("Image decode failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{reason:"image load error"}}))},n.src=t})},Rr=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw Ge("Web image processor only supports web file source",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.file},_r=()=>({async getImageInfo(e){const t=Rr(e),s=await Mr(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=Rr(e),n=await Mr(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))}})(n.width,n.height,t.maxShortEdge),i=((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 Ge("Canvas capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(s.width,s.height),o=i.getContext("2d");if(!o)throw Ge("Canvas 2d context is missing",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1});o.drawImage(n.image,0,0,s.width,s.height);const a="image/png"===(r=e.mimeType)||"image/webp"===r?r:"image/jpeg",c=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((n,r)=>{e.toBlob(e=>{e?n(e):r(Ge("Image encode failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,s)});throw Ge("Canvas encode capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,a,t.quality),d=(e=>e.name??"image")(e),l="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:l??c,name:d,mimeType:a,size:l?.size??c.size},width:s.width,height:s.height,fileName:d,fileType:a,fileSize:l?.size??c.size,webFile:l}}finally{n.cleanup()}var r},async computeMd5(e){const t=Rr(e),s=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw Ge("Binary read capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>{s(Ge("Binary read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1}))},n.onload=()=>{n.result instanceof ArrayBuffer?t(n.result):s(Ge("Binary read returned invalid result",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1}))},n.readAsArrayBuffer(e)})})(t);return Nr(new Uint8Array(s))}}),Ur=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)},Dr=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw Ge("Miniapp image processor only supports miniapp path source",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.path},Or=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw Ge("Miniapp file system capability is missing",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{capability:"getFileSystemManager"}})},Lr=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},kr=async(e,t)=>new Promise((s,n)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{n(e instanceof Error?e:new Error(Ur(e)))}})}).catch(e=>{throw Ge("Miniapp image info read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{src:t,cause:Ur(e)}})}),Pr=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,xr=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await kr(e,t);return Pr(t,s)},Fr=e=>({async getImageInfo(t){const s=Dr(t),n=await kr(e,s),r=Lr(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 n=Dr(t);if("function"!=typeof e.compressImage)throw Ge("Miniapp image compress capability is missing",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{capability:"compressImage"}});const r=await kr(e,n),i=Pr(n,r),o=((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))}})(r.width,r.height,s.maxShortEdge),a=await new Promise((t,n)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*s.quality))),compressedWidth:o.width,compressedHeight:o.height,success:e=>{e.tempFilePath?t(e.tempFilePath):n(new Error("compressImage missing tempFilePath"))},fail:e=>{n(e instanceof Error?e:new Error(Ur(e)))}})}).catch(e=>{throw Ge("Miniapp image compress failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{src:i,cause:Ur(e)}})}),c=await xr(e,a),d=await kr(e,c),l=Lr(d.type)??t.mimeType,u=await(async(e,t,s)=>{const n=Or(e);return n.getFileInfo?new Promise((e,s)=>{n.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{s(e instanceof Error?e:new Error(Ur(e)))}})}).catch(e=>{throw Ge("Miniapp file info read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{filePath:t,cause:Ur(e)}})}):s})(e,c,t.size);return{source:{sourceType:"miniapp-path",path:c,name:t.name,mimeType:l,size:u},width:d.width,height:d.height,fileName:t.name,fileType:l,fileSize:u}},async computeMd5(t){const s=Dr(t),n=await xr(e,s),r=await(async(e,t)=>{const s=Or(e),n=await new Promise((e,n)=>{s.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{n(e instanceof Error?e:new Error(Ur(e)))}})}).catch(e=>{throw Ge("Miniapp file read failed",{code:Ke.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{filePath:t,cause:Ur(e)}})});return n instanceof ArrayBuffer?new Uint8Array(n):"function"==typeof TextEncoder?(new TextEncoder).encode(n):Uint8Array.from(Array.from(n).map(e=>255&e.charCodeAt(0)))})(e,n);return Nr(r)}}),Br=/* @__PURE__ */new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),qr=[/\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],Gr=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},Kr=e=>{if(!e)return!1;const t=Gr(e,"name");if(t&&Br.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Gr(e,"message"),Gr(e,"errMsg")].some(e=>null!==e&&qr.some(t=>t.test(e)))},Vr=e=>{if(e instanceof Error)return e;const t=Gr(e,"message")??Gr(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Hr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",zr=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),jr=e=>e===qe.ALIPAY_MINIAPP||e===qe.DINGTALK_MINIAPP,Wr=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=Hr.indexOf(t[o]??""),s=Hr.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:Hr.indexOf(a),l="="===c?0:Hr.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},Qr=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),$r=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Yr=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Qr(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?Yr(s.data,t+1):e},Jr=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return $r(e);if(Qr(e))try{return $r(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return $r(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=Jr(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=Jr(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)}},Xr=(e,t)=>{if("string"==typeof e)return e;const n=e instanceof Uint8Array?e:new Uint8Array(e);if(jr(t)){const r=(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+=Hr[o>>18&63],t+=Hr[o>>12&63],t+=void 0===r?"=":Hr[o>>6&63],t+=void 0===i?"=":Hr[63&o]}return t})(n);return s.warn("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:n.byteLength,encodedCharacters:r.length,sourcePrefixHex:zr(n.subarray(0,8))}),r}const r=new ArrayBuffer(n.byteLength);return new Uint8Array(r).set(n),r},Zr=(e,t)=>"string"!=typeof e&&jr(t),ei=(e,t)=>{const n=Yr(e.data);if("string"==typeof n){if(!jr(t))return n;const r=Wr(n),i=new Uint8Array(r);return s.warn("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:n===e.data?"string":"wrapped-string",sourceCharacters:n.length,decodedBytes:r.byteLength,decodedPrefixHex:zr(i.subarray(0,8)),decodedSuffixHex:zr(i.subarray(Math.max(0,i.length-8)))}),r}const r=Jr(n);if(!r){const r="object"==typeof e.data&&null!==e.data?e.data:void 0;return void s.warn("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof n,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:r?Object.keys(r).slice(0,10):[],isBuffer:e.isBuffer})}if(!jr(t))return r.buffer;const i=(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})(r);if(!i)return s.warn("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(n),sourceBytes:r.byteLength,sourcePrefixHex:zr(r.subarray(0,8))}),r.buffer;const o=Wr(i),a=new Uint8Array(o);return s.warn("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(n),sourceBytes:r.byteLength,decodedBytes:o.byteLength,decodedPrefixHex:zr(a.subarray(0,8)),decodedSuffixHex:zr(a.subarray(Math.max(0,a.length-8)))}),o},ti=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),si=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],ni=e=>e instanceof Error?e.message:ti(e)&&"string"==typeof e.errMsg?e.errMsg:ti(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),ri=e=>e?{...e}:{},ii=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},oi=e=>{try{e.close()}catch{}},ai=(e,t)=>new Promise((n,r)=>{let i=!1,o=()=>{};const a=(e,s,n)=>{i||(i=!0,o(),r(Ge(e,{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:n,details:{url:t.url,method:"GET",cause:ni(s)}})))},c=e.downloadFile?.({url:t.url,header:ri(t.headers),timeout:t.timeoutMs??15e3,success:r=>{const c=r.tempFilePath??r.apFilePath;c?((e,t)=>new Promise((s,n)=>{const r=e.getFileSystemManager?.();r?r.readFile({filePath:t,success:e=>{const t=Jr(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,c).then(e=>{i||(i=!0,o(),s.warn("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:r.apFilePath?"apFilePath":"tempFilePath",status:r.statusCode??200,bytes:e.byteLength}),n({status:r.statusCode??200,headers:r.header??{},data:e}))}).catch(e=>{a("Mini program downloaded file read failed.",e,!1)}):a("Mini program download did not return a file path.",r,!1)},fail:e=>{a("Mini program file download failed.",e,!0)}});o=ii(t.signal,()=>{c?.abort(),a("Mini program file download aborted.","abort",!1)})}),ci=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,n)=>{let r=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:ri(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{r(),s({status:e.statusCode,headers:e.header??{},data:e.data})},fail:e=>{r(),n(Ge("Mini program request failed.",{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:ni(e)}}))}});r=ii(t.signal,()=>{i.abort(),n(Ge("Mini program request aborted.",{code:Ke.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):ai(e,t)}),di=(e,t)=>({connect:s=>new Promise((n,r)=>{let i,o,a=!1;const c=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},d=(e,t,n)=>{a||(a=!0,c(),i&&oi(i),r(Ge(t,{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:n,details:{url:s.url,cause:ni(e)}})))},l=e=>{if(!(si(s=e,"send")&&si(s,"close")&&si(s,"onOpen")&&si(s,"onMessage")&&si(s,"onError")&&si(s,"onClose")))return void d(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var s;const r=e;if(a)return void oi(r);i=r;const o=()=>{r.offOpen?.(l),r.offError?.(u)},l=()=>{a?oi(r):(a=!0,c(),o(),n(((e,t,s=He.CONNECTING)=>{const n=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set,o=/* @__PURE__ */new Set;let a=s;return e.onOpen(()=>{a=He.OPEN,n.forEach(e=>{e()})}),e.onMessage(e=>{const s=ei(e,t);void 0!==s&&r.forEach(e=>{e(s)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=He.CLOSED,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(s){if(a!==He.OPEN)throw Ge("Mini program socket is not open.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{readyState:a}});return new Promise((n,r)=>{e.send({data:Xr(s,t),...Zr(s,t)?{isBuffer:!0}:{},success:n,fail:e=>{r(Ge("Mini program socket send failed.",{code:Ke.SOCKET_FAILED,stage:Ve.SOCKET,retryable:!0,details:{cause:ni(e)}}))}})})},close(t,s){a=He.CLOSING,e.close({code:t,reason:s})},onOpen:e=>(n.add(e),()=>{n.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}})(r,t,He.OPEN)))},u=e=>{o(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};r.onOpen(l),r.onError(u)};let u;"number"==typeof s.timeoutMs&&s.timeoutMs>0&&(o=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},s.timeoutMs));try{u=e.connectSocket({url:s.url,...t===qe.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(s.protocols)?[...s.protocols]:"string"==typeof s.protocols?[s.protocols]:void 0,fail:e=>{d(e,"Mini program socket connect failed.",!0)}})}catch(p){return void d(p,"Mini program socket creation failed.",!0)}var h;"object"!=typeof(h=u)||null===h||"function"!=typeof h.then?l(u):Promise.resolve(u).then(e=>l(e),e=>d(e,"Mini program socket connect failed.",!0))})}),li=e=>({upload:t=>new Promise((s,n)=>{const r=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw Ge("Mini program upload only supports miniapp-path source.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:r.path,name:"file",header:ri(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i(),s({status:e.statusCode,body:e.data})},fail:e=>{i(),n(Ge("Mini program upload failed.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!0,details:{url:t.url,path:r.path,cause:ni(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=ii(t.signal,()=>{o.abort(),n(Ge("Mini program upload aborted.",{code:Ke.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{url:t.url,path:r.path,reason:"abort"}}))})})}),ui=(e,t)=>{const s=(e=>e===qe.ALIPAY_MINIAPP||e===qe.DINGTALK_MINIAPP)(t);return{async getItem(t){if(si(e,"getStorageSync"))try{const n=(e=>ti(e)&&"data"in e?e.data:e)(e.getStorageSync(s?{key:t}:t));return"string"==typeof n&&n.length>0?n:null}catch{return null}return si(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,n){if(si(e,"setStorageSync"))try{s?e.setStorageSync({key:t,data:n}):e.setStorageSync(t,n)}catch(r){if(Kr(r))throw Vr(r)}else if(si(e,"setStorage"))return new Promise((s,i)=>{try{e.setStorage({key:t,data:n,success:s,fail:e=>{Kr(e)?i(Vr(e)):s()}})}catch(r){if(Kr(r))return void i(Vr(r));s()}})},async removeItem(t){if(si(e,"removeStorageSync"))try{e.removeStorageSync(s?{key:t}:t)}catch{}else if(si(e,"removeStorage"))return new Promise(s=>{try{e.removeStorage({key:t,success:s,fail:()=>{s()}})}catch{s()}})}}},hi=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>si(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 si(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),si(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{si(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},n=()=>{t(!1)};return si(e,"onAppShow")&&e.onAppShow(s),si(e,"onAppHide")&&e.onAppHide(n),t(!0),()=>{si(e,"offAppShow")&&e.offAppShow(s),si(e,"offAppHide")&&e.offAppHide(n)}}}),pi=(e,t=qe.WECHAT_MINIAPP,s=t)=>{const n=(e=>{if(si(e,"request")&&si(e,"connectSocket")&&si(e,"uploadFile"))return e;throw Ge("Mini program platform capability is missing.",{code:Ke.MISSING_CAPABILITY,stage:Ve.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),r="function"==typeof n.getImageInfo?Fr(n):void 0;return{request:ci(n),socket:di(n,s),upload:li(n),runtime:hi(n,t),storage:ui(n,s),imageProcessor:r}},mi=[qe.WEB,qe.ELECTRON_RENDERER,qe.REACT_NATIVE],fi=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},gi=e=>mi.includes(e),yi=(e,t)=>e!==qe.UNIAPP?gi(e):!On(t)&&!vi(t)&&Rn(t),Ii=e=>fi(e,"getImageInfo")&&fi(e,"getFileSystemManager"),vi=e=>!On(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),Ci=(e,t)=>{if(gi(e)&&e!==qe.REACT_NATIVE)return _r();if(xn(e)&&Ii(t))return Fr(t);if(e===qe.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Rn(e))return _r();if(Ii(e.uni))return Fr(e.uni);if(Ii(e.wx))return Fr(e.wx)}},Si=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())}},Ei=(e,t,s,n)=>{if(e===qe.UNIAPP&&vi(s)&&void 0!==s.uni&&An(s.uni))return{...pi(s.uni,e,t),proto:tr()};if(((e,t)=>!yi(e,t)&&xn(e))(e,s)&&An(n))return{...pi(n,e,t),proto:tr()};const r=s.XMLHttpRequest,i=yi(e,s),o=i?nr({fetchImpl:s.fetch}):void 0,a=i?lr({webSocketCtor:s.WebSocket}):void 0,c=e===qe.REACT_NATIVE?yr({fetchImpl:s.fetch,formDataCtor:s.FormData}):i?fr({xhrFactory:"function"==typeof r?()=>new r:void 0,fetchImpl:s.fetch}):void 0,d=i&&e!==qe.REACT_NATIVE?(l={platform:e,windowRef:s.window,documentRef:s.document,navigatorRef:s.navigator},{getPlatform:()=>l.platform,getNetworkType:()=>!1===l.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(l.navigatorRef?.connection?.type??l.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=l.windowRef;if(!t)return()=>{};const s=()=>{e(!0)},n=()=>{e(!1)};return t.addEventListener("online",s),t.addEventListener("offline",n),"boolean"==typeof l.navigatorRef?.onLine&&e(l.navigatorRef.onLine),()=>{t.removeEventListener("online",s),t.removeEventListener("offline",n)}},onAppVisibilityChange(e){const t=l.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 l;return{request:o,upload:c,socket:a,runtime:d,proto:tr(),storage:Si(s),imageProcessor:i&&e!==qe.REACT_NATIVE?_r():Ci(e,n)}},bi=(e,t)=>{if(void 0!==e)return e;throw Ge("Platform adapter initialization failed.",{code:Ke.INIT_FAILED,stage:Ve.INIT,retryable:!1,details:{capability:t}})},Ai=(e,t)=>Pn(t,e).platform,Ti=e=>{const s=t(e?.runtimeInput),n=Pn(s,e?.prefer),r=n.platform,i=Ei(r,n.hostPlatform,s,n.global),o=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,i),a={...i,...o},c=(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}))(a);Bn(c);return{platform:r,platformId:r,capability:c,request:bi(a.request,"request"),upload:bi(a.upload,"upload"),socket:bi(a.socket,"socket"),runtime:bi(a.runtime,"runtime"),proto:bi(a.proto,"proto"),storage:bi(a.storage,"storage"),imageProcessor:a.imageProcessor}},wi={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Ni{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 s.debug(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const Mi={interval:3e4,timeout:6e4},Ri="function"==typeof TextDecoder?new TextDecoder:null;class _i{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 n=this.parseJson(t);if(!_i.isRecord(n))return;"pong"===_i.readString(n.type)&&(this.markAlive(),s.debug("Pong received"))},this.config={...Mi,...e}}start(e,t,n){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=n??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),s.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),s.debug("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===He.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=>{s.error("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),s.debug("Ping sent")}catch(e){s.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)?Ri?.decode(t)??Cn(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(()=>{s.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!==He.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(n){return s.warn("Heartbeat probe failed",n),!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 Ui=null;function Di(){return Ui||(Ui=er()),Ui}const Oi="websdk2:device-info",Li="webim",ki="web",Pi=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(Oi);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(Oi,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===Li){const e=`${ki}_${s}`,t=d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e});return c(t),t}if(void 0!==r){const e=d({deviceId:`webim_${ki}_${n}`,deviceName:n,deviceUuid:`${ki}_${s}`});return c(e),e}const t={deviceId:`webim_${ki}_${n}`,deviceName:`webim_${ki}_${n}`,deviceUuid:`webim_${ki}_${n}`};return c(t),t}if(n===Li){const e=`random_${ki}_${s}`;return d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e})}if(void 0!==r){return d({deviceId:`webim_${ki}_${n}`,deviceName:n,deviceUuid:`random_${ki}_${s}`})}return{deviceId:`webim_${ki}_${n}`,deviceName:`webim_${ki}_${n}`,deviceUuid:`webim_${ki}_${n}`}},xi=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Fi=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 $e(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Bi=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:sn,stringValue:JSON.stringify(n)})}catch{t.push({key:s,type:tn,stringValue:Object.prototype.toString.call(n)})}else t.push({key:s,type:tn,stringValue:n});else Number.isInteger(n)?t.push({key:s,type:Ys,varintValue:n}):t.push({key:s,type:en,doubleValue:n});else t.push({key:s,type:$s,varintValue:n?1:0});return t},qi=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:tn;if(n!==$s)if(n!==Ys&&n!==Js&&n!==Xs)if(n!==Zs)if(n!==en){if(n!==sn)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},Gi=/* @__PURE__ */new Set(["mute"]),Ki={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},Vi=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Hi=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},zi=(e,t)=>{const s=e?.map(e=>Vi(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},ji=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=Hi(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},Wi=e=>{const t=Hi(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=Ki[n];if(!e)continue;let t=r;if(Gi.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},Qi=e=>{const t=Hi(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:Vi(t.operator)??Vi(t.username)}},$i=(e,t)=>({eventName:e,payload:t}),Yi=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=Vi(e.from?.name),n=(r=e.to,Vi(r?.[0]?.name));var r;switch(e.operation){case 1:return $i(At,t);case 10:return $i(Nt,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:n??s});case 17:return $i(Tt,{...t,memberIds:zi(e.members,s),ext:e.ext??e.eventExt});case 18:return $i(wt,{...t,memberIds:zi(e.members,s)});case 20:return $i(kt,{...t,oldOwnerId:s,newOwnerId:n});case 21:return $i(Ot,{...t,adminId:n??s});case 22:return $i(Lt,{...t,adminId:n??s});case 23:{const s=(e=>{const t=Hi(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):zi(e.members,n),i=46388736e5;return $i(Mt,{...t,userIds:r,muteMembers:s??Object.fromEntries(r.map(e=>[e,i])),muteExpire:ji(e.reason,e.eventExt)??i})}case 24:return $i(Rt,{...t,userIds:zi(e.members,n)});case 25:return $i(Pt,{...t,announcement:e.reason??""});case 26:return $i(Pt,{...t,announcement:""});case 29:return $i(_t,{...t,userIds:zi(e.members,n)});case 30:return $i(Ut,{...t,userIds:zi(e.members,n)});case 31:return $i(Dt,{...t,isMuted:!0});case 32:return $i(Dt,{...t,isMuted:!1});case 14:return $i(xt,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Wi(e.eventExt)});case 43:{const n=Qi(e.eventExt);return $i(Ft,{...t,attributes:n.attributes,from:n.from??s})}case 44:{const n=Qi(e.eventExt);return $i(Bt,{...t,keyList:n.keyList,from:n.from??s})}default:return null}},Ji=/* @__PURE__ */new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Xi={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Zi=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},eo=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},to=(e,t)=>{const s=e?.map(e=>Zi(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},so=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=eo(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},no=e=>{const t=eo(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=Xi[n];if(!e)continue;let t=r;if(Ji.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},ro=(e,t)=>{const s=eo(t)??eo(e);return st(s??void 0)??void 0},io=(e,t)=>{const s=eo(t)??eo(e);return Zi(s?.fileId)??Zi(s?.file_id)??Zi(e)??""},oo=(e,t)=>({eventName:e,payload:t}),ao=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=Zi(e.from?.name),n=(r=e.to,Zi(r?.[0]?.name));var r;switch(e.operation){case 4:return oo(Xe.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return oo(Xe.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return oo(Xe.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:n,reason:e.reason});case 7:return oo(Xe.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return oo(Xe.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return oo(Xe.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return oo(Xe.USER_REMOVED,t);case 1:return oo(Xe.GROUP_DESTROYED,t);case 19:return oo(Xe.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=eo(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=Zi(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):to(e.members,n);return oo(Xe.MUTE_LIST_ADDED,{...t,userIds:r,muteExpire:r.map(e=>s?.[e]).find(e=>void 0!==e)??so(e.reason,e.eventExt)})}case 24:return oo(Xe.MUTE_LIST_REMOVED,{...t,userIds:to(e.members,n)});case 29:return oo(Xe.ALLOW_LIST_ADDED,{...t,userIds:to(e.members,n)});case 30:return oo(Xe.ALLOW_LIST_REMOVED,{...t,userIds:to(e.members,n)});case 31:return oo(Xe.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return oo(Xe.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return oo(Xe.ADMIN_ADDED,{...t,administratorId:n??s});case 22:return oo(Xe.ADMIN_REMOVED,{...t,administratorId:n??s});case 20:return oo(Xe.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:n});case 17:{const n=to(e.members,s);return oo(Xe.MEMBERS_JOINED,{...t,memberIds:n})}case 18:{const n=to(e.members,s);return oo(Xe.MEMBERS_EXITED,{...t,memberIds:n})}case 25:return oo(Xe.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return oo(Xe.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return oo(Xe.SHARED_FILE_ADDED,{...t,sharedFile:ro(e.reason,e.eventExt)});case 28:return oo(Xe.SHARED_FILE_DELETED,{...t,fileId:io(e.reason,e.eventExt)});case 14:return oo(Xe.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:no(e.eventExt)});case 41:return oo(Xe.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return oo(Xe.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const n=(e=>{const t=eo(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:Zi(t.username),attribute:n}})(e.eventExt);return oo(Xe.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:n.userId,attribute:n.attribute,from:s,source:e.source??"direct"})}default:return null}},co=/* @__PURE__ */new WeakMap,lo=(e,t)=>{co.set(e,t)},uo=e=>co.get(e)??null,ho=(e,t)=>{const s=uo(e);s&&lo(t,s)},po=/* @__PURE__ */new WeakMap,mo=e=>po.get(e),fo="singleChat",go="groupChat",yo={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},Io=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},vo=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}},Co=e=>{if(!Array.isArray(e))return;const t=e.map(e=>Io(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},So=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Eo=(...e)=>{for(const t of e){const e=Io(t);if(e)return e}},bo=(e,t)=>Boolean(e&&t&&e===t),Ao=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),To=(e,t,s)=>{const n=Co(e);if(n&&n.length>0)return n;const r=(t??[]).map(e=>Io(e.name)).filter(e=>"string"==typeof e);if(r.length>0)return r;const i=Io(s?.name);return i?[i]:[]},wo=e=>{const t=vo(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}}},No=(e,t)=>{const n=Eo(e.to?.[0]?.clientResource);if(1!==e.to?.length||Io(e.to[0]?.name)!==t.userId||!Ao(t.userId,n,t))return null;const r=(i=e.from,Io(i?.name)??"");var i;if(!r)return s.warn("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const o=(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 s.warn("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"contact",operation:o,targetUserId:r,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:n,timestamp:e.timestamp,raw:e.raw}},Mo=(e,t)=>{if(!e.groupId)return s.warn("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const n=Eo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Ao(Io(e.from?.name),n,t))return null;const r=(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 s.warn("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===r)return null;const i=To(e.members,e.to,e.from);return{category:"group",operation:r,groupId:e.groupId,userIds:i.length>0?i:void 0,operatorId:Io(e.from?.name),groupName:e.groupName,deviceId:n,timestamp:e.timestamp,raw:e.raw}},Ro=(e,t)=>{if(!e.threadId)return s.warn("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const n=Eo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Ao(Io(e.from?.name),n,t))return null;const r=(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 s.warn("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===r)return null;const i=To(e.members,e.to,e.from);return{category:"thread",operation:r,threadId:e.threadId,parentId:e.parentId,userIds:i.length>0?i:void 0,operatorId:Io(e.from?.name),threadName:e.threadName,deviceId:n,timestamp:e.timestamp,raw:e.raw}},_o=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const n=Eo(e.res,e.raw?.resource,e.raw?.clientResource);if(bo(n,t.clientResource))return s.debug("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const r="chat"===(i=e.type)||"singleChat"===i?fo:go;var i;const o=Io(e.id)??(r===fo?Io(e.from):void 0);if(!o)return s.warn("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const a=(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 s.warn("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===a?null:{category:"conversation",operation:a,conversationId:o,conversationType:r,mark:"mark"===e.operation||"mark_delete"===e.operation?wo(e.ext):void 0,operatorId:Io(e.from),deviceId:n,timestamp:vo(e.ts),raw:e.raw}},Uo=(e,t)=>{const n=Eo(e.resource,e.raw?.resource,e.raw?.clientResource);if(bo(n,t.clientResource))return s.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const r=Io(e.to);if(!r)return s.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const i=Io(e.lastMsgId),o=Co(e.msgIdList)??(i?[i]:void 0),a=vo(e.deleteTime);if(!o&&void 0===a)return s.warn("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:r}),null;const c=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(s.warn("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===c?null:{category:"messageRemoved",operation:c,conversationId:r,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?go:fo,messageIds:o,beforeTimestamp:a,deviceId:n,raw:e.raw}},Do=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,Lo=65547,ko=15,Po=2113929216,xo=65536,Fo=65536,Bo=10485760,qo={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Go={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Ko(e){if(!(e>0))return Fo;if(e<=Fo)return Fo;if(e>1073741823)return e;for(var t=Fo;t<e;)t*=2;return t}var Vo={byU16:0,byU32:1},Ho=0,zo=1,jo=2,Wo=0,Qo=1;function $o(e,t){return e[t]|e[t+1]<<8}function Yo(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Jo(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var Xo="fast";function Zo(e){return 2654435761*(e>>>0)>>>20&4095}function ea(e){return 2654435761*(e>>>0)>>>19&8191}function ta(e,t,s){if("fast"===Xo){var n=Yo(e,t);return s===Vo.byU16?ea(n):Zo(n)}throw new Error("Unsupported hash strategy: "+Xo)}function sa(e,t,s,n,r){s[t]=e-r}function na(e,t,s,n,r){sa(t,ta(e,t,n),s,0,r)}function ra(e,t,s,n){return t[e]+n}function ia(e,t,s,n,r){return ra(ta(e,t,n),s,0,r)}function oa(e,t,s,n){for(var r=t;t<n-3;){if(Yo(e,t)!==Yo(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 aa(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,A=0,T=i>0?i:s.length,w=0;if(r>Po)return 0;switch(c){case Ho:default:l=n,u=n;break;case zo:l=n-e.currentOffset,u=n-e.dictSize;break;case jo:l=n-e.currentOffset,u=n}if(a===Vo.byU16&&r>=Lo)return 0;if(r<13)return la(t,s,C,S,A,T,o);na(t,m,p,a,l),h=ta(t,++m,a);e:for(;;){var N,M,R=m,_=1,U=64;do{var D=h;if(m=R,R+=_,_=U++>>>6,R>E)return la(t,s,C,S,A,T,o);N=ra(D,p,0,l),c===jo&&(N<n?(w=v,u=y):(w=0,u=n)),h=ta(t,R,a),sa(m,D,p,0,l)}while(d===Qo&&N<f||a!==Vo.byU16&&N+65535<m||!ca(t,g,m,N,w,c,n));for(;m>C&&N+w>u;){var O=N+w-1;if(t[m-1]!==(c===jo&&N<n?g[O-y+e.dictionaryStart]:t[O]))break;m--,N--}var L=m-C;if(M=A++,o&&A+L+8+Math.floor(L/255)>T)return 0;if(L>=ko){var k=L-ko;for(s[M]=240;k>=255;)s[A++]=255,k-=255;s[A++]=k}else s[M]=L<<4;if(L>=16&&s.set&&t.subarray)s.set(t.subarray(C,C+L),A),A+=L;else for(var P=0;P<L;P++)s[A++]=t[C+P];t:for(;;){var x;if(Jo(s,A,m-N),A+=2,c===jo&&N<n){var F=m+(I-(N+w));if(F>b&&(F=b),(m+=4+(x=da(t,g,m+4,N+w+4-y+e.dictionaryStart,F,I-y)))===F&&F<b){var B=oa(t,m,n,b);x+=B,m+=B}}else m+=4+(x=oa(t,m+4,N+4,b));if(o&&A+6+(x>>>8)>T)return 0;if(x>=15){for(s[M]+=15,x-=15;x>=510;)s[A++]=255,s[A++]=255,x-=510;x>=255&&(x-=255,s[A++]=255),s[A++]=x}else s[M]+=x;if(C=m,m>E)break e;if(na(t,m-2,p,a,l),N=ia(t,m,p,a,l),c===jo&&(N<n?(w=v,u=y):(w=0,u=n)),na(t,m,p,a,l),!((d!==Qo||N>=f)&&N+65535>=m&&ca(t,g,m,N,w,c,n)))break t;s[M=A++]=0}h=ta(t,++m,a)}return la(t,s,C,S,A,T,o)}function ca(e,t,s,n,r,i,o){var a,c=Yo(e,s);i===jo&&n+r<o?a=Yo(t,n+r):a=Yo(e,n+r);return c===a}function da(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 la(e,t,s,n,r,i,o){var a=n-s;if(o&&r+a+1+Math.floor((a+255-ko)/255)>i)return 0;if(a>=ko){for(t[r++]=240,a-=ko;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 ua(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 ha(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)===ko){var A=ua(e,N={ip:p},m-ko,!0);if(p=N.ip,-1===A)return-(p-s)-1;if(f+(S+=A)<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 T=0;T<S;T++)t[f+T]=e[p+T];p+=S,f+=S;break}if(S>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+S),f);else for(T=0;T<S;T++)t[f+T]=e[p+T];if(f=E,(p+=S)+2>m)return-(p-s)-1;var w=$o(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;A=ua(e,N={ip:p},m-5+1,!1);if(p=N.ip,-1===A)return-(p-s)-1;if(f+(S+=A)<f)return-(p-s)-1}if(S+=4,d===jo&&b<l){if(f+S>g-5)return-(p-s)-1;if(S<=l-b){var M=I-(l-b);for(T=0;T<S;T++)t[f+T]=t[M+T];f+=S}else{var R=l-b;for(M=I-R,T=0;T<R;T++)t[f+T]=t[M+T];var _=S-R;if(_>(f+=R)-l)for(var U=l,D=f+_;f<D;)t[f++]=t[U++];else{for(T=0;T<_;T++)t[f+T]=t[l+T];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 pa(){return{hashTable:new Uint32Array(Oo),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function ma(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function fa(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?Qo:Wo;return e.dictionary&&c===n?(l=aa(e,t,s,n,r,o||0,a||!1,Vo.byU32,zo,h),e.dictSize+=r,e.currentOffset+=r,l):(l=aa(e,t,s,n,r,o||0,a||!1,Vo.byU32,jo,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 ya(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function Ia(e,t,s,n){return e.prefixSize=n,e.prefixEnd=s+n,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function va(e,t,s,n,r,i,o){var a;if(e.prefixEnd===i){if((a=ha(t,s,n,r,i,o,!0,0,0,jo,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=ha(t,s,n,r,i,o,!0,0,0,jo,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function Ca(e){var t=(e=e||{}).minWorkArea||Fo,s=e.maxWorkArea||Bo,n=e.shrinkThreshold||t;t<Fo&&(t=Fo),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=xo+t,this.maxBufferSize=xo+s,this.shrinkThreshold=xo+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:qo.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=pa()}function Sa(e){var t=(e=e||{}).minWorkArea||Fo,s=e.maxWorkArea||Bo,n=e.shrinkThreshold||t;t<Fo&&(t=Fo),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=xo+t,this.maxBufferSize=xo+s,this.shrinkThreshold=xo+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:qo.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Ca.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<xo?this.offset:xo,r=this.offset>xo?this.offset-xo: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},Ca.prototype.compress=function(e,t){var s=e.length;if(s<=0)return Go.PARAM_ERROR;if(s>this.maxBufferSize-xo)return Go.PARAM_ERROR;if(s>this.ringBufferSize-xo){var n=Ko(s),r=xo+n;if(r>this.maxBufferSize&&(r=this.maxBufferSize),!this._resizeBuffer(r))return Go.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(ga(this.stream,this.ringBuffer,0,xo),this.offset=xo);var i=this.offset;this.ringBuffer.set(e,i);var o=fa(this.stream,this.ringBuffer,t,i,s,0,t.length,!0);return o<=0?Go.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),o)},Ca.prototype.reset=function(){this.offset=0,ma(this.stream)},Ca.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Ca.prototype._tryAutoShrink=function(){this.shrinkMode!==qo.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===qo.AUTO_IMMEDIATE||this.shrinkMode===qo.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Ca.prototype.getWorkArea=function(){return this.ringBufferSize-xo},Ca.prototype.getRingBufferSize=function(){return this.ringBufferSize},Ca.prototype.getBaseBufferSize=function(){return this.minBufferSize},Ca.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Ca.prototype.getCurrentOffset=function(){return this.offset},Ca.prototype.getShrinkMode=function(){return this.shrinkMode},Ca.prototype.setShrinkMode=function(e){this.shrinkMode=e},Ca.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Ca.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-xo,s=this.maxBufferSize-xo;if(e<t||e>s)return Go.PARAM_ERROR;this.shrinkThreshold=xo+e},Sa.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<xo?this.offset:xo,r=this.offset>xo?this.offset-xo:0;t.set(this.ringBuffer.subarray(r,r+n),0),s=n,Ia(this.streamDecode,0,0,n)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Sa.prototype.decompress=function(e,t,s){var n=e.length;if(n<=0||s<=0)return Go.PARAM_ERROR;if(s>this.maxBufferSize-xo)return Go.PARAM_ERROR;if(s>this.ringBufferSize-xo){var r=Ko(s),i=xo+r;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return Go.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var o=this.offset-xo;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+xo),0),Ia(this.streamDecode,this.ringBuffer,0,xo),this.offset=xo}var a=va(this.streamDecode,e,this.ringBuffer,0,n,this.offset,s);return a<=0?Go.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Sa.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Sa.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Sa.prototype._tryAutoShrink=function(){this.shrinkMode!==qo.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===qo.AUTO_IMMEDIATE||this.shrinkMode===qo.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Sa.prototype.getWorkArea=function(){return this.ringBufferSize-xo},Sa.prototype.getRingBufferSize=function(){return this.ringBufferSize},Sa.prototype.getBaseBufferSize=function(){return this.minBufferSize},Sa.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Sa.prototype.getCurrentOffset=function(){return this.offset},Sa.prototype.getShrinkMode=function(){return this.shrinkMode},Sa.prototype.setShrinkMode=function(e){this.shrinkMode=e},Sa.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Sa.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-xo,s=this.maxBufferSize-xo;if(e<t||e>s)return Go.PARAM_ERROR;this.shrinkThreshold=xo+e};const Ea={LZ4_MAX_INPUT_SIZE:Po,BLOCK_MAX_SIZE:65536,DICT_SIZE:xo,DEFAULT_WORK_AREA:Fo,DEFAULT_MAX_WORK:Bo,SHRINK_MODE:qo,LZ4_ERROR:Go,alignToPowerOf2:Ko,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".');Xo=e},getHashStrategy:function(){return Xo},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>Po)return 0;if(0===n)return t.length>r?(t[r]=0,1):0;var i=n<Lo?Vo.byU16:Vo.byU32;return aa({hashTable:new Uint32Array(i===Vo.byU16?8192:Oo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,0,!1,i,Ho,Wo)},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>Po)return 0;if(i<1)return 0;if(0===n)return t[r]=0,1;var o=n<Lo?Vo.byU16:Vo.byU32;return aa({hashTable:new Uint32Array(o===Vo.byU16?8192:Oo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,i,!0,o,Ho,Wo)},compressBound:function(e){return e<0||e>Po?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:ha(e,t,s,n,r,i,!0,0,0,Ho,r,null,0))},decompressFast:function(e,t,s,n,r){return ha(e,t,s=s||0,0,n=n||0,r,!1,0,0,zo,n-65536,0,65536)},createStream:pa,resetStream:ma,loadDict:function(e,t,s,n){if(e.initCheck&&ma(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;)na(t,i,e.hashTable,Vo.byU32,r),i+=3;return n},compressContinue:fa,saveDict:ga,createStreamDecode:ya,setStreamDecode:Ia,decompressSafeContinue:va,RingBufferEncoder:Ca,RingBufferDecoder:Sa,_hashU16:ea,_hashU32:Zo,_TABLE_TYPE:Vo},ba=268435455,Aa=new Uint32Array(256);let Ta=!1;function wa(e){!function(){if(!Ta){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;Aa[e]=t>>>0}Ta=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const n=e[s]??0;t=t>>>8^(Aa[255&(t^255&n)]??0)}return(4294967295^t)>>>0}var Na=/* @__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))(Na||{});const Ma=268435455;class Ra{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Ea.DEFAULT_WORK_AREA,maxWorkArea:Ea.DEFAULT_MAX_WORK,shrinkMode:Ea.SHRINK_MODE.MANUAL};this.encoder=new Ea.RingBufferEncoder(e),this.decoder=new Ea.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>Ma)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=Ea.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>ba)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=wa(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>Ma)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=wa(o);if(c!==r)throw new Error(`CRC32 checksum mismatch: expected ${r}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const _a=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ua=(e,t)=>Ye(e,t).finish();class Da{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Pi({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:[Ts],compressType:[ws],sessionId:s,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.useCustomAttachmentUpload=e.useCustomAttachmentUpload??!1}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=Di(),t=e.lookupType("easemob.pb.Provision"),s=e.lookupType("easemob.pb.MSync"),r={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[ws],encryptType:[Ts],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,auth:`$t$${this.context.token}`,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}:{}},i=Ua(t,r),o={version:0,guid:xi({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),auth:`$t$${this.context.token}`,command:jt,deviceId:0,encryptType:[Ts],payload:i,traceId:n()};return Ua(s,o)}encodeHeartbeat(){const e=Di(),t=e.lookupType("easemob.pb.CommUnreadUL"),s=e.lookupType("easemob.pb.MSync"),r=Ua(t,{}),i={version:0,encryptType:[Ts],command:Ht,payload:r,traceId:n()};return Ua(s,i)}encodeStatisticRebuild(){const e=Di(),t=e.lookupType("easemob.pb.StatisticsBody"),s=e.lookupType("easemob.pb.Meta"),r=e.lookupType("easemob.pb.CommSyncUL"),i=e.lookupType("easemob.pb.MSync"),o=Ua(t,{operation:0}),a=s.decode(new Uint8Array);a.id=Date.now(),a.ns=ys,a.payload=o;const c=r.decode(new Uint8Array);c.meta=a;const d=Ua(r,c);return Ua(i,{version:0,encryptType:[Ts],command:Vt,payload:d,traceId:n()})}decodeProvision(e){const t=Di().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},n="number"==typeof s.errorCode?s.errorCode:Rs,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===Ms,statusCode:n,reason:r,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Di().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=Di().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=Di().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=Di(),n=t.lookupType("easemob.pb.CommSyncDL"),r=t.lookupType("easemob.pb.MessageBody"),i=n.decode(e);s.debug("decodeSync commSyncDl",{hasMetas:Array.isArray(i.metas)});const o=Array.isArray(i.metas)?i.metas:[],a=this.decodeAck(i);a?.ok&&(a.chatRoomInfo=this.decodeChatRoomJoinInfo(o));const c=Fi(i.metaId),d=Fi(i.nextKey),l=i.queue??void 0,u="boolean"==typeof i.isLast?i.isLast:void 0,h=[],p=[];if(c&&"0"!==c){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(o,r):void 0;for(const t of o){const e=this.decodeNotifyMeta(t);e.length>0&&p.push(...e)}return{ack:a,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u,replacedMessage:e}}for(const s of o){const e=this.decodeChatMeta(s,r);e&&h.push(e);const t=this.decodeChatActionMeta(s,r);t&&p.push(t);const n=this.decodeNotifyMeta(s);n.length>0&&p.push(...n)}return{ack:a,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)!==Is)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 n=e,r=n.payload;let i=null;if(r instanceof Uint8Array?i=r:r instanceof ArrayBuffer?i=new Uint8Array(r):ArrayBuffer.isView(r)&&(i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!i)return null;if(("number"==typeof n.ns?n.ns:void 0)!==Is)return null;try{const e=t.decode(i);if(!e||"object"!=typeof e)return null;const r=e,o="number"==typeof r.type?r.type:Qt;if(o!==Xt&&o!==es&&o!==ts&&o!==ss&&o!==Zt)return null;const a=this.readJid(n.to),c=Number(Fi(n.timestamp))||Date.now(),d=this.resolveActionConversationType(a.domain,r.meta,r),{senderId:l,receiverId:u}=this.resolveIncomingMessageParties(n,r,d),h=this.resolveActionConversationId(l,u,d);if(o===ts)return!0===r.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(o===Xt){s.debug("Received READ_ACK MessageBody",r);const e=(Array.isArray(r.ackMessageIds)?r.ackMessageIds:[]).map(e=>Fi(e)).filter(e=>Boolean(e)),t=Fi(r.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!h)return null;const n=qi(Array.isArray(r.ext)?r.ext.filter(_a):void 0),i=_a(n.group_ack_count)?n.group_ack_count:{},o=e.flatMap(e=>{const t=i[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:o}:{}}}}if(o===Zt){const e=Fi(r.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(o===es){const e=Fi(r.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=Fi(r.editMessageId),m=(Array.isArray(r.contents)?r.contents:[])[0],f=m?this.decodeContent(m):null;if(!p||!h||!f)return null;const g=this.resolveModifiedInfo(r.meta);return{type:"message_updated",data:{messageId:p,conversationId:h,conversationType:d,timestamp:c,message:{type:f.type,body:f.body,ext:qi(r.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!==Ss&&s!==Cs&&s!==vs&&s!==ys)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===Cs?this.decodeRosterMeta(t,r):s===vs?this.decodeMucMeta(t,r):s===ys?this.decodeStatisticGroupReceiptNotifies(t,r):this.decodeNotifyPayload(r):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const n=Di(),r=n.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof r.location||0===r.location.length)return[];const i=JSON.parse(r.location);if(!_a(i)||!Array.isArray(i.group_ack))return[];const o=this.readMetaTimestamp(e)??Date.now(),a=/* @__PURE__ */new Map;for(const e of i.group_ack){if(!_a(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||a.set(s,{conversationId:t,count:e})}}return s.debug("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(a,([e,{conversationId:t,count:s}])=>({messageId:e,conversationId:t,count:s}))}),Array.from(a,([e,{conversationId:t,count:s}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:o,receiptDetails:[{messageId:e,count:s}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==ys)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=Di(),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=Di(),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=No({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=Di(),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=Ro({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=Mo({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?Yi({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}):ao({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&&po.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 s=0;s<e.length;s+=1){const n=e[s];if(void 0===n)return[];t+=`%${n.toString(16)}`}const n=decodeURIComponent(t),r=JSON.parse(n);s.debug("Decoded MSync notify payload",{payload:r});const i="string"==typeof r.type?r.type:"";if(!i)return[];if("thread"===i){return[{type:i,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:_a(r.data)?r.data:r}}]}if("conv"===i){const e=_a(r.data)?r.data:r,t=[],s="string"==typeof e.op?e.op:"";if("pin"===s||"pin_delete"===s)return[{type:i,eventName:"onPinnedMessageChanged",data:e}];const n=_o({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 n&&t.push(this.createMultiDeviceNotify(n)),t}if("roaming_delete"===i){const e=_a(r.data)?r.data:r,t=Uo({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"===i){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const s=[];for(const n of e){if(!So(n))continue;const e=Eo(n.operator_resource,n.resource,n.clientResource);if(bo(e,t.clientResource))continue;const r=Io(n.group)??Io(n.user);if(!r||!So(n.data))continue;const i=Io(n.group)?go:fo,o=n.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:r,conversationType:i,remindType:Io(o.type),silentMode:o,deviceId:e,raw:n})}return s})(_a(r.data)&&Array.isArray(r.data.values)?r.data.values:Array.isArray(r.values)?r.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:i,data:r.data??r}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,s=Number(Fi(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:Do(e.category),data:e}}decodeNotice(e){const t=Di().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Di().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=Di(),s=t.lookupType("easemob.pb.CommSyncUL"),r=t.lookupType("easemob.pb.MSync"),i=Ua(s,{queue:e}),o={version:0,encryptType:[Ts],command:Vt,payload:i,traceId:n()};return Ua(r,o)}encodeLastSession(e,t){const s=Di(),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o=Ua(r,{queue:e,key:t}),a={version:0,encryptType:[Ts],command:Vt,payload:o,traceId:n()};return Ua(i,a)}encodeChatMessage(e,t){const s=Di(),r=s.lookupType("easemob.pb.MessageBody"),i=s.lookupType("easemob.pb.CommSyncUL"),o=s.lookupType("easemob.pb.MSync"),a=this.buildContent(e),c=this.resolveMessageProfileVersionFields(e),d=this.buildMessageMeta(e),l=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),u={type:this.resolveChatType(e),from:{name:this.context.userId},to:{name:l.name},contents:[a],ext:Bi(e.ext??{}),...d?{meta:d}:{},...c,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},h=Ua(r,u),p="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",m=this.resolveDirectedUsers(e),f=this.resolveMetaExt(e),g={id:t,to:xi({appKey:this.context.appKey,name:l.name,domain:p,clientResource:l.clientResource}),ns:Is,payload:h,routetype:this.resolveRouteType(e),directedUsers:m,ext:f,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}},y=Ua(i,{meta:g}),I={version:0,encryptType:[Ts],command:Vt,payload:y,traceId:n()};return Ua(o,I)}encodeActionMessage(e,t){const r=Di(),i=r.lookupType("easemob.pb.MessageBody"),o=r.lookupType("easemob.pb.CommSyncUL"),a=r.lookupType("easemob.pb.MSync"),c=r.lookupEnum("easemob.pb.MessageBody.EditScope"),d=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),l=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:d.name},contents:l,ext:Bi(e.ext??{})};"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?c.values.BODY_AND_EXT:c.values.BODY);const h=Ua(i,u);if("clearAllConversationUnreadMessageCount"===e.kind){const e=i.decode(h),n=i.fields.clearAllUnreadMessageCount;s.debug("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:u.type,fieldId:n?.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:xi({appKey:this.context.appKey,name:d.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:d.clientResource}),ns:Is,payload:h,routetype:Es,directedUsers:[],ext:[]},m=Ua(o,{meta:p}),f={version:0,encryptType:[Ts],command:Vt,payload:m,traceId:n()};return Ua(a,f)}encodeChatRoomOperation(e,t){const s=Di(),r=s.lookupType("easemob.pb.MUCBody"),i=s.lookupType("easemob.pb.CommSyncUL"),o=s.lookupType("easemob.pb.MSync"),a={mucId:xi({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&&(a.ext=e.ext),void 0!==e.leaveOtherRooms&&(a.leaveOtherRooms=e.leaveOtherRooms));const c=Ua(r,a),d={id:t,from:xi({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:vs,payload:c},l=Ua(i,{meta:d}),u={version:0,encryptType:[Ts],command:Vt,payload:l,traceId:n()};return Ua(o,u)}decodeServerMessageMeta(e){const t=Di(),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?vn(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(e=>{if(/^\d+$/.test(e))return e;const t=$e.fromString("1099511628211",!0);let s=$e.fromString("1469598103934665603",!0);for(let n=0;n<e.length;n+=1)s=s.xor($e.fromInt(e.charCodeAt(n),!0)).multiply(t).toUnsigned();return s.isZero()?"1":s.toString()})(e)}decodeChatRoomJoinInfo(e){const t=Di().lookupType("easemob.pb.MUCBody");for(const r of e){if(!_a(r)||r.ns!==vs)continue;const e=r.payload,i=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(i)try{const e=t.decode(i);if(!_a(e)||!_a(e.status))continue;const s=e.status.chatroomInfo;if("string"!=typeof s||""===s)continue;const n=JSON.parse(s);if(!_a(n))continue;const r=n[this.context.userId];if(!_a(r))continue;const o=r;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(n){s.error("Failed to decode chat room info from ACK",n)}}}decodeAck(e){const t=Fi(e.metaId);if(!t||"0"===t)return;const s=e.status??{},n="number"==typeof s.errorCode?s.errorCode:Rs,r="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:Fi(e.serverId),ok:n===Ms,statusCode:n,reason:r}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:$t;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=qi(t.ext),h=qi(e.ext),p=Number(Fi(e.timestamp))||Date.now(),m=Fi(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),I=this.resolveContentReplaced(y),v=this.resolveReactions(y),C=this.resolveModifiedInfo(y),S=this.resolveChatThreadMessageContext(y),E=this.resolveChatThreadOverview(y),b=this.resolveProfileVersionTime(t.userInfoUpdateTime),A=this.resolveProfileVersionTime(t.namecardUpdateTime),T={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)};lo(T,{userInfoUpdateTime:b,namecardUpdateTime:A});const w=this.decodeStreamMeta(t.stream,n);w&&(T.type="text",T.body={content:w.fullText},T.stream=w),void 0!==f&&(T.isBroadcast=f),void 0!==g&&(T.priority=g),void 0!==I&&(T.isContentReplaced=I),v&&(T.reactions=v),C&&(T.modifiedInfo=C),S&&(T.isChatThread=!0,T.chatThread=S);const N=this.resolvePeerRead(y,r,c);void 0!==N&&(T.isPeerRead=N);const M=this.resolveGroupReadCount(y,r);void 0!==M&&(T.groupReadCount=M),E&&(T.chatThreadOverview=E);const R=t.msgConfig;return R?.allowGroupAck&&(T.needReadReceipt=!0),T}resolveMessageProfileVersionFields(e){const t=uo(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 ot(Fi(e))}isPublicMessageType(e){return e===$t||e===Yt||e===Jt}resolveMessageIsOnline(e,t){if(e===Jt)return!0;const s=t.is_online;return"boolean"==typeof s?s:"number"==typeof s?0!==s:"string"!=typeof s||"0"!==s}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const s=e,n=Number(Fi(s.streamSeq));if(!Number.isFinite(n))return;const r="number"==typeof s.streamStatus?s.streamStatus:ms,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?Gt.ERROR:e===hs?Gt.START:e===ps?Gt.START_COMPLETED:e===fs?Gt.COMPLETED:e===gs?Gt.FULL:Gt.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(e){if("text"===e.type){const t=e.body;return{type:ns,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:ds,action:t.action}}if("custom"===e.type){const t=e.body;return{type:ls,customEvent:t.event,customExts:Bi(t.params??{})}}if("location"===e.type){const t=e.body;return{type:os,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:rs,displayName:t.filename,remotePath:t.originalImageUrl??"",imageType:r(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:is,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:as,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:ns,subType:0,text:we(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:cs,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,thumbnailDisplayName:t.filename}}decodeContent(e){const t="number"==typeof e.type?e.type:ns,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===us||t===ns&&(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===ns)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===ds)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===ls){const t=qi(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===os)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===rs){const t=e.size??{},s="number"==typeof t.width?t.width:0,n="number"==typeof t.height?t.height:0,r=i(e.imageType)===o,c="string"==typeof e.remotePath?e.remotePath:"",d=a(c,{deriveVariants:!this.useCustomAttachmentUpload}),l="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:d.originalImageUrl,bigImageUrl:d.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:l??d.thumbnailUrl}}}if(t===is){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===as){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===cs){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}resolveChatType(e){switch(e.conversationType){case"groupChat":return Yt;case"chatRoom":return Jt;default:return $t}}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=this.readJid(t.from),o=this.readJid(t.to),a=i.name??n.name??"",c=o.name??r.name??"";if(!("singleChat"===s&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:n.clientResource&&n.clientResource!==this.context.clientResource?`${a}/${n.clientResource}`:a,receiverId:r.clientResource?`${c}/${r.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return ts;case"sendMessageReadReceipts":return Xt;case"deliveryAck":return Zt;case"recall":return es;case"update":return ss;default:return $t}}resolveConversationType(e){return e===Yt?"groupChat":e===Jt?"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?Bi({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?As:this.resolveDeliverOnlineOnly(e)?bs:Es}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"}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(!_a(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(!_a(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(!_a(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(!_a(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=_a(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.context.userId?"SEND":"RECEIVE";return{msgServerId:s,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:h,conversationType:"groupChat",type:l,sendStatus:"sent",ext:_a(r?.ext)?r.ext:{},timestamp:n,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(_a(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=a(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:_a(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(Cn(t));return _a(e)?e:null}catch{return null}}if(_a(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return _a(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(_a).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}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[Ns]}configureCompression(e,t){if(!e||!e.includes(Ns))return void this.disableCompression();this.compressor||(this.compressor=new Ra);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===Na.UPLINK_ONLY||s===Na.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===Na.DOWNLINK_ONLY||s===Na.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Na.UPLINK_ONLY:1===e?Na.DOWNLINK_ONLY:2===e?Na.BIDIRECTIONAL:Na.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Na.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}class Oa{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.reconnectInProgress=!1,this.reconnectPaused=!1,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.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:d,autoReconnectNumMax:10,connectTimeout:c,...e},this.eventHub=t,this.msyncCodec=new Da({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:Ae.DISCONNECTED,serverUrl:this.config.serverUrl,userId:e.userId,token:e.token,reconnectAttempts:0},this.connectionRetry=new Ni({maxAttempts:this.config.autoReconnectNumMax,initialDelay:h,maxDelay:u,backoffMultiplier:l}),this.heartbeatManager=new _i({interval:this.config.heartBeatWait,timeout:p}),this.connectionEventNormalizer=new Sn,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[Ne.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,n){const r=Date.now();if(n<=r)throw new m("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,n,r),s.warn("Connection token renewed",{userId:this.config.userId,expireAt:n}),{token:t,expireAt:n}}handleOnline(){s.warn("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0;const e=this.offlineRecoverPending?Me.OFFLINE_RECOVER:Me.ONLINE;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){s.warn("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.stopHeartbeat(),this.closeWebSocket(Me.OFFLINE,!0),s.warn("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void s.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(Me.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Me.HEARTBEAT_FAILED)}}catch(t){if(s.warn("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(Me.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Me.HEARTBEAT_FAILED)}}resumeReconnect(e){this.isLoggedIn&&(this.reconnectInProgress?s.warn("Reconnect recovery skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.connection.status===Ae.CONNECTED&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),s.warn("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===Me.SEND_TIMEOUT&&s.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,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId}}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 m))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(Cn(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null)}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay();s.warn("Reconnect retry scheduled",{delayMs:Math.round(e),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise(t=>{this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,t()},e)})}buildConnectionEventPayload(e,t){const s=this.connection.error instanceof m?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===Ae.DISCONNECTED&&!this.hasEverConnected)return;if(e===Ae.RECONNECT_FAILED&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===Ae.DISCONNECTED||e===Ae.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,n,r=!1){const i=this.connection.status!==e;(i||r)&&(i&&(this.connection.status=e,this.connection.lastConnectedAt=e===Ae.CONNECTED?Date.now():void 0),n&&this.dispatchConnectionEvent(e,t),s.debug("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:r}))}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 s.warn("Provision auth token has invalid payload");const n=Number(t.expires_in);if(!Number.isFinite(n))return void s.warn("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,n)}catch(t){s.warn("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,s.warn("Token will expire"),this.eventHub.dispatch(Te.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,s.warn("Token expired"),this.eventHub.dispatch(Te.TOKEN_EXPIRED,void 0))}isTokenExpiredConnectionError(t){return t instanceof m&&t.code===e.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(t){s.warn("Connection closing because token expired",{source:t}),this.connection.error=new m("Token expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:t,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(Me.TOKEN_EXPIRED,!0,!0),this.updateStatus(Ae.DISCONNECTED,Me.TOKEN_EXPIRED,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(Me.HEARTBEAT_FAILED)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,p)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(){if(!this.reconnectInProgress)if(this.connection.status!==Ae.CONNECTED&&this.connection.status!==Ae.CONNECTING){this.isLoginPhase=!0,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(Me.LOGIN,!0),this.isLoggedIn=!0}catch(e){throw this.isLoggedIn=!1,e}finally{this.isLoginPhase=!1}}else s.warn("Connection already established or connecting")}async connectWithRetry(t,n){if(s.warn("Reconnect flow requested",{reason:t,throwOnFailure:n,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void s.warn("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:t,...this.getReconnectDiagnostic()});if(this.connection.status===Ae.CONNECTED&&this.websocket)return;if(this.reconnectPaused)return void s.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 r=null,i=null;const o=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),s.warn("Reconnect flow started",{reason:t,throwOnFailure:n,maxAttempts:o,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<o;){this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const e=this.isLoginPhase?Ae.CONNECTING:Ae.RECONNECTING;s.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(r=a,s.warn("Connection attempt failed",{attempt:this.reconnectAttempts,reason:t,error:r}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(r))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(r)){i=r;break}}if(this.connectionRetry.getAttemptCount()>=o)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){s.warn("Reconnect retry loop interrupted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,...this.getReconnectDiagnostic()});break}await this.waitForReconnectDelay()}if(i){if(this.connection.error=i,n)throw this.updateStatus(Ae.DISCONNECTED,Me.ERROR,!1),i;return this.reconnectPaused=!0,void this.updateStatus(Ae.DISCONNECTED,Me.ERROR,!0)}if(n)throw this.updateStatus(Ae.DISCONNECTED,Me.ERROR,!1),r??new m("Connection failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,s.warn("Reconnect attempts exhausted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,lastError:r,...this.getReconnectDiagnostic()}),this.updateStatus(Ae.RECONNECT_FAILED,Me.LIMIT,!0)}finally{this.reconnectInProgress=!1,s.warn("Reconnect flow finished",{reason:t,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(Me.RECONNECT,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(Ae.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),s.warn("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}async triggerReconnect(e){s.warn("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.isLoggedIn?this.reconnectInProgress?s.warn("Reconnect trigger skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.reconnectPaused?s.warn("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}):(this.connection.status===Ae.CONNECTED&&this.websocket&&this.closeWebSocket(e,!0,!0),await this.connectWithRetry(e,!1)):s.warn("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()})}handleDisconnection(e){s.warn("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(Ae.DISCONNECTED,e,!0),e!==Me.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(Ae.DISCONNECTED,e,t)):s&&this.updateStatus(Ae.DISCONNECTED,e,t)}createWebSocketConnection(){return new Promise((t,n)=>{const r=this.pickNextServerUrl();s.debug("WebSocket connecting",{url:r}),this.clearSocketListeners();let i=!1;const o=setTimeout(()=>{i=!0,s.warn("WebSocket connection attempt timed out",{url:r,connectTimeout:this.config.connectTimeout,...this.getReconnectDiagnostic()}),n(new m("Connection timeout",{code:e.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},this.config.connectTimeout);this.socketAdapter.connect({url:r,timeoutMs:this.config.connectTimeout}).then(e=>{if(clearTimeout(o),i||this.reconnectPaused)return s.warn("WebSocket connection result discarded",{url:r,cancelled:i,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void e.close();this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),this.startProvision().then(()=>{if(this.resetProvisionHandlers(),i||this.reconnectPaused)return s.warn("Provision result discarded",{url:r,cancelled:i,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void this.closeWebSocket(Me.ERROR,!1,!1);t()}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(Me.ERROR,!1,!1),n(e instanceof Error?e:new Error(String(e)))})}).catch(t=>{if(clearTimeout(o),i)return;const s=t instanceof m?t:new m("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});this.handleConnectionError(s,Me.ERROR),n(s)})}).catch(t=>{if(t instanceof m)throw t;const s=new m("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});throw this.handleConnectionError(s,Me.ERROR),s})}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(s.warn("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(Me.CLOSE))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new m("Provision interrupted",{code:e.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){if(s.error("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(t)}handleTerminalConnectionError(e,t){if(s.warn("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(Ae.DISCONNECTED,t,!0,!0)}async handleWebSocketMessage(t,n){try{if(n!==this.socketGeneration)return;s.debug("WebSocket message received",{dataType:typeof t});const i=await this.msyncCodec.normalizeIncoming(t);if(n!==this.socketGeneration)return;if(s.debug("handleWebSocketMessage data",{length:i.length}),!i.length)return;const o=this.msyncCodec.decompressIncoming(i);if(!o){const t=null!==this.provisionReject;return s.error("Failed to decompress mSync payload, closing connection",{stage:t?"provision":"connected"}),void(t?(this.rejectPendingProvision(new m("Failed to decompress Provision payload",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(Me.ERROR,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(o))return void s.debug("Ignore server normal close payload",{length:o.length});let a=null;try{a=this.msyncCodec.decodeMsync(o)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void s.warn("Discard invalid mSync payload",{length:o.length,message:e.message,prefixHex:Array.from(o.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(o.subarray(Math.max(0,o.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw s.warn("Invalid mSync payload signature",{length:o.length,prefixHex:Array.from(o.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),s.debug("handleWebSocketMessage decoded",{command:a.command}),a.command){case jt:this.handleProvisionMessage(a.payload);break;case Wt:this.handleLogoutMessage(a.payload);break;case zt:this.handleNoticeMessage(a.payload);break;case Ht:this.handleUnreadMessage(a.payload);break;case Vt:this.handleSyncMessage(a.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");s.error("Failed to handle mSync payload",e),this.handleConnectionError(e,Me.ERROR)}}startProvision(){this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(new m("Provision timeout",{code:e.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},f);try{const e=this.msyncCodec.encodeProvision();s.debug("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new m("Provision send failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(t){const n=this.msyncCodec.decodeProvision(t);if(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),n.ok)this.msyncCodec.updateResource(n.resource),this.setupTokenLifecycleFromProvision(n.authToken),this.provisionResolve?.();else{s.warn("Provision rejected",{statusCode:n.statusCode,reason:n.reason});const t=yn(n.statusCode,n.reason),r=t.code===e.UNKNOWN?e.CONNECTION_PROVISION_REJECTED:t.code;this.provisionReject?.(new m("Provision rejected",{code:r,details:{stage:"provision",reason:n.reason,statusCode:n.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),n=t.filter(e=>this.getQueueId(e));if(n.length){n.length!==t.length&&s.warn("Unread queues without usable identity were ignored",{ignoredCount:t.length-n.length}),this.startOfflineMessageSync(n);for(const e of n)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,Me.ERROR);if(!this.messageReceiver)return;const n=this.messageReceiver.handleSyncPayload(e);if(s.debug("handleSyncMessage result",{result:n}),!n)return;(void 0!==n.queue||void 0!==n.nextKey||void 0!==n.isLast)&&this.handleSyncQueueState(n)}handleSyncQueueState(e){s.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:n,queueId:r}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(r)){const t=this.offlineMessageQueueCounts.get(r)??0;this.offlineMessageQueueCounts.set(r,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const i=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(r),this.removeQueueEntry(n),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(i){if(i!==this.nextKey||!this.isSameQueue(n,this.currentQueue))return this.nextKey=i,this.currentQueueId=r,this.currentQueue=n,void this.sendLastSession(n,i);this.removeQueueEntry(n),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,n=t?this.getQueueName(t):null,r=t?this.getQueueId(t):null,i=void 0!==t&&null!==r&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&r&&i)return{queue:t,queueId:r};const o=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,a=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,c=o??a??this.queues[0],d=c?this.getQueueName(c):null,l=c?this.getQueueId(c):null;return c&&l?(s.warn("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:n,responseQueueId:r,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);s.warn("Logout message received",t)}resolveStatisticDisconnectError(t){for(const s of t)switch(s.operation){case 1:return new m("User has been removed",{code:e.USER_REMOVED,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 2:return new m("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 m("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 m("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.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.offlineRecoverPending=!1,this.closeWebSocket(Me.CLOSE,!0,!0),this.updateStatus(Ae.DISCONNECTED,Me.CLOSE,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),s.warn("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){if(e.socketAdapter)return e.socketAdapter;const t=lr({webSocketCtor:"function"==typeof WebSocket?WebSocket:void 0});if(t)return t;throw Ge("Socket capability is missing for current platform",{code:"PLATFORM_MISSING_CAPABILITY",stage:"socket",retryable:!1,details:{capability:"socket"}})}attachSocketListeners(t,n){this.clearSocketListeners(),this.socketDisposers=[t.onMessage(e=>{this.websocket===t&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(e,n)))}),t.onError(()=>{if(this.websocket!==t)return;s.warn("WebSocket error",{stage:"ws"});const n=new m("WebSocket connection error",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(n,Me.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===He.OPEN)try{const t=this.msyncCodec.prepareOutgoing(e);s.debug("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{s.error("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){s.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);s.debug("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){s.debug("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const n=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(n)}sendNextQueue(){s.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=g({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(Te.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(Te.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]),ka=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Pa=e=>Array.isArray(e)&&e.every(ka),xa=e=>"string"==typeof e?e:void 0,Fa=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Ba=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},qa=(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 I("Combine payload length header is invalid",{code:e.COMBINE_PARSE_FAILED});return n<<24|r<<16|i<<8|o},Ga=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},Ka=(e,t)=>{const s=Di().lookupType(e).decode(t);if(!ka(s))throw new Error(`${e} decoded result is invalid`);return s},Va=e=>ka(e)&&"string"==typeof e.name?e.name:"",Ha=(e,t,s)=>{const n=(Pa(e.contents)?e.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const r=(e=>{const t=Fa(e.type)??ns,s=Boolean(xa(e.remotePath))||Boolean(xa(e.title))||Boolean(xa(e.summary))||(Fa(e.combineLevel)??0)>0,n=t===ns&&0===e.subType&&s;if(t===us||n){const t=Fa(e.combineLevel)??0;return{type:"combine",body:{title:xa(e.title)??"",summary:xa(e.summary)??"",filename:xa(e.displayName)??"combine",filetype:"application/octet-stream",url:xa(e.remotePath),secret:xa(e.secretKey),fileLength:Fa(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ns)return{type:"text",body:{content:xa(e.text)??""}};if(t===ds)return{type:"cmd",body:{action:xa(e.action)??""}};if(t===ls){const t=qi(Pa(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:xa(e.customEvent)??"",params:t}}}if(t===os)return{type:"location",body:{latitude:Fa(e.latitude)??0,longitude:Fa(e.longitude)??0,address:xa(e.address),buildingName:xa(e.buildingName)}};if(t===rs){const t=ka(e.size)?e.size:{},s=xa(e.remotePath)??"",n=a(s),r=xa(e.thumbnailRemotePath),c=i(e.imageType)===o;return{type:"image",body:{localUrl:"",filename:xa(e.displayName)??"image",filetype:"application/octet-stream",width:Fa(t.width)??0,height:Fa(t.height)??0,isGif:1===e.subType,isOriginalImage:c,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:xa(e.secretKey),fileLength:Fa(e.fileLength),thumbnailUrl:r??n.thumbnailUrl}}}if(t===is){const t=ka(e.size)?e.size:{};return{type:"video",body:{url:xa(e.remotePath)??"",filename:xa(e.displayName)??"video",filetype:"application/octet-stream",duration:Fa(e.duration)??0,width:Fa(t.width),height:Fa(t.height),secret:xa(e.secretKey),fileLength:Fa(e.fileLength),thumbnailUrl:xa(e.thumbnailRemotePath)}}}if(t===as)return{type:"voice",body:{url:xa(e.remotePath)??"",filename:xa(e.displayName)??"voice",filetype:"application/octet-stream",duration:Fa(e.duration)??0,secret:xa(e.secretKey),fileLength:Fa(e.fileLength)}};if(t===cs)return{type:"file",body:{url:xa(e.remotePath)??"",filename:xa(e.displayName)??"file",filetype:"application/octet-stream",secret:xa(e.secretKey),fileLength:Fa(e.fileLength)}};return null})(n);if(!r)throw new Error("MessageBody content type is unsupported");const c=Va(e.from)||Va(s?.from)||`unknown-${t}`,d=Va(e.to)||Va(s?.to)||`unknown-${t}`,l=(u=e.type)===Yt?"groupChat":u===Jt?"chatRoom":"singleChat";var u;const h=d||c,p=Number(Fi(s?.timestamp))||Date.now(),m=qi(Pa(e.ext)?e.ext:void 0),f={msgServerId:Fi(s?.id),msgLocalId:"",type:r.type,sender:{userId:c},conversationId:h,conversationType:l,timestamp:p,body:r.body,ext:m};return"number"==typeof r.combineLevel&&(f.body.combineLevel=r.combineLevel),f},za=(e,t)=>{const s=[];try{const r=Ka("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=Ka("easemob.pb.MessageBody",i);return Ha(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=Ka("easemob.pb.MessageBody",e);return Ha(s,t)}catch(r){s.push(r instanceof Error?r.message:String(r))}try{const s=Ka("easemob.pb.MessageBody.Content",e);return Ha({type:$t,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("; "))},ja=(t,s)=>{const n=Cn(t);try{const t=JSON.parse(n);if(!ka(t))throw new I("Combine payload item is invalid",{code:e.COMBINE_PARSE_FAILED,details:{index:s}});return t}catch(r){if(r instanceof I)throw r;try{return za(t,s)}catch(i){throw new I("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)}})}}},Wa=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Qa{constructor(e,t,s,n){this.websocket=null,this.pendingMessages=/* @__PURE__ */new Map,this.ackTimeout=v,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,n){const r=this.msyncCodec.toProtocolId(t.msgLocalId);if(Kt(t))throw new y("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==He.OPEN){const s=this.msyncCodec.toProtocolId(t.msgLocalId);throw new y("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:s,retryable:!0}})}let i={...t,sendStatus:"sending"};ho(t,i),s.debug("Message send queued",{msgLocalId:t.msgLocalId,protocolId:r,type:t.type,conversationType:t.conversationType,conversationId:t.conversationId});try{const e="combine"===i.type?this.prepareCombineMessage(i):i,t={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,n):e,sendStatus:"sending"};ho(i,t),i=t,n?.onSending?.(t);const s=await this.doSendMessage(t);return n?.onSuccess?.(s),s}catch(o){const e={...i,sendStatus:"failed"};throw ho(i,e),n?.onFailed?.(e,o instanceof Error?o:new Error(String(o))),o}}async sendAction(e,t){const n=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&s.debug("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:n,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const r=this.msyncCodec.encodeActionMessage(e,n);"clearAllConversationUnreadMessageCount"===e.kind&&s.debug("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:n,payloadBytes:r.byteLength});const i="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(n,r,t,this.createPendingDataReport({category:"message",operationName:i,operationType:"MESSAGE",requestName:i,msgId:e.messageId,messageType:Wa(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 n=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:t.msgLocalId,messageType:Wa(t.conversationType)});return new Promise((r,i)=>{const o=this.msyncCodec.toProtocolId(t.msgLocalId),a=setTimeout(()=>{this.pendingMessages.delete(o),this.finishPendingDataReport(n,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),i(new y("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(o,{kind:"message",message:t,protocolId:o,timeoutId:a,resolve:e=>{clearTimeout(a),r(e)},reject:e=>{clearTimeout(a),i(e)},report:n});try{if(!this.websocket||this.websocket.readyState!==He.OPEN)throw new y("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(t,o),c=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(c)).catch(r=>{const c=r instanceof Error?r.message:String(r);this.pendingMessages.delete(o),clearTimeout(a),this.finishPendingDataReport(n,{code:-1,success:!1,description:c}),s.warn("Message send socket failure",{msgLocalId:t.msgLocalId,protocolId:o,websocketReadyState:this.websocket?.readyState??null,cause:c}),i(new y(`WebSocket send failed: ${c}`,{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0,cause:c}}))}),s.debug("Message sent",{msgLocalId:t.msgLocalId,protocolId:o})}catch(c){if(this.pendingMessages.delete(o),clearTimeout(a),this.finishPendingDataReport(n,{code:c instanceof y?c.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:c instanceof Error?c.message:String(c)}),c instanceof y)throw c;throw new y("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0}})}})}async sendProtocolPayload(t,s,n,r){return new Promise((i,o)=>{const a=setTimeout(()=>{this.pendingMessages.delete(t),this.finishPendingDataReport(r,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),o(new y("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{protocolId:t,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(t,{kind:"action",protocolId:t,timeoutId:a,createAckError:n,resolve:i,reject:o,report:r});try{if(!this.websocket||this.websocket.readyState!==He.OPEN)throw new y("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(a),this.finishPendingDataReport(r,{code:-1,success:!1,description:n}),o(new y(`WebSocket action send failed: ${n}`,{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0,cause:n}}))})}catch(c){if(this.pendingMessages.delete(t),clearTimeout(a),this.finishPendingDataReport(r,{code:c instanceof y?c.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:c instanceof Error?c.message:String(c)}),c instanceof y)throw c;o(new y("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{protocolId:t,retryable:!1}}))}})}prepareCombineMessage(t){const s=t.body,n=s.messageList??[];Re(n);const r=_e(n);Ue(r);const i=(t=>{try{const s=t.map((t,s)=>{const n=JSON.stringify(t);if(!n)throw new y("Combine payload item encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{index:s}});return vn(n)}),n=La.length+s.reduce((e,t)=>e+4+t.length,0)+1,r=new Uint8Array(n);let i=0;r.set(La,i),i+=La.length;for(const e of s){const t=Ba(e.length);r.set(t,i),i+=t.length,r.set(e,i),i+=e.length}const o=Ga(r.subarray(0,r.length-1));return r[r.length-1]=o,r}catch(s){if(s instanceof y)throw s;throw new y("Combine payload encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{cause:s instanceof Error?s.message:String(s)}})}})(n),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=De(a);if(!c&&!this.attachmentUploader)throw new y("Combine payload local url generation failed",{code:e.COMBINE_ENCODE_FAILED});Oe.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 ho(t,d),Le(t,d),d}handleAck(e,t,n,r){const i=this.pendingMessages.get(e);if(!i)return void s.debug("Received ACK without a tracked pending message",{protocolId:e});if("action"===i.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(i.report,{code:200,success:!0}),void i.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:r});const o={...i.message,...this.resolveReplacedMessage(i.message,n),sendStatus:"sent",msgServerId:t||n?.msgServerId||i.message.msgServerId};ho(i.message,o),this.pendingMessages.delete(e),this.finishPendingDataReport(i.report,{code:200,success:!0}),"image"!==o.type&&"video"!==o.type&&"voice"!==o.type&&"file"!==o.type&&"combine"!==o.type||Oe.delete(o.msgLocalId),s.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(Ne.MESSAGE_SENT,o),i.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 n=this.pendingMessages.get(e);if(!n)return;if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t instanceof y?t.code:-1,success:!1,description:t.message}),void n.reject(t);const r={...n.message,sendStatus:"failed"};ho(n.message,r),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t instanceof y?t.code:-1,success:!1,description:t.message}),s.warn("Message send failed after ACK/error",{protocolId:e,msgLocalId:r.msgLocalId,type:r.type,conversationType:r.conversationType,conversationId:r.conversationId,error:t.message}),n.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 y("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)>=C){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(s.warn("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=g({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<C&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<C&&(this.chatRoomReportSaturated=!1)))}}class $a{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!==Gt.START&&t.stream.status!==Gt.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 Ya{constructor(e,t){this.completedIds=/* @__PURE__ */new Set,this.eventHub=e,this.cache=t??new $a}handle(e){const t=this.resolveMessageId(e);if(!t)return void s.warn("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void s.debug("stream message already completed, ignore",{msgId:t});if(e.stream.status===Gt.FULL)return void this.handleFullChunk(t,e);const n=this.cache.get(t);if(n?.completed)return void s.debug("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:r}=this.cache.addChunk(t,e);r?s.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?Gt.ERROR:s.stream.status,a=this.buildDispatchMessage(s,{status:o,fullText:i,deltaText:r});if(this.eventHub.dispatch(Ze.STREAM_MESSAGE,a),this.cache.markDispatched(e,s,i),o===Gt.START_COMPLETED||o===Gt.COMPLETED||o===Gt.ERROR){const t=o===Gt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else s.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?Gt.ERROR:o?Gt.START_COMPLETED:Gt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:r,deltaText:i});this.eventHub.dispatch(Ze.STREAM_MESSAGE,c);const d=a===Gt.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:Gt.ERROR,fullText:r,deltaText:i});this.eventHub.dispatch(Ze.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 Ja{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 Xa=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Za{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new Ya(s),this.messageContexts=/* @__PURE__ */new Map,this.recentMessageIds=new Ja(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{s.debug("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);s.debug("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:n,messages:r}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),n&&(s.debug("Decoded sync ACK",{ok:n.ok,protocolId:n.protocolId,serverId:n.serverId??null,statusCode:n.statusCode??null,reason:n.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(n,t.replacedMessage));for(const e of r)this.dispatchMessage(e);return t}catch(t){s.error("Failed to decode sync payload",t)}return null}handleAck(t,n){if(t.ok)return s.debug("ACK accepted",{protocolId:t.protocolId,serverId:t.serverId??null,hasReplacedMessage:Boolean(n)}),void(t.chatRoomInfo?this.messageSender.handleAck(t.protocolId,t.serverId,n,t.chatRoomInfo):this.messageSender.handleAck(t.protocolId,t.serverId,n));s.warn("ACK rejected",{protocolId:t.protocolId,statusCode:t.statusCode,reason:t.reason,hasReplacedMessage:Boolean(n)});const r=((t,s)=>{const n=yn(t,s),r=n.code===e.UNKNOWN?e.MESSAGE_SEND_FAILED:n.code;return{code:r,message:In[r]??(s?`Message send failed: ${s}`:"Message send failed for an unknown reason"),retryable:n.retryable}})(t.statusCode,t.reason),i=new y(r.message,{code:r.code,details:{protocolId:t.protocolId,serverCode:t.statusCode,reason:t.reason,retryable:!1}});this.messageSender.handleAckFailure(t.protocolId,t.statusCode,t.reason,i)}dispatchMessage(e){if(Kt(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?s.debug("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(Ze.MESSAGE,e),s.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=>{s.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(Ze.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(Ne.USER_INFO_NOTIFY,a)}handleContactNotify(e){if(s.debug("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==et.INVITED&&e.eventName!==et.DELETED&&e.eventName!==et.ADDED&&e.eventName!==et.REFUSE&&e.eventName!==et.AGREED)return;const t=e.data;if(!t||"object"!=typeof t)return;const n=t;"string"==typeof n.from&&n.from&&"string"==typeof n.to&&n.to&&"string"==typeof n.message&&this.eventHub.dispatch(e.eventName,n)}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(tt.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(Ne.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(Ne.CHATROOM_NOTIFY,s)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const s of t){if(!Xa(s)||"string"!=typeof s.messageId)continue;const e=this.resolveReactionConversationContext(s);e&&this.eventHub.dispatch(Ze.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(!Xa(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(Ze.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(!Xa(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(!Xa(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(!Xa(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(!Xa(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(Ze.MESSAGE_DELIVERED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!Xa(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(Ze.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(!Xa(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Xa(t.message)||"string"!=typeof t.message.type||!Xa(t.message.body)||!Xa(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Xa(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(Ze.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(Ne.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)Xa(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)!Xa(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 ec=e=>e instanceof Error?e.message:String(e);class tc{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?nr({fetchImpl:fetch}):void 0))(e)}async downloadAndParse(t){const s=t.url.trim();if(!s)throw new S("Combine message url is required",{code:e.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof t.maxItems?t.maxItems:ke;Pe(1,r);const i=this.requestAdapter;if(!i)throw new I("Request adapter is required for combine message download",{code:e.COMBINE_DOWNLOAD_FAILED});const o=E(s,t.secret);try{const s=await i.request({url:o,method:"GET",responseType:"arraybuffer",timeoutMs:t.timeoutMs??15e3,headers:{[b]:n()}});if(401===s.status||403===s.status)throw new A(401===s.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===s.status?e.AUTH_UNAUTHORIZED:e.AUTH_FORBIDDEN,details:{url:o,httpStatus:s.status}});if(s.status>=400)throw new I("Combine payload download failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{status:s.status,url:o}});const a=(t=>{if(t.length<La.length+1)throw new I("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 I("Combine payload header is invalid",{code:e.COMBINE_PARSE_FAILED});const n=t.subarray(0,t.length-1),r=Ga(n),i=t[t.length-1]??0;if(i!==r)throw new I("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 I("Combine payload length header is incomplete",{code:e.COMBINE_PARSE_FAILED});const s=qa(t,a);if(a+=4,s<=0||a+s>c)throw new I("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=ja(n,o.length);o.push(r)}if(a!==c)throw new I("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 vn(t);throw new I("Combine payload response type is invalid",{code:e.COMBINE_DOWNLOAD_FAILED})})(s.data));return Pe(a.length,r),Re(a),a.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(a){if(a instanceof S||a instanceof A||a instanceof I)throw a;throw new I("Combine payload download or parse failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{cause:ec(a),url:o}})}}}const sc=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"}},nc=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 rc{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?nr({fetchImpl:fetch}):void 0))(e)}async download(t,s=15e3){if("image"!==t.type&&"video"!==t.type&&"voice"!==t.type&&"file"!==t.type)throw new S("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:r,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(!r)throw new S("attachment url is required",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});if(!this.requestAdapter)throw new T("request adapter is required for attachment download");const o=await this.requestAdapter.request({url:E(r,i),method:"GET",responseType:"arraybuffer",timeoutMs:s,headers:{[b]:n()}});if(401===o.status)throw new A("attachment download unauthorized",{code:e.AUTH_UNAUTHORIZED,details:{url:r,httpStatus:o.status}});if(403===o.status)throw new A("attachment download forbidden",{code:e.AUTH_FORBIDDEN,details:{url:r,httpStatus:o.status}});if(404===o.status){const t=("string"==typeof o.data?o.data:"").includes("expired");throw new w(t?"attachment file is expired":"attachment not found",t?e.ATTACHMENT_EXPIRED:e.ATTACHMENT_NOT_FOUND)}if(429===o.status)throw new w("attachment download rate limited",e.SERVICE_LIMIT_EXCEEDED);if(o.status>=400)throw new w("attachment download failed",e.FILE_DOWNLOAD_FAILED,{details:{status:o.status,url:r}});return{filename:sc(t),mimeType:nc(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:r}}}const ic=(e,t,s)=>({Authorization:`Bearer ${e}`,Accept:t,[b]:n(),...s??{}}),oc=async t=>{const n=ic(t.token,"application/json",t.headers),r=Date.now(),i="upload.multipart.init"===t.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===t.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",o=t.dataReportOperation?.startRequest({requestName:i,method:t.method,url:t.url});let a=0;if(s.debug("Upload request start",{operation:t.operation,method:t.method}),t.requestAdapter)try{const i=await t.requestAdapter.request({url:t.url,method:t.method,headers:n,responseType:"json",timeoutMs:L});a=i.status;const d=Date.now()-r;if(i.status<200||i.status>=300)throw s.warn("Upload response error",{operation:t.operation,method:t.method,status:i.status,duration:d}),new M("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:i.status}});s.debug("Upload response success",{operation:t.operation,method:t.method,status:i.status,duration:d});const l="string"==typeof(c=i.data)?JSON.parse(c):c;return o?.finish({code:i.status,success:!0}),l}catch(u){if(o?.finish({code:0!==a?a:u instanceof M?u.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:u instanceof Error?u.message:String(u)}),u instanceof M)throw u;throw s.warn("Upload request failed",{operation:t.operation,method:t.method}),new M("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}var c;const d=new AbortController,l=setTimeout(()=>d.abort(),L);try{const i=await fetch(t.url,{method:t.method,headers:n,signal:d.signal});a=i.status;const c=Date.now()-r;if(!i.ok)throw s.warn("Upload response error",{operation:t.operation,method:t.method,status:i.status,duration:c}),new M("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:i.status}});return s.debug("Upload response success",{operation:t.operation,method:t.method,status:i.status,duration:c}),o?.finish({code:i.status,success:!0}),await i.json()}catch(u){if(o?.finish({code:0!==a?a:u instanceof M?u.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:u instanceof Error?u.message:String(u)}),u instanceof M)throw u;if(u instanceof Error&&"AbortError"===u.name)throw s.warn("Upload request timeout",{operation:t.operation,method:t.method,timeout:L}),new M("Upload timeout",{code:e.UPLOAD_TIMEOUT,details:{url:t.url,timeout:L}});throw s.warn("Upload request failed",{operation:t.operation,method:t.method}),new M("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}finally{clearTimeout(l)}},ac=(t,n,r,i,o,a)=>new Promise((c,d)=>{const l=new XMLHttpRequest,u=Date.now(),h=a?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:t});s.debug("Upload part start",{operation:"upload.multipart.part",partNumber:r}),l.upload&&o&&l.upload.addEventListener("progress",e=>{o(e.loaded)},!1),l.addEventListener("abort",()=>{h?.finish({code:e.UPLOAD_ABORTED,success:!1,description:"Upload aborted"}),s.warn("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),d(new M("Upload aborted",{code:e.UPLOAD_ABORTED,details:{url:t,partNumber:r}}))},!1),l.addEventListener("error",()=>{h?.finish({code:e.UPLOAD_REQUEST_FAILED,success:!1,description:"Upload part failed"}),s.warn("Upload part failed",{operation:"upload.multipart.part",partNumber:r}),d(new M("Upload part failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t,partNumber:r}}))},!1),l.addEventListener("timeout",()=>{h?.finish({code:e.UPLOAD_TIMEOUT,success:!1,description:"Upload timeout"}),s.warn("Upload part timeout",{operation:"upload.multipart.part",partNumber:r,timeout:L}),d(new M("Upload timeout",{code:e.UPLOAD_TIMEOUT,details:{url:t,partNumber:r}}))},!1),l.addEventListener("load",()=>{const n=Date.now()-u;if(200!==l.status)return h?.finish({code:l.status,success:!1,description:"Upload part failed"}),s.warn("Upload part error",{operation:"upload.multipart.part",partNumber:r,status:l.status,duration:n}),void d(new M("Upload part failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t,partNumber:r,status:l.status}}));s.debug("Upload part success",{operation:"upload.multipart.part",partNumber:r,duration:n}),h?.finish({code:l.status,success:!0}),c()},!1);const p=new FormData;p.append("part_file",i),p.append("part_number",r),l.timeout=L,l.open("PUT",t),Object.entries(ic(n,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{l.setRequestHeader(e,t)}),l.send(p)}),cc=async t=>{if(t.fileSize<=N)throw new M("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,{orgName:m,appName:f}=R(s.appKey),g=`${s.restBaseUrl}/${m}/${f}/sdk/chatfiles/part-upload`;let y;try{y=await oc({url:g,method:"POST",token:s.token,operation:"upload.multipart.init",requestAdapter:s.requestAdapter,dataReportOperation:t.dataReportOperation})}catch(F){throw new M("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:F,url:g}})}const I=(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:k,i="string"==typeof s?.uuid?s.uuid:"";if(!i)throw new M("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{fileMaxSize:n,partMinSize:r,uuid:i}})(y);if(I.fileMaxSize&&c>I.fileMaxSize)throw new M("File size exceeds limit",{code:e.UPLOAD_SIZE_EXCEEDED,details:{fileSize:c,maxSize:I.fileMaxSize}});const v=I.partMinSize||k,C=Math.ceil(c/v),S=Array.from({length:C},()=>0),E=`${s.restBaseUrl}/${m}/${f}/sdk/chatfiles/part-upload/${I.uuid}`,b=[],A=(e,s)=>{S[e]=s;const n=S.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<C;e+=1){const r=e*v,i=Math.min(c,r+v),o=n.slice(r,i),a=String(e+1),d=ac(E,s.token,a,o,t=>A(e,t),t.dataReportOperation).finally(()=>{const e=b.indexOf(d);e>=0&&b.splice(e,1)});b.push(d),b.length>=_&&await Promise.race(b)}await Promise.all(b);const T=P(i),w=U(`${s.restBaseUrl}/${m}/${f}/sdk/chatfiles/part-upload/${I.uuid}`,{"restrict-access":"true","chat-type":T,"chat-target":r,"thumbnail-width":t.thumbnailWidth,"thumbnail-height":t.thumbnailHeight,md5:u??"",..."image"===d?{imageType:D(l),width:h,height:p}:{}}),L=await oc({url:w,method:"POST",token:s.token,operation:"upload.multipart.complete",requestAdapter:s.requestAdapter,dataReportOperation:t.dataReportOperation}),x=O({response:L,restBaseUrl:s.restBaseUrl,orgName:m,appName:f,fileType:a,fileName:o,fallbackSize:c,messageType:d,imageType:l,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(x),x},dc=t=>new Promise((r,i)=>{const{config:o,file:a,conversationId:c,conversationType:d,messageType:l,imageType:u,md5:h,width:p,height:m,fileName:f,fileType:g,fileSize:y}=t,{orgName:I,appName:v}=R(o.appKey),C=P(d),S=U(`${o.restBaseUrl}/${I}/${v}/chatfiles`,{"chat-type":C,"chat-target":c,md5:h??"",..."image"===l?{imageType:D(u),width:p,height:m}:{}}),E=Date.now(),A=t.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:S});s.debug("Upload request start",{operation:"upload.simple",method:"POST",fileSize:y,messageType:l});const T=new XMLHttpRequest;T.upload&&t.callbacks?.onFileUploadProgress&&T.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.callbacks?.onFileUploadProgress?.({loaded:e.loaded});const s=e.total?e.loaded/e.total*100:void 0;t.callbacks?.onFileUploadProgress?.({loaded:e.loaded,total:e.total,percent:s})},!1),T.addEventListener("abort",()=>{A?.finish({code:e.UPLOAD_ABORTED,success:!1,description:"Upload canceled"}),s.warn("Upload request aborted",{operation:"upload.simple"}),t.callbacks?.onFileUploadCanceled?.(),i(new M("Upload canceled",{code:e.UPLOAD_ABORTED,details:{url:S}}))},!1),T.addEventListener("error",()=>{A?.finish({code:e.UPLOAD_REQUEST_FAILED,success:!1,description:"Upload failed"}),s.warn("Upload request failed",{operation:"upload.simple"}),i(new M("Upload failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:S}}))},!1),T.addEventListener("timeout",()=>{A?.finish({code:e.UPLOAD_TIMEOUT,success:!1,description:"Upload timeout"}),s.warn("Upload request timeout",{operation:"upload.simple",timeout:L}),i(new M("Upload timeout",{code:e.UPLOAD_TIMEOUT,details:{url:S,timeout:L}}))},!1),T.addEventListener("load",()=>{try{const n=Date.now()-E,i=JSON.parse(T.responseText);if(T.status>=400)throw A?.finish({code:T.status,success:!1,description:"Upload failed"}),s.warn("Upload response error",{operation:"upload.simple",status:T.status,duration:n}),new M("Upload failed",{code:e.UPLOAD_REQUEST_FAILED,details:{status:T.status,response:i}});s.debug("Upload response success",{operation:"upload.simple",status:T.status,duration:n});const a=O({response:i,restBaseUrl:o.restBaseUrl,orgName:I,appName:v,fileType:g,fileName:f,fallbackSize:y,messageType:l,imageType:u,useCustomAttachmentUpload:o.useCustomAttachmentUpload});t.callbacks?.onFileUploadComplete?.(a),A?.finish({code:T.status||200,success:!0}),r(a)}catch(n){A?.finish({code:n instanceof M?n.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:n instanceof Error?n.message:String(n)}),i(n instanceof Error?n:new Error(String(n)))}},!1),T.timeout=L,T.open("POST",S),T.setRequestHeader("restrict-access","true"),T.setRequestHeader("Accept","*/*"),T.setRequestHeader("Authorization",`Bearer ${o.token}`),T.setRequestHeader(b,n());const w=new FormData;w.append("file",a,f),void 0!==t.thumbnailWidth&&w.append("thumbnail-width",String(t.thumbnailWidth)),void 0!==t.thumbnailHeight&&w.append("thumbnail-height",String(t.thumbnailHeight)),T.send(w)}),lc=_r(),uc=e=>Object.prototype.toString.call(e),hc=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:uc(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}},pc=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}),mc=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,fc=e=>"object"==typeof e&&null!==e,gc=(e,t)=>{const s=fc(t)?t:void 0,n=s?.code===Ke.MISSING_CAPABILITY&&s.stage===Ve.RUNTIME;return"miniapp-path"===e&&(e=>{if(!fc(e))return!1;const t=fc(e.details)?e.details:void 0;return e.code===Ke.MISSING_CAPABILITY&&e.stage===Ve.RUNTIME&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&n};class yc{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(t,n){if(!mc(t.type))return t;const r=t.body;if(this.hasUploadedRemoteResource(t.type,r))return t;const i=this.resolveUploadUrl(t.type,r),o=Oe.get(t.msgLocalId),a=Boolean(o);if(s.warn("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:t.msgLocalId,messageType:t.type,conversationType:t.conversationType,hasFile:a,uploadUrl:i,cachedFile:hc(o),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}}),!x(i,a))return t;if(!o)throw new M("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:t.msgLocalId,url:i}});if(!this.config?.restBaseUrl)throw new M("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,r,o),c.precheck?.hit||(l=g({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:t.msgLocalId,messageType:t.type})),d=c.precheck?.hit?this.buildPrecheckedUploadResult(t,c,n):await this.uploadAttachment(t,c,n,l),l?.finish({code:0,success:!0})}catch(u){const t=ze(u);throw l?.finish({code:t.code,success:!1,description:t.message}),t.code===e.UPLOAD_ABORTED&&n?.onFileUploadCanceled?.(),n?.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&&F(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&F(t.url)}async prepareAttachmentUpload(e,t,n){const r=B(n,t);if(s.warn("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:pc(r)}),"image"!==e.type){return{body:t,fileInfo:r,md5FileInfo:r,precheck:await this.maybePrecheck(e,r,r,void 0)}}const i=t,a=await this.resolveImageCandidate(i,r),c={...i,width:a.width,height:a.height,isOriginalImage:a.imagePolicy.resolvedImageType===o},d=await this.maybePrecheck(e,a.fileInfo,r,a.imagePolicy.resolvedImageType);return{body:c,fileInfo:a.fileInfo,md5FileInfo:r,imageType:a.imagePolicy.resolvedImageType,precheck:d,originalWidth:i.width,originalHeight:i.height}}async resolveImageCandidate(e,t){const n=q(e);if(s.warn("Image send policy resolved",{operation:"upload.image.policy",reason:n.reason,imageType:n.resolvedImageType,isGif:e.isGif,source:pc(t)}),n.resolvedImageType===o){let r=e.width,i=e.height;if(!r||!i){const e=this.resolveImageProcessor(t.source.sourceType);s.warn("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:pc(t)});const n=await e.getImageInfo(t.source);r=n.width,i=n.height}return{imagePolicy:n,sourceKind:"origin",fileInfo:t,width:r,height:i}}try{const e=this.resolveImageProcessor(t.source.sourceType);s.warn("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:pc(t)});const r=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:n,sourceKind:"big",fileInfo:{source:r.source,fileName:r.fileName??t.fileName,fileType:r.fileType??t.fileType,fileSize:r.fileSize??t.fileSize,webFile:r.webFile},width:r.width,height:r.height}}catch(r){return s.warn("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:n.reason,error:r instanceof Error?r.message:String(r),source:pc(t)}),{imagePolicy:{resolvedImageType:o,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,n,r){if(!mc(e.type))return;if(!0!==this.config?.enableMd5Check)return void s.debug("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:r,fileSize:t.fileSize});const i=G({messageType:e.type,fileSize:t.fileSize,imageType:r});if(!i.shouldPrecheck)return void s.debug("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:r,fileSize:t.fileSize,thresholdBytes:i.thresholdBytes});let o;try{o=await this.computeMd5(n)}catch(c){if(gc(n.source.sourceType,c))return void s.warn("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:r,thresholdType:i.thresholdType,source:pc(n),error:c instanceof Error?c.message:String(c)});throw c}const a=await this.requestPrecheck(e,i.thresholdType,o,r);return s.debug(a.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:a.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:r,exists:a.exists,existsType:a.existsType,uuid:a.uuid,hasShareSecret:"string"==typeof a.shareSecret&&a.shareSecret.length>0}),{...a,md5:o}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return s.warn("Attachment md5 compute start",{operation:"upload.md5.start",source:pc(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return s.warn("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return s.warn("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),lc;throw s.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),Ge("Image processor capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(t,n,r,i){if(!this.config)throw new M("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:o,appName:a}=R(this.config.appKey),c=U(`${this.config.restBaseUrl}/${o}/${a}/chatfiles/exists`,{md5:r,..."image"===t.type?{imageType:D(i)}:{}}),d=await this.requestJson({url:c,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(e=>{s.warn("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:t.type,imageType:i,thresholdType:n,md5:r,error:e instanceof Error?e.message:String(e)})});return d?K(d):{exists:!1,hit:!1}}async requestJson(e){return this.config?.requestAdapter?this.requestByAdapter(this.config.requestAdapter,e):this.requestByFetch(e)}async requestByAdapter(t,s){const n=await t.request({url:s.url,method:s.method,headers:s.headers,responseType:"json",timeoutMs:L});if(n.status>=400)throw new M("Upload precheck request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:n.status,operation:s.operation}});return n.data}async requestByFetch(t){if("function"!=typeof fetch)throw Ge("Request capability is missing for current platform",{code:Ke.MISSING_CAPABILITY,stage:Ve.REQUEST,retryable:!1,details:{operation:t.operation}});const s=new AbortController,n=setTimeout(()=>s.abort(),L);try{const n=await fetch(t.url,{method:t.method,headers:t.headers,signal:s.signal});if(!n.ok)throw new M("Upload precheck request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:n.status,operation:t.operation}});return await n.json()}finally{clearTimeout(n)}}buildPrecheckedUploadResult(t,s,n){if(!this.config||!s.precheck)throw new M("Precheck result is required",{code:e.UPLOAD_REQUEST_FAILED});if(!s.precheck.uuid)throw new M("Precheck hit missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{precheck:s.precheck}});if(!mc(t.type))throw new M("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const{orgName:r,appName:i}=R(this.config.appKey),a="image"===t.type?s.precheck.existsType??s.imageType:void 0,c="image"===t.type&&a===o?s.md5FileInfo:s.fileInfo,d="image"===t.type&&a===o?s.originalWidth:"image"===t.type?s.body.width:void 0,l="image"===t.type&&a===o?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=O({response:u,restBaseUrl:this.config.restBaseUrl,orgName:r,appName:i,fileType:c.fileType,fileName:c.fileName,fallbackSize:c.fileSize,messageType:t.type,imageType:a,width:d,height:l,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(h),h}async uploadAttachment(t,n,r,i){if(!this.config)throw new M("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});if(!mc(t.type))throw new M("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const o=t.type,a=await this.resolveUploadMetadata(o,n);if(this.config.uploadAdapter)return s.warn("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:o,source:pc(n.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,t,n,a,r);if(!n.fileInfo.webFile)throw new M("Upload adapter is required for non-web file source",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:n.fileInfo.source.sourceType}});const c={message:t,file:n.fileInfo.webFile,conversationId:t.conversationId,conversationType:t.conversationType,messageType:o,imageType:n.imageType,md5:a.md5,width:a.width,height:a.height,fileName:n.fileInfo.fileName,fileType:n.fileInfo.fileType,fileSize:n.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(o,n.body),thumbnailHeight:this.resolveThumbnailHeight(o,n.body),callbacks:r,config:this.config,dataReportOperation:i},d=!1!==this.config?.enableMultipartUpload,l=d&&n.fileInfo.fileSize>N;if(s.warn("Attachment web upload selected",{operation:"upload.web.selected",messageType:o,source:pc(n.fileInfo),multipartEnabled:d,uploadMode:l?"multipart":"simple"}),l)try{return await cc(c)}catch(u){const e=u instanceof M?u.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return dc(c);throw u}return dc(c)}async uploadByAdapter(t,r,i,o,a){if(!this.config)throw new M("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:c,appName:d}=R(this.config.appKey),l=P(r.conversationType);if(!mc(r.type))throw new M("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:r.type}});const u=r.type,h=U(`${this.config.restBaseUrl}/${c}/${d}/chatfiles`,{"chat-type":l,"chat-target":r.conversationId,md5:o.md5,..."image"===u?{imageType:D(i.imageType),width:o.width,height:o.height}:{}}),p={},m={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[b]:n()},f=this.resolveThumbnailWidth(u,i.body),g=this.resolveThumbnailHeight(u,i.body);void 0!==f&&(p["thumbnail-width"]=String(f)),void 0!==g&&(p["thumbnail-height"]=String(g)),s.warn("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:u,source:pc(i.fileInfo),uploadUrl:h,fields:p});const y=await t.upload({url:h,headers:m,source:i.fileInfo.source,fields:p,onProgress:e=>{a?.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 M("Upload failed",{code:s,details:{status:y.status,response:y.body}})}let I;try{I=JSON.parse(y.body)}catch(C){throw new M("Upload response parse failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:y.body,cause:C instanceof Error?C.message:String(C)}})}const v=O({response:I,restBaseUrl:this.config.restBaseUrl,orgName:c,appName:d,fileType:i.fileInfo.fileType,fileName:i.fileInfo.fileName,fallbackSize:i.fileInfo.fileSize,messageType:u,imageType:i.imageType,width:o.width,height:o.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return a?.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 ho(e,r),Le(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 ho(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 ho(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 ho(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 ho(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 n=t.precheck?.md5??"";if(!t.precheck)try{n=await this.computeMd5(t.md5FileInfo)}catch(i){if(!gc(t.md5FileInfo.source.sourceType,i))throw i;s.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:pc(t.md5FileInfo),error:i instanceof Error?i.message:String(i)})}const r=t.body;return{md5:n,width:"image"===e&&"number"==typeof r.width&&r.width>0?r.width:void 0,height:"image"===e&&"number"==typeof r.height&&r.height>0?r.height:void 0}}}class Ic{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 vc="__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 Oa({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),n=e.restBaseUrl?new yc({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 Qa(s,null,this.eventHub,n),this.messageReceiver=new Za(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new tc(e.platformAdapter?.request),this.attachmentDownloader=new rc(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(vc,{[Te.CONNECTED]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[Te.DISCONNECTED]:e=>{this.messageSender.setWebSocket(null)},[Te.RECONNECT_FAILED]:e=>{this.messageSender.setWebSocket(null)},[Ne.MESSAGE_SENT]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new Ic(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(){return this.connectionManager.connect()}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}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(vc),Oe.clear()}}const Sc=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)},Ec=e=>{const t=atob(e),s=new Uint8Array(new ArrayBuffer(t.length));for(let n=0;n<t.length;n+=1)s[n]=t.charCodeAt(n);return s};class bc{getCrypto(){return t().crypto}constructor(e,s){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 s=Pn(e);if("web"!==s.framework&&"worker"!==s.framework&&s.platform!==qe.ELECTRON_RENDERER)return!1;const n=e.crypto;return void 0!==n&&void 0!==n.subtle&&"function"==typeof n.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const t=`${e}:${s}`;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:Sc(n),ct:Sc(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=Ec(t.iv),n=Ec(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 Ac="conversationMap",Tc="userInfoMap",wc="groupNamecardMap",Nc="contactRelationMap",Mc="contactVersion",Rc="contactMeta",_c="sessionListMap",Uc="sessionListCheckpoint",Dc="joinedGroupPreview",Oc="metadata",Lc=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class kc{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 Pc=()=>{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 xc{constructor(e,t){this.storage=t??xc.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!xc.checkAvailable())return null;const e=Pc();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=Pc();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 dt(n,t)}catch(n){return s.warn("CacheStore read failed",n),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,n){if(!this.storage)return;const r=lt(t);if(null!==r)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(r):r;await this.storage.setItem(e,t)}catch(i){if(Kr(i))throw i;if(n)throw i;s.warn("CacheStore write failed",i)}else if(n)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){s.warn("CacheStore remove failed",t)}}}const Fc={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Bc={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class qc{constructor(){this.items=/* @__PURE__ */new Map,this.versionState=Fc,this.meta=Bc}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(!ut(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 ut(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"}:Fc}normalizeMeta(e){return ut(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"}:Bc}}const Gc=(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}},Kc=(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}},Vc=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 Hc{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=Gc(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=Kc(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:Vc(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(!ut(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=ut(e.body)?e.body:{},i="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,o="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:s,body:r,timestamp:n,userInfoUpdateTime:i,namecardUpdateTime:o}:null}}const zc=(e,t)=>`${e}:${t}`;class jc{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(zc(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,n){const r=zc(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(zc(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=zc(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(zc(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=Gc(r,e,t),o=new Set(i.removed.map(e=>zc(e.groupId,e.userId)));this.items.clear();for(const a of n)o.has(zc(a.groupId,a.userId))||this.items.set(zc(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=Kc(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>zc(e.groupId,e.userId)));this.items.clear();for(const o of s)i.has(zc(o.groupId,o.userId))||this.items.set(zc(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||!ut(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 Wc=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Qc=e=>{const t={...e};return delete t.type,t},$c=e=>{if(!ut(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!ut(e.body))return null;const s=((e,t)=>{if(ut(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=Wc(e.conversationType),r=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),i=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),o=(e=>{if(ut(e)&&"string"==typeof e.operatorId&&"number"==typeof e.operationCount&&"number"==typeof e.operationTime)return{operatorId:e.operatorId,operationCount:e.operationCount,operationTime:e.operationTime}})(e.modifiedInfo),a="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,c="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return{msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:s,body:Qc(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...n?{conversationType:n}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...r?{sendStatus:r}:{},...i?{direct:i}:{},...o?{modifiedInfo:o}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Yc=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},Jc=(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 Xc{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(Jc)}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(Jc)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!ut(e))return null;const s=e,n="string"==typeof s.conversationId?s.conversationId:"";if(!n)return null;const r=Wc(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:$c(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:Yc(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 Zc{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=Gc(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=Kc(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(!ut(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 ed=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,td=e=>e.lastMessageAt??e.updatedAt,sd=e=>[...e].sort((e,t)=>{const s=ed(t)-ed(e);if(0!==s)return s;const n=td(t)-td(e);return 0!==n?n:e.conversationId.localeCompare(t.conversationId)}),nd=e=>`${e.conversationType}:${e.conversationId}`,rd=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,id=(e,t)=>((e,t)=>td(t)>td(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:rd(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(nd(i));for(const i of e.existing)t.set(nd(i),i);const n=e.snapshot.map(e=>{const s=t.get(nd(e));return s?id(e,s):e}),r=e.existing.filter(t=>!s.has(nd(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return sd([...n,...r])},ad=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],cd=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),dd=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 ld{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,ad.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 ud=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class hd{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 bc(e.appKey,e.userId);this.store=new xc(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Lc(s,Ac),this.userInfoKey=Lc(s,Tc),this.groupNamecardKey=Lc(s,wc),this.sessionListKey=Lc(s,_c),this.sessionListCheckpointKey=Lc(s,Uc),this.joinedGroupPreviewKey=Lc(s,Dc),this.contactRelationKey=Lc(s,Nc),this.contactVersionKey=Lc(s,Mc),this.contactMetaKey=Lc(s,Rc),this.metadataKey=Lc(s,Oc),this.metadataStore=new kc(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Hc,this.userInfoCache=new Zc,this.groupNamecardCache=new jc,this.sessionListCache=new Xc,this.joinedGroupPreviewCache=new nt,this.contactCache=new qc,this.userInfoRuntimeStore=new ld,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 nt;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?cd(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([dd(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})}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=nd(e.nextRecord),s=e.existing.filter(e=>nd(e)!==t);return sd([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&&ut(r)&&Array.isArray(r.items)?r.items:[];this.sessionListCache.load(i,e);const o=(r&&ut(r)&&ut(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&&ut(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&ut(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 r=6;for(let i=0;i<=r;i+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!Kr(t))return this.restoreDirtyBatch(e),void s.warn("Cache flush failed",t);const r=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,r),"none"===r)return void s.warn("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(r)}catch(n){if(!Kr(n))return this.restoreDirtyBatch(e),void s.warn("Cache quota cleanup persistence failed",n)}}s.warn("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of ud)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=>ed(e)>0),s=/* @__PURE__ */new Map;for(const r of e.incoming)s.set(nd(r),r);const n=t.length>0?e.existing.filter(e=>!s.has(nd(e))&&0===ed(e)):e.existing.filter(e=>!s.has(nd(e)));return sd([...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=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",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=uo(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{msgId:e.msgServerId||e.msgLocalId,type:e.type,body:this.normalizeMessageBody(e.body),timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return e&&"object"==typeof e&&!Array.isArray(e)?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="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,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?{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}: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?cd(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=t?`${t.msgServerId}:${t.from}:${t.to}:${t.conversationId}:${t.conversationType}:${t.type}:${t.sendStatus??""}:${t.direct??""}:${t.sender.userId}:${t.sender.nickname??""}:${t.sender.avatarUrl??""}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",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 pd{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,n){try{const r=n(t);return this.isPromiseLike(r)?Promise.resolve(r).then(()=>{}).catch(t=>{s.error(`Event handler error for ${e}`,t)}):null}catch(r){return s.error(`Event handler error for ${e}`,r),null}}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const md={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function fd(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 gd(e){return new Promise(t=>setTimeout(t,e))}const yd=e=>{const t={...e};return delete t.type,t},Id=(e,t)=>{const s=e.lastMessage;if(!s)return null;const n=((e,t)=>{const s=t.getCurrentUserId?.()??"",n="singleChat"===e.type?e.conversationId:"";return{from:n,to:"singleChat"===e.type?s:e.conversationId,sender:{userId:n}}})(e,t);return{msgServerId:s.msgId,from:n.from,to:n.to,sender:n.sender,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof s.type&&s.type.length>0?s.type:"text",timestamp:s.timestamp,body:yd(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},vd=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},dd=async(e,t)=>{const s=await cd(e,t);return e.map(e=>((e,t,s)=>{const n=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),r=((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),i="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,n,r):"groupChat"===e.type?(o=e.conversationId,a=s.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:o}):(e=>({conversationName:e}))(e.conversationId);var o,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:ad(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:i.conversationName,conversationAvatar:i.conversationAvatar}})(e,t,s))};class ld{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 T("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 T("Session-list sync requestId mismatch",e.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:t.requestId}});if(this.isTerminal())throw new T("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 ud=0,hd=5,pd=10,md=11,fd=1,gd=2,yd=1,Id=2,vd=3,Cd=e=>e===fd?"groupChat":e===gd?"chatRoom":"singleChat",Sd=()=>Si().lookupType("easemob.pb.MessageBody"),Ed=e=>{const t=Sd().toObject(Sd().decode(e),{longs:Number,bytes:Uint8Array}),s=Array.isArray(t.contents)?t.contents:[],n=(r=s[0])&&"object"==typeof r&&!Array.isArray(r)?r:{};var r;const i="number"==typeof n.type?n.type:0;return 0===i?{type:"text",content:"string"==typeof n.text?n.text:""}:1===i?{type:"image",filename:"string"==typeof n.displayName?n.displayName:"image",remotePath:"string"==typeof n.remotePath?n.remotePath:""}:2===i?{type:"video",filename:"string"==typeof n.displayName?n.displayName:"video",remotePath:"string"==typeof n.remotePath?n.remotePath:""}:3===i?{type:"location",latitude:"number"==typeof n.latitude?n.latitude:0,longitude:"number"==typeof n.longitude?n.longitude:0,address:"string"==typeof n.address?n.address:void 0}:4===i?{type:"voice",filename:"string"==typeof n.displayName?n.displayName:"voice",remotePath:"string"==typeof n.remotePath?n.remotePath:"",duration:"number"==typeof n.duration?n.duration:0}:5===i?{type:"file",filename:"string"==typeof n.displayName?n.displayName:"file",remotePath:"string"==typeof n.remotePath?n.remotePath:""}:6===i?{type:"cmd",action:"string"==typeof n.action?n.action:""}:7===i?{type:"custom",event:"string"==typeof n.customEvent?n.customEvent:""}:8===i?{type:"combine",title:"string"==typeof n.title?n.title:"",summary:"string"==typeof n.summary?n.summary:""}:{}},bd=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}},Ad=e=>{const t={...e};return delete t.type,t},Td=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,wd=(e,t,s)=>{if(!e)return null;const n=(e=>{if(!e)return"";const t=e.lastIndexOf("_");return t>=0?e.slice(t+1):e})(e.from?.name),r={userId:n};return"singleChat"===s.conversationType&&n===s.conversationId&&s.singleChatPeerDisplay&&(s.singleChatPeerDisplay.conversationName!==n&&(r.nickname=s.singleChatPeerDisplay.conversationName),s.singleChatPeerDisplay.conversationAvatar&&(r.avatarUrl=s.singleChatPeerDisplay.conversationAvatar)),{msgServerId:e.id??"",from:n,to:Td({conversationId:s.conversationId,conversationType:s.conversationType,from:n,currentUserId:s.currentUserId}),sender:r,conversationId:s.conversationId,conversationType:s.conversationType,type:(i=t.type,"text"===i||"image"===i||"file"===i||"voice"===i||"video"===i||"location"===i||"custom"===i||"cmd"===i||"combine"===i?i:"text"),timestamp:e.timestamp??0,body:Ad(t)};var i},Nd=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},Md=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return Ed(e)}catch{return{}}})(e.last_message?.payload),n=e.session_id??"",r=Cd(e.session_type),i=(e=>{const t=e.session_id??"",s=Cd(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:bd(e)})(e);return{conversationId:n,conversationType:r,unreadCount:e.unread_count??0,lastMessage:wd(e.last_message,s,{conversationId:n,conversationType:r,currentUserId:t,singleChatPeerDisplay:"singleChat"===r?i:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:Nd(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===yd?"ALL":o===Id?"AT":o===vd?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),Rd={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 _d=null,Ud=!1;const Dd=()=>_d||(Ud||(Qe.util.Long=$e,Qe.configure(),Ud=!0),We(),_d=Qe.Root.fromJSON(Rd),Je(_d),_d),Ld=e=>Dd().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}},kd=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}},Pd=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}},xd=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:Pd(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 Fd{constructor(){this.requestType=Ld("easemob.sessionlist.GetSessionListRequest"),this.responseType=Ld("easemob.sessionlist.GetSessionListResponse"),this.errorType=Ld("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:ud}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=Od(t.type);return s!==pd?null:{type:s,header:kd(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!==md?null:{type:s,header:kd(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:xd(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!==hd?null:{type:s,header:kd(t.header),code:Od(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Bd=async s=>{const n=s.client.getCacheManager(),r=s.client.getRestContext(),i=s.client.getSessionListSyncWsUrls();if(!n||0===i.length)throw new p("session-list sync websocket is unavailable",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[o,a]=r.appKey.split("#");if(!o||!a)throw new C("session-list appKey is invalid",{code:e.VALIDATION_INVALID_FORMAT,details:{appKey:r.appKey}});const c=n.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:s.session.getRequestId(),resource:r.clientResource,org:o,app:a,username:r.userId,lastSyncTime:(l=c.sessionsLastSyncTs,Math.max(0,l-K)),params:s.params});var l;const u=new Fd;let h=0,m=c.sessionsLastSyncTs;return await s.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:s.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:n=>{if(5===n.type&&"code"in n&&"message"in n)throw 1002===(i=n).code?new b(i.message,{code:e.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:i.code}}):1003===i.code?new T(i.message,e.SERVER_BUSY,{details:{protocol:"session-list",responseCode:i.code}}):1501===i.code||1001===i.code?new C(i.message,{code:e.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:i.code}}):1503===i.code?new T(i.message,e.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:i.code}}):(i.code,new T(i.message,e.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:i.code}}));var i;if(11!==n.type)throw new T("session-list response type is invalid",e.MESSAGE_DECODE_FAILED,{details:{responseType:n.type}});const o=n,a=o.header?.requestId;if(a&&a!==s.session.getRequestId())return;h+=1,t.debug("Decoded session-list sync raw response",{requestId:s.session.getRequestId(),batchSequence:h,response:o});const c=Md(o,r.userId),d=s.session.pushBatch({requestId:s.session.getRequestId(),batchSequence:h,sessions:c,isLastBatch:!0===o.isLastBatch,lastSyncFinishedTs:o.lastSyncFinishedTs});if("number"==typeof o.lastSyncFinishedTs&&(m=o.lastSyncFinishedTs),!d.done)return;return{done:!0,result:{items:s.session.getItems(),lastSyncFinishedTs:m}}}})},qd=()=>Date.now(),Gd={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Kd=(e,t)=>({status:e,determinedAt:qd(),reason:t}),Vd=t=>t instanceof T&&(t.code===e.SERVER_BUSY||1103===t.code),Hd=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Vd(e)});class zd{constructor(e){this.running=null,this.currentSession=null,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}refresh(e){return this.running||(this.currentSession=new ld,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[];this.client.emitSyncDataStart("conversation");const r=await this.tryDirectFallback(n);if(r)return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),r;try{const e=n.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let r=0;const o=await async function(e,t,s={}){const n={...nd,...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=rd(o,n);await id(e)}throw r}(async()=>{r+=1;const e=1===r?t:this.createRetrySession();e.start();try{return await Bd({client:this.client,session:e,params:s})}catch(n){throw e.fail(),n}},Vd,Gd),a={result:o,syncStartedAt:t.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:qd()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:qd()};try{await n.commitSessionListSync({items:c,mode:e,checkpoint:d,syncStartedAt:a.syncStartedAt})}catch(i){t.fail();const e=new V("Session-list final persistence failed",{details:{cause:i instanceof Error?i.message:String(i)}});return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Hd(e)}),n.loadSessionList()}const l=n.loadSessionList();return n.updateConversationsFromServer(l.map(at),{syncStartedAt:a.syncStartedAt}),await n.flushPending(),this.client.emitConversationListUpdate("conversation","full"===e),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),l}catch(i){const s=i instanceof T?i:new T(i instanceof Error?i.message:String(i));t.fail();const r=(t=>t.code===e.OPERATION_UNSUPPORTED||t.code===e.AUTH_UNAUTHORIZED?{capabilityState:Kd("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 o=await this.buildFallbackSessionList(n);return r.shouldUseFallback&&n.replaceSessionList(o),this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Hd(s)}),o}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}var t;const s=Boolean(this.client.getServerUrlsConfig()?.syncWsUrl),n=this.client.isSessionListDnsProbeAvailable();if(!s&&!n){this.capabilityState=Kd("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new ld}async buildFallbackSessionList(e){return await(async(e,t)=>await dd(e,t))(e.loadConversationSummaries(),this.client)}}const jd=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Wd=async t=>{if("string"==typeof t||jd(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):jd(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 T("sync websocket frame payload type is invalid",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof t}})},Qd=e=>{const t=Math.max(e-1,0),s=$*Math.pow(Y,t);return Math.min(s,Q)},$d=async e=>{await new Promise(t=>{setTimeout(t,e)})},Yd=e=>e instanceof Error?e:new Error(String(e));class Jd{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 T("sync websocket session is cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:t.requestId}});if(this.pending.has(t.requestId))throw new T("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,Yd(n))}return await s}cancel(t="sync-websocket-cancelled"){this.cancelled=!0;const s=new T("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!==He.OPEN){if(this.connectPromise)return await this.connectPromise;this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let s=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&t.warn("sync websocket retry started",this.buildLogContext({reason:s?.message}));try{return void(await this.openSocket())}catch(n){if(s=Yd(n),this.cancelled||0===this.pending.size)throw s;if(this.attempt>=3)throw t.warn("sync websocket retry exhausted",this.buildLogContext({reason:s.message})),s;const e=Qd(this.attempt);t.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:e,reason:s.message})),await $d(e)}}throw new p("sync websocket retry exhausted",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:s?.message??"unknown"}})}async openSocket(){const s=await this.getUrls();if(0===s.length)throw new p("sync websocket urls are unavailable",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const n=s[this.urlIndex%s.length];if(this.urlIndex+=1,!n)throw new p("sync websocket url is invalid",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=n,this.state="connecting",t.warn("sync websocket connect started",this.buildLogContext());const r=Te(),i=this.socketAdapter??ir({webSocketCtor:r.WebSocket});if(!i)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let o=null;try{const e=await Promise.race([i.connect({url:n}),new Promise((e,t)=>{o=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},H)})]);o&&clearTimeout(o),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(),t.warn("sync websocket connected",this.buildLogContext())}catch(a){if(o&&clearTimeout(o),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),a instanceof p)throw a;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:a instanceof Error?a.message:String(a)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await Wd(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Yd(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(s){const n=[];let r=null;for(const e of this.pending.values())try{const t=e.decode(s);if(t.requestId&&t.requestId===e.requestId){try{const s=await e.onFrame(t.frame,this.socket);s?.done&&(this.pending.delete(e.requestId),e.resolve(s.result),this.closeIfComplete())}catch(i){this.pending.delete(e.requestId),e.reject(Yd(i)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:e,frame:t.frame})}catch(i){n.push(Yd(i))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&n.length===this.pending.size)throw new T("sync websocket frame decode failed",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:n[0]?.message}});return t.warn("sync websocket frame ignored",this.buildLogContext({reason:n[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?(t.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(Yd(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===He.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)}))}),t.warn("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(s){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:s instanceof Error?s.message:String(s)}))}}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||(t.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"))},j))}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>=He.CLOSING||(this.state="closing",s.close(e,t))}buildConnectionError(t,s,n={}){return new p(t,{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:s,url:this.activeUrl,...n}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:W(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const Xd=async(t,s,n)=>{const{orgName:r,appName:i}=M(t.appKey),o=`/${r}/${i}/user/${encodeURIComponent(t.userId)}/roster/metadata/version`,a=new J(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(ht(t))return ht(t.data)?r(t.data):r(t);throw new C("Invalid contact metadata response",{code:e.VALIDATION_INVALID_FORMAT,details:{payload:t}})})(await a.get(o),s)}catch(c){if(c instanceof C)throw c;const t=c instanceof T&&c.details?c.details:{};throw new X("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 T?c.code:void 0}})}},Zd=e=>pt.string().regex(/^https?:\/\/\S+$/i,e),el=e=>pt.string().regex(/^wss?:\/\/\S+$/i,e),tl=pt.object({appKey:pt.string().min(1,"appKey is required"),enableUserInfoSync:pt.boolean().optional(),enableSyncData:pt.array(pt.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:pt.boolean().optional(),deleteConversationOnGroupDestroyed:pt.boolean().optional(),syncConversationListConfig:pt.object({includeEmpty:pt.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:pt.boolean().optional(),useFixedDeviceId:pt.boolean().optional(),deviceId:pt.string().min(1,"deviceId is required").optional(),serviceConfig:pt.object({dnsConfigUrls:pt.array(Zd("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:pt.object({restApiUrl:Zd("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:el("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:Zd("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:el("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:pt.boolean().optional(),customDeviceName:pt.string().min(1,"customDeviceName is required").optional(),customOSPlatform:pt.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:pt.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:pt.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:pt.array(pt.unknown()).optional(),platformAdapterOptions:pt.object({prefer:pt.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:pt.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:pt.custom(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{"enableMd5Check"in e&&t.addIssue({code:pt.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:pt.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:pt.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:pt.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:pt.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:pt.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:pt.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&n&&t.addIssue({code:pt.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(n?.restApiUrl||t.addIssue({code:pt.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:pt.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),sl=pt.object({userId:pt.string().min(1,"userId is required"),token:pt.string().min(1,"token is required")}),nl=pt.string().trim().min(1,"token is required"),rl=pt.object({channelName:pt.string().trim().min(1,"channelName is required").optional()}).optional(),il=pt.array(pt.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))),ol=pt.object({protocol:pt.string(),domain:pt.string().optional(),ip:pt.string().optional(),port:pt.union([pt.string(),pt.number()]).optional()}).passthrough(),al=pt.object({rest:pt.object({hosts:pt.array(ol).nonempty()}),"msync-wx":pt.object({hosts:pt.array(ol).nonempty()}),"sync-ws":pt.object({hosts:pt.array(ol).nonempty()}).optional(),enableReportLogs:pt.enum(["true","false"]).optional(),reportInterval:pt.number().positive().finite().optional(),enableDataReport:pt.enum(["true","false"]).optional(),enableMd5Check:pt.enum(["true","false"]).optional(),uploadinparts_enable:pt.enum(["true","false"]).optional()}).passthrough(),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"],ll=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function ul(e){return"object"==typeof e&&null!==e}function hl(e){return Array.isArray(e)?{hosts:e}:function(e){return ul(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function pl(e,t,s){for(const n of t){const t=hl(e[n]);if(t)return{key:n,section:t}}for(const[n,r]of Object.entries(e)){if(!s(n))continue;const e=hl(r);if(e)return{key:n,section:e}}}function ml(e){if(!ul(e))return Fe.validateOrThrow(al,e);const s=hl(e.rest),n=pl(e,dl,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),r=pl(e,ll,e=>{const t=e.toLowerCase();return!t.includes("msync")&&t.includes("sync")&&(t.includes("ws")||t.includes("socket"))}),i={...e,rest:s??e.rest,"msync-wx":n?.section};r?.section?i["sync-ws"]=r.section:"sync-ws"in i&&!hl(i["sync-ws"])&&delete i["sync-ws"];const o="true"===(a=e.enableReportLogs)||!0===a?"true":"false"===a||!1===a?"false":void 0;var a;o&&(i.enableReportLogs=o);const c=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!==c?i.reportInterval=c:delete i.reportInterval;const d=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);d?i.enableDataReport=d:delete i.enableDataReport;const l=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);l?i.enableMd5Check=l:delete i.enableMd5Check;const u=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return u?i.uploadinparts_enable=u:delete i.uploadinparts_enable,n&&"msync-wx"!==n.key&&t.warn("DNS config websocket section normalized",{sourceKey:n.key}),r&&"sync-ws"!==r.key&&t.warn("DNS config sync websocket section normalized",{sourceKey:r.key}),Fe.validateOrThrow(al,i)}function fl(t,s){const n=t.domain||t.ip;if(!n)throw new C("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 gl(e,t){return"https"===e?"https":"http"===e?"http":t}function yl(t,s){const n=t.domain||t.ip;if(!n)throw new C("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 Il(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function vl(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 Cl(e,t,s){const n=new J(e,{requestAdapter:s,includeRequestId:!0});let r="/easemob/server.json",i=!0;try{const t=new URL(e),s=""!==t.pathname&&"/"!==t.pathname,n=""!==t.search;(s||n)&&(r="",i=!1)}catch{r="/easemob/server.json",i=!0}if(i){r=`${r}?${new URLSearchParams({app_key:t,_v:String(Date.now())}).toString()}`}return ml(await n.get(r))}function Sl(t,s){const n=t["sync-ws"];return n&&Array.isArray(n.hosts)?n.hosts.map(t=>function(t,s){const n=t.domain||t.ip;if(!n)throw new C("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}`}(t,gl(t.protocol,s))).filter(e=>"string"==typeof e&&e.length>0):[]}async function El(s){const n=s.baseUrls&&s.baseUrls.length>0?s.baseUrls:cl;if(0===n.length)throw new C("DNS_CONFIG list is empty",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=s.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let i;for(const c of n)try{const t=await Cl(c,s.appKey,s.requestAdapter),n=vl(Il(t["msync-wx"].hosts,r));if(0===n.length)throw new C("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 i=n[0];if(!i)throw new C("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 o=Il(t.rest.hosts,r);if(0===o.length)throw new C("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 a=o[0];if(!a)throw new C("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 d=n.map(e=>fl(e,gl(e.protocol,r))),l=fl(i,gl(i.protocol,r)),u=Sl(t,r);return{websocketUrl:l,websocketUrls:d,syncWebsocketUrls:u,baseUrl:c,restBaseUrl:yl(a,gl(a.protocol,r)),dnsConfig:t}}catch(a){t.warn("DNS config candidate failed",{baseUrl:c,reason:a instanceof Error?a.message:String(a),error:a instanceof Error&&"function"==typeof a.toJSON?a.toJSON():a}),i=a}const o={stage:"dns"};throw i&&(o.reason=i.message,"code"in i&&"number"==typeof i.code&&(o.causeCode=i.code)),new p("DNS_CONFIG exhausted",{code:e.CONNECTION_DNSLIST_FAILED,details:o})}const bl=t=>new C(t,{code:e.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),Al=e=>{if(!ht(e))throw bl("Invalid REST response");return ht(e.data)?e.data:e},Tl=(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}}},wl=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},Nl=e=>{const{orgName:t,appName:s}=M(e.appKey);return`/${t}/${s}`},Ml=async(e,t)=>{const s=await e.get((e=>`${Nl(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Al(e),s=Tl(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw bl("Invalid token expires response");return s})(s)},Rl=async(e,t,s)=>{const n=await e.get(((e,t)=>{const s=new URLSearchParams({channelName:t?.channelName??"*"});return`${Nl(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${s.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=Al(e);return{appId:wl(t,["app_id","appId"])??"",rtcToken:wl(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:wl(t,["channel_name","channelName"])??"",rtcUid:Tl(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:Tl(t,["expires_in","expire","expireAt"])??0}})(n)},_l=async(e,t,s)=>{const n=await e.post((e=>`${Nl(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Al(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)},Ul=async(e,t)=>{const s=await e.get((e=>`${Nl(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=ht(e)&&Array.isArray(e.data)?e.data:[],n=[];for(const r of s){if(!ht(r))continue;const e=wl(r,["res","resource","clientResource"]);e&&e!==t.clientResource&&n.push(`${t.userId}/${e}`)}return n})(s,t)};class Dl{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 s=this.readyGroups.splice(e,1)[0];if(!s)return;this.activeGroupCount+=1,this.activeGroups.add(s.groupId),Promise.resolve(this.options.onFlushGroup(s)).catch(e=>{t.warn("Group namecard hydration queue flush failed",{groupId:s.groupId,userIds:s.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(s.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 Ll{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 n=this.generation;this.activeCount+=1;const r=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let i;try{i=Promise.resolve(this.options.onFlush(r))}catch(s){i=Promise.reject(s instanceof Error?s:new Error(String(s)))}i.catch(s=>{const r=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(t.warn("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:r.length>0,error:s instanceof Error?s.message:String(s)}),n===this.generation&&0!==r.length){for(const e of r)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)}}const Ol=Ie(ve,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),kl=class s{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=be.DISCONNECTED,this.loginAttempt=0,this.currentUserId=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.config={appKey:e.appKey,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.config.platformAdapterOptions&&(this.platformAdapter=mi(this.config.platformAdapterOptions)),this.managerRegistry=/* @__PURE__ */new Map,this.managerCapabilities=/* @__PURE__ */new Map,this.eventHub=new sd,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 Ll({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:ee,maxRetries:Z,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Dl({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:se,maxBatchSize:te,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[Ae.CONNECTING]:e=>{this.updateState(e.state)},[Ae.CONNECTED]:e=>{this.updateState(e.state)},[Ae.DISCONNECTED]:e=>{this.updateState(e.state)},[Ae.RECONNECT_FAILED]:e=>{this.updateState(e.state)},[Ze.MESSAGE]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[Ze.STREAM_MESSAGE]:e=>{this.handleIncomingConversationStreamMessage(e)},[Ne.MESSAGE_SENT]:e=>{this.handleOutgoingConversationMessage(e)},[Ze.MULTI_DEVICE_CONTACT]:e=>{this.handleMultiDeviceContactEvent(e)},[Ze.MULTI_DEVICE_CONVERSATION]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[et.ADDED]:e=>this.handleIncomingContactRosterEvent("add",e),[et.AGREED]:e=>this.handleIncomingContactRosterEvent("add",e),[et.INVITED]:e=>this.handleIncomingContactRosterEvent("none",e),[et.REFUSE]:e=>this.handleIncomingContactRosterEvent("none",e),[et.DELETED]:e=>this.handleIncomingContactRosterEvent("remove",e),[Ne.GROUP_NOTIFY]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===Xe.GROUP_DESTROYED&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[Ne.CHATROOM_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[Ne.CHAT_THREAD_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[Ne.USER_INFO_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(t){const n=Fe.validateOrThrow(tl,t),r=n.customOSPlatform,i=s.normalizeServiceConfig(n.serviceConfig),o={appKey:n.appKey,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:s.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:oe,userInfoBatchSize:ie,groupNamecardWindowMs:re,groupNamecardMaxConcurrency:ne},platformAdapterOptions:n.platformAdapterOptions},a=t.managers??[];if(s.instance){if(!s.isSameConfig(s.instance.config,o))throw new C("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:s.instance.config,next:o}});return a.length>0&&s.instance.registerManagers(a),s.instance.validateOptionalCapabilityDependencies(),s.instance}return s.instance=new s(o),a.length>0&&s.instance.registerManagers(a),s.instance.validateOptionalCapabilityDependencies(),s.instance}async login(n){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const r=Fe.validateOrThrow(sl,n);if(this.state===be.CONNECTING||this.state===be.CONNECTED){const t=this.currentUserId&&this.currentUserId!==r.userId;throw new p(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 i=++this.loginAttempt;t.warn("Login started",{userId:r.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const o=this.platformAdapter??mi(this.config.platformAdapterOptions);this.platformAdapter=o,ae({requestAdapter:o.request,onDiagnostic:(e,s)=>{t.warn(e,s)}});const a=ce({appKey:this.config.appKey,uid:r.userId,sdkVersion:"5.0.0",platform:o.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),c=o.runtime.getNetworkType?.();c&&c.then(e=>{ye(e)}).catch(()=>{ye("unknown")});const d=f({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:r.userId});let l,u,h;this.updateState(be.CONNECTING),this.logReportEnabled=!1,de("unknown");let m,g=!1,y=!1,I=!0;if("dns"===this.config.serviceConfig.mode){const e=d?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const s=await El({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:o.request});t.warn("DNS resolved for login",{baseUrl:s.baseUrl,websocketUrl:s.websocketUrl,syncWsCount:s.syncWebsocketUrls.length,restBaseUrl:s.restBaseUrl}),l=s.websocketUrl,u=s.websocketUrls,this.contactSyncWsUrls=s.syncWebsocketUrls,this.syncConversationListConfigWsUrls=s.syncWebsocketUrls,this.contactSyncDnsResolved=!0,h=s.restBaseUrl,g="true"===s.dnsConfig.enableReportLogs,m=s.dnsConfig.reportInterval,y="true"===s.dnsConfig.enableMd5Check,I="false"!==s.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),le(s.dnsConfig.enableDataReport),t.debug("DNS report switch resolved",{enabled:g})}catch(S){const t=S instanceof T?S.code:-1,s=S instanceof Error?S.message:String(S);throw e?.finish({code:t,success:!1,description:s}),d?.finish({code:t,success:!1,description:s}),le(void 0),de("disabled"),this.updateState(be.DISCONNECTED),S}}else{const t=this.config.serviceConfig.serverUrls;if(!t?.wsUrl||!t.restApiUrl){const t=new C("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 d?.finish({code:t.code,success:!1,description:t.message}),le(void 0),this.updateState(be.DISCONNECTED),t}l=t.wsUrl,h=t.restApiUrl,y=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=t.syncWsUrl?[t.syncWsUrl]:[],this.contactSyncDnsResolved=!1,le(void 0)}if(ue({restBaseUrl:h,appKey:this.config.appKey,userId:r.userId,token:r.token,requestAdapter:o.request}),he(m),this.logReportEnabled=g,de(g?"enabled":"disabled"),this.resetCore(),i!==this.loginAttempt){const t=new p("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}});throw d?.finish({code:e.CONNECTION_CANCELLED,success:!1,description:t.message}),this.updateState(be.DISCONNECTED),fe(),t}this.core=new dc({serverUrl:l,serverUrls:u,userId:r.userId,token:r.token,appKey:this.config.appKey,restBaseUrl:h,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:y,enableMultipartUpload:I,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:a,platformAdapter:o,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),ue({resource:this.core.getClientResource()});const v=d?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:l});try{if(t.warn("Connecting core websocket",{serverUrl:l,restBaseUrl:h,userId:r.userId}),await this.core.connect(),v?.finish({code:200,success:!0}),d?.finish({code:0,success:!0}),t.warn("Core websocket connected",{userId:r.userId,resource:this.core.getClientResource()}),this.currentUserId=r.userId,pe({uid:r.userId}),this.restBaseUrl=h??null,this.authToken=r.token,this.clientResource=this.core.getClientResource(),await this.initCacheManager(r.userId),t.warn("Cache initialized after login",{userId:r.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),await this.syncSelfUserInfoAfterLogin(),this.config.enableSyncData.includes("conversation")&&await this.refreshSessionList(this.config.syncConversationListConfig),this.triggerConfiguredSyncDataAfterLogin(r.userId),this.logReportEnabled)try{await me()}catch(S){t.warn("Report logs on login failed",S)}}catch(S){const e=S instanceof T?S.code:-1,t=S instanceof Error?S.message:String(S);throw v?.finish({code:e,success:!1,description:t}),d?.finish({code:e,success:!1,description:t}),this.resetCore(),this.updateState(be.DISCONNECTED),fe(),S}}async logout(){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(this.loginAttempt+=1,!this.core)return this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),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.resetManagerSessionRuntimes(),this.updateState(be.DISCONNECTED),this.logReportEnabled=!1,de("disabled"),ge(),void fe();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await me()}catch(n){t.warn("Report logs on logout failed",n)}await this.core.disconnect()}finally{this.resetCore(),this.updateState(be.DISCONNECTED),this.logReportEnabled=!1,de("disabled"),ge(),fe()}}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 C("restBaseUrl is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new C("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new C("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 C("clientResource is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.config.appKey,userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(s){const n=Fe.validateOrThrow(nl,s);if(!this.core||!this.currentUserId||this.state!==be.CONNECTED)throw new p("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const r=this.getRestContext(),i={...r},o=new J(i.restBaseUrl,{errorMap:Ol,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});o.setAuthToken(n),t.warn("Renew token started",{userId:r.userId});const a=await Ml(o,i);if(a<=Date.now())throw new p("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const c=this.core.renewToken(n,a);return this.authToken=n,ue({token:n}),t.warn("Renew token succeeded",{userId:r.userId,expireAt:a}),c}async getRTCTokenInfo(e){const s=Fe.validateOrThrow(rl,e),n=this.getRestContext(),r=new J(n.restBaseUrl,{errorMap:Ol,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return r.setAuthToken(n.token),t.warn("Get RTC token info started",{userId:n.userId,hasChannelName:Boolean(s?.channelName)}),Rl(r,n,s)}async getUserIdsWithRTCUids(e){const s=Fe.validateOrThrow(il,e),n=this.getRestContext(),r=new J(n.restBaseUrl,{errorMap:Ol,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return r.setAuthToken(n.token),t.warn("Get userIds with RTC UIDs started",{userId:n.userId,count:s.length}),_l(r,n,s)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),s=new J(e.restBaseUrl,{errorMap:Ol,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(e.token),t.warn("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),Ul(s,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(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;return e?this.buildAuthenticatedSessionListSyncUrls([e]):this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new Jd({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)}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===Gt.START_COMPLETED||e.stream.status===Gt.FULL||e.stream.status===Gt.COMPLETED||e.stream.status===Gt.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:so(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 mt(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 s=this.getUserInfoReadCapability();if(!s)return[];try{return await s.getUserInfoByUserId({userIds:e})}catch(n){return t.warn("Contact roster event user info fetch failed",{userIds:e,error:n}),[]}}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&&t.warn("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(s){t.warn("Self user info sync failed after login",{userId:this.currentUserId,error:s})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=Zi(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=>{Ji.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 s=this.getUserInfoReadCapability();if(!s||0===e.length)return;const n=e.map(e=>e.userId);let r;try{r=await s.getUserInfoByUserId({userIds:n})}catch(l){throw t.warn("User info hydration failed",{userIds:n,error:l}),l}const i=this.currentUserId,o=i?r.find(e=>e.userId===i):void 0,a=r.filter(e=>e.userId!==i);o&&this.dispatchOwnInfoUpdated(o),a.length>0&&this.dispatchUserInfoUpdated(a),r.length>0&&this.refreshConversationDisplayFromUserInfos(r.map(e=>({userId:e.userId})),"profile");const c=new Set(r.map(e=>e.userId)),d=n.filter(e=>!c.has(e));d.length>0&&t.warn("User info hydration returned partial result",{requestedUserIds:n,missingUserIds:d})}async flushGroupNamecardHydrationBatch(e){const s=this.getGroupNamecardHydrationCapability();if(s&&0!==e.targets.length)try{await s.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(n){t.warn("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:n})}}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(t){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(t,n){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new C("sender.userId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new C("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(Kt(t))throw new g("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.core||this.state!==be.CONNECTED)throw new g("ChatClient is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,n)}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(Xe.USER_GROUP_NAMECARD_UPDATED,{groupId:e,userId:t,namecard:s})}async downloadAndParseCombinePayload(t){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new C("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,n){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new C("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendMessageAction(t,n)}async sendChatRoomOperation(t,n){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new C("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(t,n)}async downloadAttachment(t){if(s.instance!==this)throw new C("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new C("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.downloadAttachment(t)}decodeServerMessageMeta(t){if(!this.core)throw new C("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 s.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),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),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 C(`${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(t){if(s.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",e.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}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 C(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)}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new td({appKey:this.config.appKey,userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode}),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(ct),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(Ze.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()}triggerConfiguredSyncDataAfterLogin(e){this.config.enableSyncData.includes("contact")&&(t.warn("Triggering automatic contact sync after login",{userId:e}),this.triggerContactSync()),this.config.enableSyncData.includes("group")&&(t.warn("Triggering automatic group sync after login",{userId:e}),this.triggerGroupSync())}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new zd(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const t=this.managerRegistry.get("contactManager");if(!t?.createSyncController)throw new C("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 Xd(this.getContactSyncRestContext(),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 C("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(Ze.SYNC_DATA_START,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(Ze.SYNC_DATA_FINISHED,e)}requireCacheManager(){if(!this.cacheManager)throw new C("cacheManager is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){const s=this.config.serviceConfig.serverUrls?.syncWsUrl;if(s)return this.buildAuthenticatedContactSyncUrls([s]);if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw t.warn("Automatic contact sync sync-ws is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new T("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw t.warn("Automatic contact sync sync-ws is unavailable without dns service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new T("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await El({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=e.syncWebsocketUrls,this.contactSyncDnsResolved=!0}catch(n){throw t.warn("Automatic contact sync sync-ws DNS resolve failed",{userId:this.currentUserId,reason:n instanceof Error?n.message:String(n)}),new T("Contact sync websocket dns resolve failed",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:n instanceof Error?n.message:String(n)}})}if(0===this.contactSyncWsUrls.length)throw t.warn("Automatic contact sync sync-ws is unavailable after DNS resolve",{userId:this.currentUserId,serviceConnectionMode:"dns"}),new T("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});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 C("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const s=new URL(e);return""!==s.pathname&&"/"!==s.pathname||(s.pathname="/ws"),s.searchParams.set("token",t),s.toString()}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.getContactSyncRestContext(),{orgName:s,appName:n}=M(t.appKey);return{type:ft.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}}resetCore(){this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core&&(this.core.destroy(),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,this.resetManagerSessionRuntimes())}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}static isSameConfig(e,t){return e.appKey===t.appKey&&(!!s.isSameStringArray(e.enableSyncData,t.enableSyncData)&&(e.useCustomAttachmentUpload===t.useCustomAttachmentUpload&&(e.enableMd5Check===t.enableMd5Check&&(!!s.isSameServiceConfig(e.serviceConfig,t.serviceConfig)&&(e.useFixedDeviceId===t.useFixedDeviceId&&(e.deviceId===t.deviceId&&(e.useReplacedMessageContents===t.useReplacedMessageContents&&(e.customDeviceName===t.customDeviceName&&(e.customOSPlatform===t.customOSPlatform&&(e.platformAdapterOptions?.prefer===t.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===t.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.overrides===t.platformAdapterOptions?.overrides&&(e.uiKitVersion===t.uiKitVersion&&(e.cacheEncryptionMode===t.cacheEncryptionMode&&(e.enableUserInfoSync===t.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===t.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===t.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===t.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===t.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===t.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===t.profileSync.groupNamecardMaxConcurrency))))))))))))))))))}static normalizeServiceConfig(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??cl,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:e?.serverUrls}}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,t){if(e.mode!==t.mode)return!1;if(e.dnsConfigUrls.length!==t.dnsConfigUrls.length)return!1;for(let s=0;s<e.dnsConfigUrls.length;s+=1)if(e.dnsConfigUrls[s]!==t.dnsConfigUrls[s])return!1;return s.isSameServerUrls(e.serverUrls,t.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl&&e.syncRestApiUrl===t.syncRestApiUrl&&e.syncWsUrl===t.syncWsUrl)}};kl.instance=null;let Pl=kl;export{b as AuthenticationError,io as CONVERSATION_MARK,td as CacheManager,Pl as ChatClient,Be as ChatManager,vt as ChatRoom,Ct as ChatRoomManager,yt as ChatThread,It as ChatThreadManager,p as ConnectionError,gt as ContactManager,rt as Group,it as GroupManager,qt as ImageType,y as MessageReceiveError,g as MessageSendError,A as NetworkError,St as PresenceManager,Et as PushManager,qe as RUNTIME_PLATFORMS,Ce as RestBusinessError,X as RestTransportError,T as SDKError,V as StorageError,Gt as StreamMessageStatus,N as UploadError,bt as UserInfoManager,C as ValidationError,mi as createPlatformAdapter,pi as detectRuntimePlatform,Se as isSDKError,Ee 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 vd(e,t);return e.map(e=>((e,t,s)=>{const n=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),r=((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),i="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,n,r):"groupChat"===e.type?(o=e.conversationId,a=s.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:o}):(e=>({conversationName:e}))(e.conversationId);var o,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:Id(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:i.conversationName,conversationAvatar:i.conversationAvatar}})(e,t,s))};class Sd{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 w("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 w("Session-list sync requestId mismatch",e.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:t.requestId}});if(this.isTerminal())throw new w("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 Ed=0,bd=5,Ad=10,Td=11,wd=1,Nd=2,Md=1,Rd=2,_d=3,Ud=e=>e===wd?"groupChat":e===Nd?"chatRoom":"singleChat",Dd=()=>Di().lookupType("easemob.pb.MessageBody"),Od=e=>{const t=Dd().toObject(Dd().decode(e),{longs:Number,bytes:Uint8Array}),s=Array.isArray(t.contents)?t.contents:[],n=(r=s[0])&&"object"==typeof r&&!Array.isArray(r)?r:{};var r;const i="number"==typeof n.type?n.type:0;return 0===i?{type:"text",content:"string"==typeof n.text?n.text:""}:1===i?{type:"image",filename:"string"==typeof n.displayName?n.displayName:"image",remotePath:"string"==typeof n.remotePath?n.remotePath:""}:2===i?{type:"video",filename:"string"==typeof n.displayName?n.displayName:"video",remotePath:"string"==typeof n.remotePath?n.remotePath:""}:3===i?{type:"location",latitude:"number"==typeof n.latitude?n.latitude:0,longitude:"number"==typeof n.longitude?n.longitude:0,address:"string"==typeof n.address?n.address:void 0}:4===i?{type:"voice",filename:"string"==typeof n.displayName?n.displayName:"voice",remotePath:"string"==typeof n.remotePath?n.remotePath:"",duration:"number"==typeof n.duration?n.duration:0}:5===i?{type:"file",filename:"string"==typeof n.displayName?n.displayName:"file",remotePath:"string"==typeof n.remotePath?n.remotePath:""}:6===i?{type:"cmd",action:"string"==typeof n.action?n.action:""}:7===i?{type:"custom",event:"string"==typeof n.customEvent?n.customEvent:""}:8===i?{type:"combine",title:"string"==typeof n.title?n.title:"",summary:"string"==typeof n.summary?n.summary:""}:{}},Ld=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}},kd=e=>{const t={...e};return delete t.type,t},Pd=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,xd=(e,t,s)=>{if(!e)return null;const n=(e=>{if(!e)return"";const t=e.lastIndexOf("_");return t>=0?e.slice(t+1):e})(e.from?.name),r={userId:n};return"singleChat"===s.conversationType&&n===s.conversationId&&s.singleChatPeerDisplay&&(s.singleChatPeerDisplay.conversationName!==n&&(r.nickname=s.singleChatPeerDisplay.conversationName),s.singleChatPeerDisplay.conversationAvatar&&(r.avatarUrl=s.singleChatPeerDisplay.conversationAvatar)),{msgServerId:e.id??"",from:n,to:Pd({conversationId:s.conversationId,conversationType:s.conversationType,from:n,currentUserId:s.currentUserId}),sender:r,conversationId:s.conversationId,conversationType:s.conversationType,type:(i=t.type,"text"===i||"image"===i||"file"===i||"voice"===i||"video"===i||"location"===i||"custom"===i||"cmd"===i||"combine"===i?i:"text"),timestamp:e.timestamp??0,body:kd(t)};var i},Fd=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},Bd=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return Od(e)}catch{return{}}})(e.last_message?.payload),n=e.session_id??"",r=Ud(e.session_type),i=(e=>{const t=e.session_id??"",s=Ud(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Ld(e)})(e);return{conversationId:n,conversationType:r,unreadCount:e.unread_count??0,lastMessage:xd(e.last_message,s,{conversationId:n,conversationType:r,currentUserId:t,singleChatPeerDisplay:"singleChat"===r?i:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:Fd(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===Md?"ALL":o===Rd?"AT":o===_d?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),qd={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 Gd=null,Kd=!1;const Vd=()=>Gd||(Kd||(Qe.util.Long=$e,Qe.configure(),Kd=!0),We(),Gd=Qe.Root.fromJSON(qd),Je(Gd),Gd),Hd=e=>Vd().lookupType(e),zd=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}},jd=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:zd(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:zd(t.protocol_version)??zd(t.protocolVersion)??0}},Wd=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}},Qd=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==zd(t.id)?String(zd(t.id)):void 0,from:Wd(t.from),timestamp:zd(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 $d{constructor(){this.requestType=Hd("easemob.sessionlist.GetSessionListRequest"),this.responseType=Hd("easemob.sessionlist.GetSessionListResponse"),this.errorType=Hd("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:Ed}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=zd(t.type);return s!==Ad?null:{type:s,header:jd(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:zd(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=zd(t.type);return s!==Td?null:{type:s,header:jd(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:zd(t.session_type),last_message:Qd(t.last_message),updated_at:zd(t.updated_at),pinned_time:zd(t.pinned_time),unread_count:zd(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:zd(t.read_receipt),remind_type:zd(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:zd(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=zd(t.type);return s!==bd?null:{type:s,header:jd(t.header),code:zd(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Yd=async t=>{const n=t.client.getCacheManager(),r=t.client.getRestContext(),i=t.client.getSessionListSyncWsUrls();if(!n||0===i.length)throw new m("session-list sync websocket is unavailable",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[o,a]=r.appKey.split("#");if(!o||!a)throw new S("session-list appKey is invalid",{code:e.VALIDATION_INVALID_FORMAT,details:{appKey:r.appKey}});const c=n.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:r.clientResource,org:o,app:a,username:r.userId,lastSyncTime:(l=c.sessionsLastSyncTs,Math.max(0,l-V)),params:t.params});var l;const u=new $d;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:n=>{if(5===n.type&&"code"in n&&"message"in n)throw 1002===(i=n).code?new A(i.message,{code:e.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:i.code}}):1003===i.code?new w(i.message,e.SERVER_BUSY,{details:{protocol:"session-list",responseCode:i.code}}):1501===i.code||1001===i.code?new S(i.message,{code:e.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:i.code}}):1503===i.code?new w(i.message,e.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:i.code}}):(i.code,new w(i.message,e.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:i.code}}));var i;if(11!==n.type)throw new w("session-list response type is invalid",e.MESSAGE_DECODE_FAILED,{details:{responseType:n.type}});const o=n,a=o.header?.requestId;if(a&&a!==t.session.getRequestId())return;h+=1,s.debug("Decoded session-list sync raw response",{requestId:t.session.getRequestId(),batchSequence:h,response:o});const c=Bd(o,r.userId),d=t.session.pushBatch({requestId:t.session.getRequestId(),batchSequence:h,sessions:c,isLastBatch:!0===o.isLastBatch,lastSyncFinishedTs:o.lastSyncFinishedTs});if("number"==typeof o.lastSyncFinishedTs&&(p=o.lastSyncFinishedTs),!d.done)return;return{done:!0,result:{items:t.session.getItems(),lastSyncFinishedTs:p}}}})},Jd=()=>Date.now(),Xd={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Zd=(e,t)=>({status:e,determinedAt:Jd(),reason:t}),el=t=>t instanceof w&&(t.code===e.SERVER_BUSY||1103===t.code),tl=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:el(e)});class sl{constructor(e){this.running=null,this.currentSession=null,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}refresh(e){return this.running||(this.currentSession=new Sd,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[];this.client.emitSyncDataStart("conversation");const r=await this.tryDirectFallback(n);if(r)return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),r;try{const e=n.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let r=0;const o=await async function(e,t,s={}){const n={...md,...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=fd(o,n);await gd(e)}throw r}(async()=>{r+=1;const e=1===r?t:this.createRetrySession();e.start();try{return await Yd({client:this.client,session:e,params:s})}catch(n){throw e.fail(),n}},el,Xd),a={result:o,syncStartedAt:t.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:Jd()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:Jd()};try{await n.commitSessionListSync({items:c,mode:e,checkpoint:d,syncStartedAt:a.syncStartedAt})}catch(i){t.fail();const e=new H("Session-list final persistence failed",{details:{cause:i instanceof Error?i.message:String(i)}});return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:tl(e)}),n.loadSessionList()}const l=n.loadSessionList();return n.updateConversationsFromServer(l.map(at),{syncStartedAt:a.syncStartedAt}),await n.flushPending(),this.client.emitConversationListUpdate("conversation","full"===e),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),l}catch(i){const s=i instanceof w?i:new w(i instanceof Error?i.message:String(i));t.fail();const r=(t=>t.code===e.OPERATION_UNSUPPORTED||t.code===e.AUTH_UNAUTHORIZED?{capabilityState:Zd("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 o=await this.buildFallbackSessionList(n);return r.shouldUseFallback&&n.replaceSessionList(o),this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:tl(s)}),o}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}var t;const s=Boolean(this.client.getServerUrlsConfig()?.syncWsUrl),n=this.client.isSessionListDnsProbeAvailable();if(!s&&!n){this.capabilityState=Zd("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new Sd}async buildFallbackSessionList(e){return await(async(e,t)=>await Cd(e,t))(e.loadConversationSummaries(),this.client)}}const nl=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),rl=async t=>{if("string"==typeof t||nl(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):nl(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 w("sync websocket frame payload type is invalid",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof t}})},il=e=>{const t=Math.max(e-1,0),s=Y*Math.pow(J,t);return Math.min(s,$)},ol=async e=>{await new Promise(t=>{setTimeout(t,e)})},al=e=>e instanceof Error?e:new Error(String(e));class cl{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 w("sync websocket session is cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:t.requestId}});if(this.pending.has(t.requestId))throw new w("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,al(n))}return await s}cancel(t="sync-websocket-cancelled"){this.cancelled=!0;const s=new w("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!==He.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&&s.warn("sync websocket retry started",this.buildLogContext({reason:t?.message}));try{return void(await this.openSocket())}catch(n){if(t=al(n),this.cancelled||0===this.pending.size)throw t;if(this.attempt>=3)throw s.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),t;const e=il(this.attempt);s.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:e,reason:t.message})),await ol(e)}}throw new m("sync websocket retry exhausted",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:t?.message??"unknown"}})}async openSocket(){const n=await this.getUrls();if(0===n.length)throw new m("sync websocket urls are unavailable",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const r=n[this.urlIndex%n.length];if(this.urlIndex+=1,!r)throw new m("sync websocket url is invalid",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=r,this.state="connecting",s.warn("sync websocket connect started",this.buildLogContext());const i=t(),o=this.socketAdapter??lr({webSocketCtor:i.WebSocket});if(!o)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let a=null;try{const e=await Promise.race([o.connect({url:r}),new Promise((e,t)=>{a=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},z)})]);a&&clearTimeout(a),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(),s.warn("sync websocket connected",this.buildLogContext())}catch(c){if(a&&clearTimeout(a),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),c instanceof m)throw c;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:c instanceof Error?c.message:String(c)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await rl(e);if(!(await this.routeFrame(t)))return}catch(t){const e=al(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(t){const n=[];let r=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(i){this.pending.delete(e.requestId),e.reject(al(i)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||r||(r={pending:e,frame:s.frame})}catch(i){n.push(al(i))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&n.length===this.pending.size)throw new w("sync websocket frame decode failed",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:n[0]?.message}});return s.warn("sync websocket frame ignored",this.buildLogContext({reason:n[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?(s.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(al(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===He.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)}))}),s.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||(s.warn("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},j))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},W))}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>=He.CLOSING||(this.state="closing",s.close(e,t))}buildConnectionError(t,s,n={}){return new m(t,{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:s,url:this.activeUrl,...n}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:Q(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const dl=async(t,s,n)=>{const{orgName:r,appName:i}=R(t.appKey),o=`/${r}/${i}/user/${encodeURIComponent(t.userId)}/roster/metadata/version`,a=new X(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(ut(t))return ut(t.data)?r(t.data):r(t);throw new S("Invalid contact metadata response",{code:e.VALIDATION_INVALID_FORMAT,details:{payload:t}})})(await a.get(o),s)}catch(c){if(c instanceof S)throw c;const t=c instanceof w&&c.details?c.details:{};throw new Z("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 w?c.code:void 0}})}},ll=e=>ht.string().regex(/^https?:\/\/\S+$/i,e),ul=e=>ht.string().regex(/^wss?:\/\/\S+$/i,e),hl=ht.object({appKey:ht.string().min(1,"appKey is required"),enableUserInfoSync:ht.boolean().optional(),enableSyncData:ht.array(ht.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:ht.boolean().optional(),deleteConversationOnGroupDestroyed:ht.boolean().optional(),syncConversationListConfig:ht.object({includeEmpty:ht.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:ht.boolean().optional(),useFixedDeviceId:ht.boolean().optional(),deviceId:ht.string().min(1,"deviceId is required").optional(),serviceConfig:ht.object({dnsConfigUrls:ht.array(ll("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:ht.object({restApiUrl:ll("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:ul("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:ll("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:ul("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:ht.boolean().optional(),customDeviceName:ht.string().min(1,"customDeviceName is required").optional(),customOSPlatform:ht.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:ht.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:ht.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:ht.array(ht.unknown()).optional(),platformAdapterOptions:ht.object({prefer:ht.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:ht.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:ht.custom(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{"enableMd5Check"in e&&t.addIssue({code:ht.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:ht.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:ht.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:ht.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:ht.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:ht.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:ht.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&n&&t.addIssue({code:ht.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(n?.restApiUrl||t.addIssue({code:ht.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:ht.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),pl=ht.object({userId:ht.string().min(1,"userId is required"),token:ht.string().min(1,"token is required")}),ml=ht.string().trim().min(1,"token is required"),fl=ht.object({channelName:ht.string().trim().min(1,"channelName is required").optional()}).optional(),gl=ht.array(ht.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))),yl=ht.object({protocol:ht.string(),domain:ht.string().optional(),ip:ht.string().optional(),port:ht.union([ht.string(),ht.number()]).optional()}).passthrough(),Il=ht.object({rest:ht.object({hosts:ht.array(yl).nonempty()}),"msync-wx":ht.object({hosts:ht.array(yl).nonempty()}),"sync-ws":ht.object({hosts:ht.array(yl).nonempty()}).optional(),enableReportLogs:ht.enum(["true","false"]).optional(),reportInterval:ht.number().positive().finite().optional(),enableDataReport:ht.enum(["true","false"]).optional(),enableMd5Check:ht.enum(["true","false"]).optional(),uploadinparts_enable:ht.enum(["true","false"]).optional()}).passthrough(),vl=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Cl=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],Sl=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function El(e){return"object"==typeof e&&null!==e}function bl(e){return Array.isArray(e)?{hosts:e}:function(e){return El(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Al(e,t,s){for(const n of t){const t=bl(e[n]);if(t)return{key:n,section:t}}for(const[n,r]of Object.entries(e)){if(!s(n))continue;const e=bl(r);if(e)return{key:n,section:e}}}function Tl(e){if(!El(e))return Fe.validateOrThrow(Il,e);const t=bl(e.rest),n=Al(e,Cl,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),r=Al(e,Sl,e=>{const t=e.toLowerCase();return!t.includes("msync")&&t.includes("sync")&&(t.includes("ws")||t.includes("socket"))}),i={...e,rest:t??e.rest,"msync-wx":n?.section};r?.section?i["sync-ws"]=r.section:"sync-ws"in i&&!bl(i["sync-ws"])&&delete i["sync-ws"];const o="true"===(a=e.enableReportLogs)||!0===a?"true":"false"===a||!1===a?"false":void 0;var a;o&&(i.enableReportLogs=o);const c=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!==c?i.reportInterval=c:delete i.reportInterval;const d=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);d?i.enableDataReport=d:delete i.enableDataReport;const l=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);l?i.enableMd5Check=l:delete i.enableMd5Check;const u=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return u?i.uploadinparts_enable=u:delete i.uploadinparts_enable,n&&"msync-wx"!==n.key&&s.warn("DNS config websocket section normalized",{sourceKey:n.key}),r&&"sync-ws"!==r.key&&s.warn("DNS config sync websocket section normalized",{sourceKey:r.key}),Fe.validateOrThrow(Il,i)}function wl(t,s){const n=t.domain||t.ip;if(!n)throw new S("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 Nl(e,t){return"https"===e?"https":"http"===e?"http":t}function Ml(t,s){const n=t.domain||t.ip;if(!n)throw new S("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 Rl(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function _l(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 Ul(e,t,s){const n=new X(e,{requestAdapter:s,includeRequestId:!0});let r="/easemob/server.json",i=!0;try{const t=new URL(e),s=""!==t.pathname&&"/"!==t.pathname,n=""!==t.search;(s||n)&&(r="",i=!1)}catch{r="/easemob/server.json",i=!0}if(i){r=`${r}?${pt({app_key:t,_v:String(Date.now())}).toString()}`}return Tl(await n.get(r))}function Dl(t,s){const n=t["sync-ws"];return n&&Array.isArray(n.hosts)?n.hosts.map(t=>function(t,s){const n=t.domain||t.ip;if(!n)throw new S("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}`}(t,Nl(t.protocol,s))).filter(e=>"string"==typeof e&&e.length>0):[]}async function Ol(t){const n=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:vl;if(0===n.length)throw new S("DNS_CONFIG list is empty",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=t.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let i;for(const c of n)try{const s=await Ul(c,t.appKey,t.requestAdapter),n=_l(Rl(s["msync-wx"].hosts,r));if(0===n.length)throw new S("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 i=n[0];if(!i)throw new S("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 o=Rl(s.rest.hosts,r);if(0===o.length)throw new S("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 a=o[0];if(!a)throw new S("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 d=n.map(e=>wl(e,Nl(e.protocol,r))),l=wl(i,Nl(i.protocol,r)),u=Dl(s,r);return{websocketUrl:l,websocketUrls:d,syncWebsocketUrls:u,baseUrl:c,restBaseUrl:Ml(a,Nl(a.protocol,r)),dnsConfig:s}}catch(a){s.warn("DNS config candidate failed",{baseUrl:c,reason:a instanceof Error?a.message:String(a),error:a instanceof Error&&"function"==typeof a.toJSON?a.toJSON():a}),i=a}const o={stage:"dns"};throw i&&(o.reason=i.message,"code"in i&&"number"==typeof i.code&&(o.causeCode=i.code)),new m("DNS_CONFIG exhausted",{code:e.CONNECTION_DNSLIST_FAILED,details:o})}const Ll=t=>new S(t,{code:e.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),kl=e=>{if(!ut(e))throw Ll("Invalid REST response");return ut(e.data)?e.data:e},Pl=(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}}},xl=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},Fl=e=>{const{orgName:t,appName:s}=R(e.appKey);return`/${t}/${s}`},Bl=async(e,t)=>{const s=await e.get((e=>`${Fl(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=kl(e),s=Pl(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw Ll("Invalid token expires response");return s})(s)},ql=async(e,t,s)=>{const n=await e.get(((e,t)=>{const s=pt({channelName:t?.channelName??"*"});return`${Fl(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${s.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=kl(e);return{appId:xl(t,["app_id","appId"])??"",rtcToken:xl(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:xl(t,["channel_name","channelName"])??"",rtcUid:Pl(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:Pl(t,["expires_in","expire","expireAt"])??0}})(n)},Gl=async(e,t,s)=>{const n=await e.post((e=>`${Fl(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=kl(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)},Kl=async(e,t)=>{const s=await e.get((e=>`${Fl(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=ut(e)&&Array.isArray(e.data)?e.data:[],n=[];for(const r of s){if(!ut(r))continue;const e=xl(r,["res","resource","clientResource"]);e&&e!==t.clientResource&&n.push(`${t.userId}/${e}`)}return n})(s,t)};class Vl{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=>{s.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 Hl{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 n=this.generation;this.activeCount+=1;const r=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let i;try{i=Promise.resolve(this.options.onFlush(r))}catch(t){i=Promise.reject(t instanceof Error?t:new Error(String(t)))}i.catch(t=>{const r=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(s.warn("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:r.length>0,error:t instanceof Error?t.message:String(t)}),n===this.generation&&0!==r.length){for(const e of r)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)}}const zl=ve(Ce,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),jl=class t{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=Ae.DISCONNECTED,this.loginAttempt=0,this.currentUserId=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.config={appKey:e.appKey,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.config.platformAdapterOptions&&(this.platformAdapter=Ti(this.config.platformAdapterOptions)),this.managerRegistry=/* @__PURE__ */new Map,this.managerCapabilities=/* @__PURE__ */new Map,this.eventHub=new pd,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 Hl({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:te,maxRetries:ee,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Vl({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:ne,maxBatchSize:se,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[Te.CONNECTING]:e=>{this.updateState(e.state)},[Te.CONNECTED]:e=>{this.updateState(e.state)},[Te.DISCONNECTED]:e=>{this.updateState(e.state)},[Te.RECONNECT_FAILED]:e=>{this.updateState(e.state)},[Ze.MESSAGE]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[Ze.STREAM_MESSAGE]:e=>{this.handleIncomingConversationStreamMessage(e)},[Ne.MESSAGE_SENT]:e=>{this.handleOutgoingConversationMessage(e)},[Ze.MULTI_DEVICE_CONTACT]:e=>{this.handleMultiDeviceContactEvent(e)},[Ze.MULTI_DEVICE_CONVERSATION]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[et.ADDED]:e=>this.handleIncomingContactRosterEvent("add",e),[et.AGREED]:e=>this.handleIncomingContactRosterEvent("add",e),[et.INVITED]:e=>this.handleIncomingContactRosterEvent("none",e),[et.REFUSE]:e=>this.handleIncomingContactRosterEvent("none",e),[et.DELETED]:e=>this.handleIncomingContactRosterEvent("remove",e),[Ne.GROUP_NOTIFY]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===Xe.GROUP_DESTROYED&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[Ne.CHATROOM_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[Ne.CHAT_THREAD_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[Ne.USER_INFO_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(s){const n=Fe.validateOrThrow(hl,s),r=n.customOSPlatform,i=t.normalizeServiceConfig(n.serviceConfig),o={appKey:n.appKey,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:ae,userInfoBatchSize:oe,groupNamecardWindowMs:ie,groupNamecardMaxConcurrency:re},platformAdapterOptions:n.platformAdapterOptions},a=s.managers??[];if(t.instance){if(!t.isSameConfig(t.instance.config,o))throw new S("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(n){if(t.instance!==this)throw new S("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const r=Fe.validateOrThrow(pl,n);if(this.state===Ae.CONNECTING||this.state===Ae.CONNECTED){const t=this.currentUserId&&this.currentUserId!==r.userId;throw new m(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 i=++this.loginAttempt;s.warn("Login started",{userId:r.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const o=this.platformAdapter??Ti(this.config.platformAdapterOptions);this.platformAdapter=o,ce({requestAdapter:o.request,onDiagnostic:(e,t)=>{s.warn(e,t)}});const a=de({appKey:this.config.appKey,uid:r.userId,sdkVersion:"5.0.1",platform:o.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),c=o.runtime.getNetworkType?.();c&&c.then(e=>{Ie(e)}).catch(()=>{Ie("unknown")});const d=g({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:r.userId});let l,u,h;this.updateState(Ae.CONNECTING),this.logReportEnabled=!1,le("unknown");let p,f=!1,y=!1,I=!0;if("dns"===this.config.serviceConfig.mode){const e=d?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await Ol({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:o.request});s.warn("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),l=t.websocketUrl,u=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,h=t.restBaseUrl,f="true"===t.dnsConfig.enableReportLogs,p=t.dnsConfig.reportInterval,y="true"===t.dnsConfig.enableMd5Check,I="false"!==t.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),ue(t.dnsConfig.enableDataReport),s.debug("DNS report switch resolved",{enabled:f})}catch(C){const t=C instanceof w?C.code:-1,s=C instanceof Error?C.message:String(C);throw e?.finish({code:t,success:!1,description:s}),d?.finish({code:t,success:!1,description:s}),ue(void 0),le("disabled"),this.updateState(Ae.DISCONNECTED),C}}else{const t=this.config.serviceConfig.serverUrls;if(!t?.wsUrl||!t.restApiUrl){const t=new S("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 d?.finish({code:t.code,success:!1,description:t.message}),ue(void 0),this.updateState(Ae.DISCONNECTED),t}l=t.wsUrl,h=t.restApiUrl,y=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=t.syncWsUrl?[t.syncWsUrl]:[],this.contactSyncDnsResolved=!1,ue(void 0)}if(he({restBaseUrl:h,appKey:this.config.appKey,userId:r.userId,token:r.token,requestAdapter:o.request}),pe(p),this.logReportEnabled=f,le(f?"enabled":"disabled"),this.resetCore(),i!==this.loginAttempt){const t=new m("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}});throw d?.finish({code:e.CONNECTION_CANCELLED,success:!1,description:t.message}),this.updateState(Ae.DISCONNECTED),ge(),t}this.core=new Cc({serverUrl:l,serverUrls:u,userId:r.userId,token:r.token,appKey:this.config.appKey,restBaseUrl:h,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:y,enableMultipartUpload:I,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:a,platformAdapter:o,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),he({resource:this.core.getClientResource()});const v=d?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:l});try{if(s.warn("Connecting core websocket",{serverUrl:l,restBaseUrl:h,userId:r.userId}),await this.core.connect(),v?.finish({code:200,success:!0}),d?.finish({code:0,success:!0}),s.warn("Core websocket connected",{userId:r.userId,resource:this.core.getClientResource()}),this.currentUserId=r.userId,me({uid:r.userId}),this.restBaseUrl=h??null,this.authToken=r.token,this.clientResource=this.core.getClientResource(),await this.initCacheManager(r.userId),s.warn("Cache initialized after login",{userId:r.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),await this.syncSelfUserInfoAfterLogin(),this.config.enableSyncData.includes("conversation")&&await this.refreshSessionList(this.config.syncConversationListConfig),this.triggerConfiguredSyncDataAfterLogin(r.userId),this.logReportEnabled)try{await fe()}catch(C){s.warn("Report logs on login failed",C)}}catch(C){const e=C instanceof w?C.code:-1,t=C instanceof Error?C.message:String(C);throw v?.finish({code:e,success:!1,description:t}),d?.finish({code:e,success:!1,description:t}),this.resetCore(),this.updateState(Ae.DISCONNECTED),ge(),C}}async logout(){if(t.instance!==this)throw new S("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(this.loginAttempt+=1,!this.core)return this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),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.resetManagerSessionRuntimes(),this.updateState(Ae.DISCONNECTED),this.logReportEnabled=!1,le("disabled"),ye(),void ge();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await fe()}catch(n){s.warn("Report logs on logout failed",n)}await this.core.disconnect()}finally{this.resetCore(),this.updateState(Ae.DISCONNECTED),this.logReportEnabled=!1,le("disabled"),ye(),ge()}}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 S("restBaseUrl is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new S("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new S("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 S("clientResource is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.config.appKey,userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(t){const n=Fe.validateOrThrow(ml,t);if(!this.core||!this.currentUserId||this.state!==Ae.CONNECTED)throw new m("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const r=this.getRestContext(),i={...r},o=new X(i.restBaseUrl,{errorMap:zl,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});o.setAuthToken(n),s.warn("Renew token started",{userId:r.userId});const a=await Bl(o,i);if(a<=Date.now())throw new m("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const c=this.core.renewToken(n,a);return this.authToken=n,he({token:n}),s.warn("Renew token succeeded",{userId:r.userId,expireAt:a}),c}async getRTCTokenInfo(e){const t=Fe.validateOrThrow(fl,e),n=this.getRestContext(),r=new X(n.restBaseUrl,{errorMap:zl,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return r.setAuthToken(n.token),s.warn("Get RTC token info started",{userId:n.userId,hasChannelName:Boolean(t?.channelName)}),ql(r,n,t)}async getUserIdsWithRTCUids(e){const t=Fe.validateOrThrow(gl,e),n=this.getRestContext(),r=new X(n.restBaseUrl,{errorMap:zl,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return r.setAuthToken(n.token),s.warn("Get userIds with RTC UIDs started",{userId:n.userId,count:t.length}),Gl(r,n,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new X(e.restBaseUrl,{errorMap:zl,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),s.warn("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),Kl(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(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;return e?this.buildAuthenticatedSessionListSyncUrls([e]):this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new cl({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)}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===Gt.START_COMPLETED||e.stream.status===Gt.FULL||e.stream.status===Gt.COMPLETED||e.stream.status===Gt.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:mo(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 mt(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(n){return s.warn("Contact roster event user info fetch failed",{userIds:e,error:n}),[]}}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&&s.warn("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){s.warn("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=uo(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=>{co.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};lo(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 n=e.map(e=>e.userId);let r;try{r=await t.getUserInfoByUserId({userIds:n})}catch(l){throw s.warn("User info hydration failed",{userIds:n,error:l}),l}const i=this.currentUserId,o=i?r.find(e=>e.userId===i):void 0,a=r.filter(e=>e.userId!==i);o&&this.dispatchOwnInfoUpdated(o),a.length>0&&this.dispatchUserInfoUpdated(a),r.length>0&&this.refreshConversationDisplayFromUserInfos(r.map(e=>({userId:e.userId})),"profile");const c=new Set(r.map(e=>e.userId)),d=n.filter(e=>!c.has(e));d.length>0&&s.warn("User info hydration returned partial result",{requestedUserIds:n,missingUserIds:d})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(n){s.warn("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:n})}}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 S("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 S("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 S("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 S("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(Kt(s))throw new y("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:s.msgLocalId,retryable:!1}});if(!this.core||this.state!==Ae.CONNECTED)throw new y("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)}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(Xe.USER_GROUP_NAMECARD_UPDATED,{groupId:e,userId:t,namecard:s})}async downloadAndParseCombinePayload(s){if(t.instance!==this)throw new S("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new S("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 S("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new S("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 S("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new S("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(s,n)}async downloadAttachment(s){if(t.instance!==this)throw new S("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new S("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.downloadAttachment(s)}decodeServerMessageMeta(t){if(!this.core)throw new S("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),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),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 S(`${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 S(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)}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new hd({appKey:this.config.appKey,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(ct),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(Ze.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()}triggerConfiguredSyncDataAfterLogin(e){this.config.enableSyncData.includes("contact")&&(s.warn("Triggering automatic contact sync after login",{userId:e}),this.triggerContactSync()),this.config.enableSyncData.includes("group")&&(s.warn("Triggering automatic group sync after login",{userId:e}),this.triggerGroupSync())}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new sl(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const t=this.managerRegistry.get("contactManager");if(!t?.createSyncController)throw new S("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 dl(this.getContactSyncRestContext(),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 S("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(Ze.SYNC_DATA_START,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(Ze.SYNC_DATA_FINISHED,e)}requireCacheManager(){if(!this.cacheManager)throw new S("cacheManager is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){const t=this.config.serviceConfig.serverUrls?.syncWsUrl;if(t)return this.buildAuthenticatedContactSyncUrls([t]);if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw s.warn("Automatic contact sync sync-ws is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new w("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw s.warn("Automatic contact sync sync-ws is unavailable without dns service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new w("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await Ol({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=e.syncWebsocketUrls,this.contactSyncDnsResolved=!0}catch(n){throw s.warn("Automatic contact sync sync-ws DNS resolve failed",{userId:this.currentUserId,reason:n instanceof Error?n.message:String(n)}),new w("Contact sync websocket dns resolve failed",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:n instanceof Error?n.message:String(n)}})}if(0===this.contactSyncWsUrls.length)throw s.warn("Automatic contact sync sync-ws is unavailable after DNS resolve",{userId:this.currentUserId,serviceConnectionMode:"dns"}),new w("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});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 S("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 S("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.getContactSyncRestContext(),{orgName:s,appName:n}=R(t.appKey);return{type:ft.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}}resetCore(){this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core&&(this.core.destroy(),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,this.resetManagerSessionRuntimes())}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}static isSameConfig(e,s){return e.appKey===s.appKey&&(!!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?.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){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??vl,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:e?.serverUrls}}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&&e.syncRestApiUrl===t.syncRestApiUrl&&e.syncWsUrl===t.syncWsUrl)}};jl.instance=null;let Wl=jl;export{A as AuthenticationError,yo as CONVERSATION_MARK,hd as CacheManager,Wl as ChatClient,Be as ChatManager,vt as ChatRoom,Ct as ChatRoomManager,yt as ChatThread,It as ChatThreadManager,m as ConnectionError,gt as ContactManager,rt as Group,it as GroupManager,qt as ImageType,I as MessageReceiveError,y as MessageSendError,T as NetworkError,St as PresenceManager,Et as PushManager,qe as RUNTIME_PLATFORMS,Se as RestBusinessError,Z as RestTransportError,w as SDKError,H as StorageError,Gt as StreamMessageStatus,M as UploadError,bt as UserInfoManager,S as ValidationError,Ti as createPlatformAdapter,Ai as detectRuntimePlatform,Ee as isSDKError,be as setLogLevel};