easemob-websdk 5.1.0 → 5.1.2

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 (100) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/chat-client.d.ts +42 -8
  3. package/chunks/{chat-manager-D_KF5qM1.cjs → chat-manager-BFd2Z4oY.cjs} +1 -1
  4. package/chunks/{chat-manager-DCqgMxLm.js → chat-manager-CId_M_e5.js} +1 -1
  5. package/chunks/common-BvlDAw4a.js +1 -0
  6. package/chunks/common-tHGz9VBk.cjs +1 -0
  7. package/chunks/event-system-B62vbKqG.js +1 -0
  8. package/chunks/{event-system-COBJFEIq.cjs → event-system-TYhmgy4K.cjs} +1 -1
  9. package/chunks/group-user-info-resolver-B-dyr__b.cjs +1 -0
  10. package/chunks/group-user-info-resolver-DMccCqez.js +1 -0
  11. package/chunks/index-BBFJYOM8.js +1 -0
  12. package/chunks/{index-Dvvh1nf6.cjs → index-DJPAjXAp.cjs} +1 -1
  13. package/chunks/index-DtWkVcfb.cjs +1 -0
  14. package/chunks/index-l_BUKi77.js +1 -0
  15. package/chunks/light-BcQg8h2W.cjs +1 -0
  16. package/chunks/light-DImBnNes.js +1 -0
  17. package/chunks/{reflection-proto-codec-CjRraw85.js → reflection-proto-codec-7r8Sei3y.js} +1 -1
  18. package/chunks/{reflection-proto-codec-BerStgkC.cjs → reflection-proto-codec-CwrIKT1L.cjs} +1 -1
  19. package/chunks/{session-list-query-rynxSxtv.js → session-list-query-Cvr6rlme.js} +1 -1
  20. package/chunks/{session-list-query-C4OQMvPf.cjs → session-list-query-Dslj2k3t.cjs} +1 -1
  21. package/chunks/{user-info-DfbCp80h.js → user-info-AlshAvdy.js} +1 -1
  22. package/chunks/{user-info-DsDDTJrw.cjs → user-info-DH3aE1gm.cjs} +1 -1
  23. package/config/timeouts.d.ts +11 -0
  24. package/core/connection/connection-manager.d.ts +18 -1
  25. package/core/connection/login-deadline.d.ts +22 -0
  26. package/core/events/event-hub.d.ts +1 -0
  27. package/core/index.d.ts +8 -1
  28. package/core/message/attachment-downloader.d.ts +1 -1
  29. package/core/session-list-sync/session-list-sync-controller.d.ts +5 -0
  30. package/index.cjs +1 -1
  31. package/index.d.ts +11 -9
  32. package/index.js +2 -2
  33. package/log.d.ts +27 -0
  34. package/managers/chat/index.cjs +1 -1
  35. package/managers/chat/index.js +1 -1
  36. package/managers/chat-thread/index.cjs +1 -1
  37. package/managers/chat-thread/index.js +1 -1
  38. package/managers/chatroom/chatroom.d.ts +1 -1
  39. package/managers/chatroom/index.cjs +1 -1
  40. package/managers/chatroom/index.js +1 -1
  41. package/managers/chatroom-manager.d.ts +6 -1
  42. package/managers/contact/index.cjs +1 -1
  43. package/managers/contact/index.js +1 -1
  44. package/managers/group/index.cjs +1 -1
  45. package/managers/group/index.js +1 -1
  46. package/managers/presence/index.cjs +1 -1
  47. package/managers/presence/index.js +1 -1
  48. package/managers/push/index.cjs +1 -1
  49. package/managers/push/index.d.ts +2 -0
  50. package/managers/push/index.js +1 -1
  51. package/managers/push/native-push-controller.d.ts +62 -0
  52. package/managers/push/native-push-normalizer.d.ts +15 -0
  53. package/managers/push-manager.d.ts +63 -4
  54. package/managers/user-info/index.cjs +1 -1
  55. package/managers/user-info/index.js +1 -1
  56. package/managers/user-info-manager.d.ts +3 -2
  57. package/message/combine-payload-codec.d.ts +2 -1
  58. package/package.json +1 -1
  59. package/platform/index.d.ts +1 -1
  60. package/platform/request/default-request-adapter.d.ts +7 -0
  61. package/platform/socket/default-socket-adapter.d.ts +6 -0
  62. package/platform/types.d.ts +22 -2
  63. package/platform/upload/legacy-multipart-upload.d.ts +14 -0
  64. package/platform/upload/legacy-simple-upload.d.ts +3 -0
  65. package/protocol/msync/codec.d.ts +5 -0
  66. package/rest/client.d.ts +0 -4
  67. package/rest/contact-management.d.ts +1 -0
  68. package/rest/dns-config.d.ts +6 -1
  69. package/rest/error-maps/chatroom.d.ts +6 -0
  70. package/rest/error-maps/common.d.ts +3 -0
  71. package/rest/error-maps/contact.d.ts +8 -3
  72. package/rest/error-maps/push.d.ts +13 -1
  73. package/rest/error-maps/user-info.d.ts +51 -3
  74. package/rest/service-url.d.ts +6 -0
  75. package/types/chat-client.d.ts +16 -9
  76. package/types/chatroom.d.ts +3 -34
  77. package/types/event-system.d.ts +52 -1
  78. package/types/index.d.ts +5 -7
  79. package/types/log.d.ts +19 -0
  80. package/types/manager.d.ts +31 -0
  81. package/types/push.d.ts +77 -0
  82. package/upload/attachment-uploader.d.ts +1 -5
  83. package/upload/multipart-upload.d.ts +4 -14
  84. package/upload/simple-upload.d.ts +4 -3
  85. package/upload/types.d.ts +2 -1
  86. package/utils/error-codes.generated.d.ts +1 -0
  87. package/utils/log-reporter.d.ts +1 -7
  88. package/utils/logger.d.ts +28 -2
  89. package/validators/chat-client.d.ts +22 -50
  90. package/validators/message-create.d.ts +18 -18
  91. package/chunks/common-BIpcR2uQ.cjs +0 -1
  92. package/chunks/common-D_DfwSd3.js +0 -1
  93. package/chunks/event-system-D6IJA0C4.js +0 -1
  94. package/chunks/group-user-info-resolver-Ds35Z1Uf.cjs +0 -1
  95. package/chunks/group-user-info-resolver-lEtRdWli.js +0 -1
  96. package/chunks/index-BmwQgZ3E.js +0 -1
  97. package/chunks/index-BsIqq7LU.cjs +0 -1
  98. package/chunks/index-CFMcR5a_.js +0 -1
  99. package/chunks/light-Dg9A1Xmd.js +0 -1
  100. package/chunks/light-dJjIln5b.cjs +0 -1
package/index.js CHANGED
@@ -1,3 +1,3 @@
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 K,Y as G,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-D_DfwSd3.js";import{R as Se,ap as Ee,aq as be}from"./chunks/common-D_DfwSd3.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-DCqgMxLm.js";import{C as Be}from"./chunks/chat-manager-DCqgMxLm.js";import{R as qe,c as Ke,P as Ge,a as Ve,S as He,m as ze}from"./chunks/group-user-info-resolver-lEtRdWli.js";import{i as je,a as We,L as Qe,e as $e,b as Ye}from"./chunks/reflection-proto-codec-CjRraw85.js";import{l as Je}from"./chunks/light-Dg9A1Xmd.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-CFMcR5a_.js";import{G as rt,a as it}from"./chunks/index-CFMcR5a_.js";import{n as ot}from"./chunks/profile-version-DLMz8lqW.js";import{a as at,t as ct}from"./chunks/session-list-query-rynxSxtv.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-BmwQgZ3E.js";import{C as gt}from"./chunks/index-BmwQgZ3E.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"},Kt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function Gt(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,Ks=13,Gs=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,[Ks]:e.AUTH_LOGIN_TOO_MANY_DEVICES,[Gs]: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,Ks,Gs,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 Ke("Platform missing required capabilities.",{code:Ge.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}}}}}}}}}},Kn=e=>{if(!e||0===e.trim().length)throw Ke("Proto type name is required.",{code:Ge.PROTO_FAILED,stage:Ve.PROTO,retryable:!1,details:{typeName:e}})};class Gn{constructor(){this.codecMap=/* @__PURE__ */new Map}register(e,t){Kn(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 Ke("Proto payload must be an object.",{code:Ge.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 Kn(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Ke("Proto codec not found.",{code:Ge.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 Je.Namespace,$n=e=>e instanceof Je.Type,Yn=e=>{for(const t of e.nestedArray)$n(t)?je(t):Qn(t)&&Yn(t)},Jn=()=>{Vn||(Je.util.Long=Qe,Je.configure(),Vn=!0),We();const e=Je.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 Ke(`Static proto ${s} failed.`,{code:Ge.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 Gn,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 Ke("Request adapter execution failed.",{code:Ge.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 Ke("Socket event listener API is unsupported.",{code:Ge.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 Ke("Socket one-time listener API is unsupported.",{code:Ge.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 Ke("Socket is not open.",{code:Ge.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(Ke("Socket creation failed.",{code:Ge.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(Ke("Socket connection timed out.",{code:Ge.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(Ke("Socket connection failed before open.",{code:Ge.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 Ke("Upload adapter execution failed.",{code:Ge.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 Ke("Web upload adapter only supports web-file source.",{code:Ge.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const s=t.source.file;if(!s)throw Ke("Upload source file is required for web-file uploads.",{code:Ge.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(Ke("Upload adapter execution failed.",{code:Ge.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 Ke("Upload adapter execution failed.",{code:Ge.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 Ke("Upload adapter execution failed.",{code:Ge.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 Ke("React Native upload adapter only supports rn-uri source.",{code:Ge.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===Ge.UPLOAD_FAILED&&t.stage===Ve.UPLOAD})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw Ke("React Native upload adapter execution failed.",{code:Ge.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 Ke("Image decode capability is missing for current platform",{code:Ge.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(Ke("Image decode failed",{code:Ge.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 Ke("Web image processor only supports web file source",{code:Ge.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 Ke("Canvas capability is missing for current platform",{code:Ge.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(s.width,s.height),o=i.getContext("2d");if(!o)throw Ke("Canvas 2d context is missing",{code:Ge.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(Ke("Image encode failed",{code:Ge.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,s)});throw Ke("Canvas encode capability is missing for current platform",{code:Ge.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 Ke("Binary read capability is missing for current platform",{code:Ge.MISSING_CAPABILITY,stage:Ve.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>{s(Ke("Binary read failed",{code:Ge.UPLOAD_FAILED,stage:Ve.RUNTIME,retryable:!1}))},n.onload=()=>{n.result instanceof ArrayBuffer?t(n.result):s(Ke("Binary read returned invalid result",{code:Ge.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 Ke("Miniapp image processor only supports miniapp path source",{code:Ge.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 Ke("Miniapp file system capability is missing",{code:Ge.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 Ke("Miniapp image info read failed",{code:Ge.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 Ke("Miniapp image compress capability is missing",{code:Ge.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 Ke("Miniapp image compress failed",{code:Ge.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 Ke("Miniapp file info read failed",{code:Ge.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 Ke("Miniapp file read failed",{code:Ge.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],Kr=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},Gr=e=>{if(!e)return!1;const t=Kr(e,"name");if(t&&Br.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Kr(e,"message"),Kr(e,"errMsg")].some(e=>null!==e&&qr.some(t=>t.test(e)))},Vr=e=>{if(e instanceof Error)return e;const t=Kr(e,"message")??Kr(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=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,oi=e=>ii(e.statusCode)?e.statusCode:ii(e.status)?e.status:void 0,ai=e=>{if(!ti(e))return{};const t={};return Object.entries(e).forEach(([e,s])=>{"string"==typeof s&&(t[e]=s)}),t},ci=e=>({...ai(e.headers),...ai(e.header)}),di=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},li=e=>{try{e.close()}catch{}},ui=(e,t)=>new Promise((n,r)=>{let i=!1,o=()=>{};const a=(e,s,n)=>{i||(i=!0,o(),r(Ke(e,{code:Ge.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=di(t.signal,()=>{c?.abort(),a("Mini program file download aborted.","abort",!1)})}),hi=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();const i=oi(e);void 0!==i?s({status:i,headers:ci(e),data:e.data}):n(Ke("Mini program request response status is invalid.",{code:Ge.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{r(),n(Ke("Mini program request failed.",{code:Ge.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:ni(e)}}))}});r=di(t.signal,()=>{i.abort(),n(Ke("Mini program request aborted.",{code:Ge.REQUEST_FAILED,stage:Ve.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):ui(e,t)}),pi=(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&&li(i),r(Ke(t,{code:Ge.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 li(r);i=r;const o=()=>{r.offOpen?.(l),r.offError?.(u)},l=()=>{a?li(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 Ke("Mini program socket is not open.",{code:Ge.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(Ke("Mini program socket send failed.",{code:Ge.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))})}),mi=e=>({upload:t=>new Promise((s,n)=>{const r=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw Ke("Mini program upload only supports miniapp-path source.",{code:Ge.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();const o=oi(e);void 0!==o?s({status:o,body:e.data}):n(Ke("Mini program upload response status is invalid.",{code:Ge.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{url:t.url,path:r.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),n(Ke("Mini program upload failed.",{code:Ge.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=di(t.signal,()=>{o.abort(),n(Ke("Mini program upload aborted.",{code:Ge.UPLOAD_FAILED,stage:Ve.UPLOAD,retryable:!1,details:{url:t.url,path:r.path,reason:"abort"}}))})})}),fi=(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(Gr(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=>{Gr(e)?i(Vr(e)):s()}})}catch(r){if(Gr(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()}})}}},gi=(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)}}}),yi=(e,t=qe.WECHAT_MINIAPP,s=t)=>{const n=(e=>{if(si(e,"request")&&si(e,"connectSocket")&&si(e,"uploadFile"))return e;throw Ke("Mini program platform capability is missing.",{code:Ge.MISSING_CAPABILITY,stage:Ve.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),r="function"==typeof n.getImageInfo?Fr(n):void 0;return{request:hi(n),socket:pi(n,s),upload:mi(n),runtime:gi(n,t),storage:fi(n,s),imageProcessor:r}},Ii=[qe.WEB,qe.ELECTRON_RENDERER,qe.REACT_NATIVE],vi=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Ci=e=>Ii.includes(e),Si=(e,t)=>e!==qe.UNIAPP?Ci(e):!On(t)&&!bi(t)&&Rn(t),Ei=e=>vi(e,"getImageInfo")&&vi(e,"getFileSystemManager"),bi=e=>!On(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),Ai=(e,t)=>{if(Ci(e)&&e!==qe.REACT_NATIVE)return _r();if(xn(e)&&Ei(t))return Fr(t);if(e===qe.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Rn(e))return _r();if(Ei(e.uni))return Fr(e.uni);if(Ei(e.wx))return Fr(e.wx)}},Ti=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())}},wi=(e,t,s,n)=>{if(e===qe.UNIAPP&&bi(s)&&void 0!==s.uni&&An(s.uni))return{...yi(s.uni,e,t),proto:tr()};if(((e,t)=>!Si(e,t)&&xn(e))(e,s)&&An(n))return{...yi(n,e,t),proto:tr()};const r=s.XMLHttpRequest,i=Si(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:Ti(s),imageProcessor:i&&e!==qe.REACT_NATIVE?_r():Ai(e,n)}},Ni=(e,t)=>{if(void 0!==e)return e;throw Ke("Platform adapter initialization failed.",{code:Ge.INIT_FAILED,stage:Ve.INIT,retryable:!1,details:{capability:t}})},Mi=(e,t)=>Pn(t,e).platform,Ri=e=>{const s=t(e?.runtimeInput),n=Pn(s,e?.prefer),r=n.platform,i=wi(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:Ni(a.request,"request"),upload:Ni(a.upload,"upload"),socket:Ni(a.socket,"socket"),runtime:Ni(a.runtime,"runtime"),proto:Ni(a.proto,"proto"),storage:Ni(a.storage,"storage"),imageProcessor:a.imageProcessor}},_i={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Ui{constructor(e={}){this.attemptCount=0,this.config={..._i,...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 Di={interval:3e4,timeout:6e4},Oi="function"==typeof TextDecoder?new TextDecoder:null;class Li{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(!Li.isRecord(n))return;"pong"===Li.readString(n.type)&&(this.markAlive(),s.debug("Pong received"))},this.config={...Di,...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)?Oi?.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 ki=null;function Pi(){return ki||(ki=er()),ki}const xi="websdk2:device-info",Fi="webim",Bi="web",qi=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(xi);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(xi,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===Fi){const e=`${Bi}_${s}`,t=d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e});return c(t),t}if(void 0!==r){const e=d({deviceId:`webim_${Bi}_${n}`,deviceName:n,deviceUuid:`${Bi}_${s}`});return c(e),e}const t={deviceId:`webim_${Bi}_${n}`,deviceName:`webim_${Bi}_${n}`,deviceUuid:`webim_${Bi}_${n}`};return c(t),t}if(n===Fi){const e=`random_${Bi}_${s}`;return d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e})}if(void 0!==r){return d({deviceId:`webim_${Bi}_${n}`,deviceName:n,deviceUuid:`random_${Bi}_${s}`})}return{deviceId:`webim_${Bi}_${n}`,deviceName:`webim_${Bi}_${n}`,deviceUuid:`webim_${Bi}_${n}`}},Ki=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Gi=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 Qe(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Vi=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},Hi=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},zi=/* @__PURE__ */new Set(["mute"]),ji={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},Wi=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Qi=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},$i=(e,t)=>{const s=e?.map(e=>Wi(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Yi=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=Qi(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=Qi(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=ji[n];if(!e)continue;let t=r;if(zi.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=Qi(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:Wi(t.operator)??Wi(t.username)}},Zi=(e,t)=>({eventName:e,payload:t}),eo=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=Wi(e.from?.name),n=(r=e.to,Wi(r?.[0]?.name));var r;switch(e.operation){case 1:return Zi(At,t);case 10:return Zi(Nt,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:n??s});case 17:return Zi(Tt,{...t,memberIds:$i(e.members,s),ext:e.ext??e.eventExt});case 18:return Zi(wt,{...t,memberIds:$i(e.members,s)});case 20:return Zi(kt,{...t,oldOwnerId:s,newOwnerId:n});case 21:return Zi(Ot,{...t,adminId:n??s});case 22:return Zi(Lt,{...t,adminId:n??s});case 23:{const s=(e=>{const t=Qi(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):$i(e.members,n),i=46388736e5;return Zi(Mt,{...t,userIds:r,muteMembers:s??Object.fromEntries(r.map(e=>[e,i])),muteExpire:Yi(e.reason,e.eventExt)??i})}case 24:return Zi(Rt,{...t,userIds:$i(e.members,n)});case 25:return Zi(Pt,{...t,announcement:e.reason??""});case 26:return Zi(Pt,{...t,announcement:""});case 29:return Zi(_t,{...t,userIds:$i(e.members,n)});case 30:return Zi(Ut,{...t,userIds:$i(e.members,n)});case 31:return Zi(Dt,{...t,isMuted:!0});case 32:return Zi(Dt,{...t,isMuted:!1});case 14:return Zi(xt,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Ji(e.eventExt)});case 43:{const n=Xi(e.eventExt);return Zi(Ft,{...t,attributes:n.attributes,from:n.from??s})}case 44:{const n=Xi(e.eventExt);return Zi(Bt,{...t,keyList:n.keyList,from:n.from??s})}default:return null}},to=/* @__PURE__ */new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),so={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},no=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ro=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},io=(e,t)=>{const s=e?.map(e=>no(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},oo=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=ro(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},ao=e=>{const t=ro(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=so[n];if(!e)continue;let t=r;if(to.has(n))t=!0===r||"true"===r;else if("max_users"===n){const e=Number(r);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},co=(e,t)=>{const s=ro(t)??ro(e);return st(s??void 0)??void 0},lo=(e,t)=>{const s=ro(t)??ro(e);return no(s?.fileId)??no(s?.file_id)??no(e)??""},uo=(e,t)=>({eventName:e,payload:t}),ho=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=no(e.from?.name),n=(r=e.to,no(r?.[0]?.name));var r;switch(e.operation){case 4:return uo(Xe.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return uo(Xe.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return uo(Xe.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:n,reason:e.reason});case 7:return uo(Xe.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return uo(Xe.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return uo(Xe.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return uo(Xe.USER_REMOVED,t);case 1:return uo(Xe.GROUP_DESTROYED,t);case 19:return uo(Xe.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=ro(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=no(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):io(e.members,n);return uo(Xe.MUTE_LIST_ADDED,{...t,userIds:r,muteExpire:r.map(e=>s?.[e]).find(e=>void 0!==e)??oo(e.reason,e.eventExt)})}case 24:return uo(Xe.MUTE_LIST_REMOVED,{...t,userIds:io(e.members,n)});case 29:return uo(Xe.ALLOW_LIST_ADDED,{...t,userIds:io(e.members,n)});case 30:return uo(Xe.ALLOW_LIST_REMOVED,{...t,userIds:io(e.members,n)});case 31:return uo(Xe.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return uo(Xe.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return uo(Xe.ADMIN_ADDED,{...t,administratorId:n??s});case 22:return uo(Xe.ADMIN_REMOVED,{...t,administratorId:n??s});case 20:return uo(Xe.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:n});case 17:{const n=io(e.members,s);return uo(Xe.MEMBERS_JOINED,{...t,memberIds:n})}case 18:{const n=io(e.members,s);return uo(Xe.MEMBERS_EXITED,{...t,memberIds:n})}case 25:return uo(Xe.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return uo(Xe.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return uo(Xe.SHARED_FILE_ADDED,{...t,sharedFile:co(e.reason,e.eventExt)});case 28:return uo(Xe.SHARED_FILE_DELETED,{...t,fileId:lo(e.reason,e.eventExt)});case 14:return uo(Xe.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:ao(e.eventExt)});case 41:return uo(Xe.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return uo(Xe.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const n=(e=>{const t=ro(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:no(t.username),attribute:n}})(e.eventExt);return uo(Xe.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:n.userId,attribute:n.attribute,from:s,source:e.source??"direct"})}default:return null}},po=/* @__PURE__ */new WeakMap,mo=(e,t)=>{po.set(e,t)},fo=e=>po.get(e)??null,go=(e,t)=>{const s=fo(e);s&&mo(t,s)},yo=/* @__PURE__ */new WeakMap,Io=e=>yo.get(e),vo="singleChat",Co="groupChat",So={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},Eo=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},bo=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}},Ao=e=>{if(!Array.isArray(e))return;const t=e.map(e=>Eo(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},To=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),wo=(...e)=>{for(const t of e){const e=Eo(t);if(e)return e}},No=(e,t)=>Boolean(e&&t&&e===t),Mo=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),Ro=(e,t,s)=>{const n=Ao(e);if(n&&n.length>0)return n;const r=(t??[]).map(e=>Eo(e.name)).filter(e=>"string"==typeof e);if(r.length>0)return r;const i=Eo(s?.name);return i?[i]:[]},_o=e=>{const t=bo(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}}},Uo=(e,t)=>{const n=wo(e.to?.[0]?.clientResource);if(1!==e.to?.length||Eo(e.to[0]?.name)!==t.userId||!Mo(t.userId,n,t))return null;const r=(i=e.from,Eo(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}},Do=(e,t)=>{if(!e.groupId)return s.warn("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const n=wo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Mo(Eo(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=Ro(e.members,e.to,e.from);return{category:"group",operation:r,groupId:e.groupId,userIds:i.length>0?i:void 0,operatorId:Eo(e.from?.name),groupName:e.groupName,deviceId:n,timestamp:e.timestamp,raw:e.raw}},Oo=(e,t)=>{if(!e.threadId)return s.warn("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const n=wo(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Mo(Eo(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=Ro(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:Eo(e.from?.name),threadName:e.threadName,deviceId:n,timestamp:e.timestamp,raw:e.raw}},Lo=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const n=wo(e.res,e.raw?.resource,e.raw?.clientResource);if(No(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?vo:Co;var i;const o=Eo(e.id)??(r===vo?Eo(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?_o(e.ext):void 0,operatorId:Eo(e.from),deviceId:n,timestamp:bo(e.ts),raw:e.raw}},ko=(e,t)=>{const n=wo(e.resource,e.raw?.resource,e.raw?.clientResource);if(No(n,t.clientResource))return s.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const r=Eo(e.to);if(!r)return s.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const i=Eo(e.lastMsgId),o=Ao(e.msgIdList)??(i?[i]:void 0),a=bo(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?Co:vo,messageIds:o,beforeTimestamp:a,deviceId:n,raw:e.raw}},Po=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var xo=4096,Fo=65547,Bo=15,qo=2113929216,Ko=65536,Go=65536,Vo=10485760,Ho={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},zo={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function jo(e){if(!(e>0))return Go;if(e<=Go)return Go;if(e>1073741823)return e;for(var t=Go;t<e;)t*=2;return t}var Wo={byU16:0,byU32:1},Qo=0,$o=1,Yo=2,Jo=0,Xo=1;function Zo(e,t){return e[t]|e[t+1]<<8}function ea(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function ta(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var sa="fast";function na(e){return 2654435761*(e>>>0)>>>20&4095}function ra(e){return 2654435761*(e>>>0)>>>19&8191}function ia(e,t,s){if("fast"===sa){var n=ea(e,t);return s===Wo.byU16?ra(n):na(n)}throw new Error("Unsupported hash strategy: "+sa)}function oa(e,t,s,n,r){s[t]=e-r}function aa(e,t,s,n,r){oa(t,ia(e,t,n),s,0,r)}function ca(e,t,s,n){return t[e]+n}function da(e,t,s,n,r){return ca(ia(e,t,n),s,0,r)}function la(e,t,s,n){for(var r=t;t<n-3;){if(ea(e,t)!==ea(e,s)){for(;t<n&&e[t]===e[s];)t++,s++;return t-r}t+=4,s+=4}for(;t<n&&e[t]===e[s];)t++,s++;return t-r}function ua(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>qo)return 0;switch(c){case Qo:default:l=n,u=n;break;case $o:l=n-e.currentOffset,u=n-e.dictSize;break;case Yo:l=n-e.currentOffset,u=n}if(a===Wo.byU16&&r>=Fo)return 0;if(r<13)return ma(t,s,C,S,A,T,o);aa(t,m,p,a,l),h=ia(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 ma(t,s,C,S,A,T,o);N=ca(D,p,0,l),c===Yo&&(N<n?(w=v,u=y):(w=0,u=n)),h=ia(t,R,a),oa(m,D,p,0,l)}while(d===Xo&&N<f||a!==Wo.byU16&&N+65535<m||!ha(t,g,m,N,w,c,n));for(;m>C&&N+w>u;){var O=N+w-1;if(t[m-1]!==(c===Yo&&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>=Bo){var k=L-Bo;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(ta(s,A,m-N),A+=2,c===Yo&&N<n){var F=m+(I-(N+w));if(F>b&&(F=b),(m+=4+(x=pa(t,g,m+4,N+w+4-y+e.dictionaryStart,F,I-y)))===F&&F<b){var B=la(t,m,n,b);x+=B,m+=B}}else m+=4+(x=la(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(aa(t,m-2,p,a,l),N=da(t,m,p,a,l),c===Yo&&(N<n?(w=v,u=y):(w=0,u=n)),aa(t,m,p,a,l),!((d!==Xo||N>=f)&&N+65535>=m&&ha(t,g,m,N,w,c,n)))break t;s[M=A++]=0}h=ia(t,++m,a)}return ma(t,s,C,S,A,T,o)}function ha(e,t,s,n,r,i,o){var a,c=ea(e,s);i===Yo&&n+r<o?a=ea(t,n+r):a=ea(e,n+r);return c===a}function pa(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 ma(e,t,s,n,r,i,o){var a=n-s;if(o&&r+a+1+Math.floor((a+255-Bo)/255)>i)return 0;if(a>=Bo){for(t[r++]=240,a-=Bo;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 fa(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 ga(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)===Bo){var A=fa(e,N={ip:p},m-Bo,!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=Zo(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=fa(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===Yo&&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 ya(){return{hashTable:new Uint32Array(xo),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function Ia(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function va(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:Jo;return e.dictionary&&c===n?(l=ua(e,t,s,n,r,o||0,a||!1,Wo.byU32,$o,h),e.dictSize+=r,e.currentOffset+=r,l):(l=ua(e,t,s,n,r,o||0,a||!1,Wo.byU32,Yo,h),e.dictionary=t,e.dictionaryStart=n,e.dictSize=r,e.currentOffset+=r,l)}function Ca(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 Sa(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function Ea(e,t,s,n){return e.prefixSize=n,e.prefixEnd=s+n,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function ba(e,t,s,n,r,i,o){var a;if(e.prefixEnd===i){if((a=ga(t,s,n,r,i,o,!0,0,0,Yo,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=ga(t,s,n,r,i,o,!0,0,0,Yo,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function Aa(e){var t=(e=e||{}).minWorkArea||Go,s=e.maxWorkArea||Vo,n=e.shrinkThreshold||t;t<Go&&(t=Go),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=Ko+t,this.maxBufferSize=Ko+s,this.shrinkThreshold=Ko+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ho.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=ya()}function Ta(e){var t=(e=e||{}).minWorkArea||Go,s=e.maxWorkArea||Vo,n=e.shrinkThreshold||t;t<Go&&(t=Go),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=Ko+t,this.maxBufferSize=Ko+s,this.shrinkThreshold=Ko+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ho.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Aa.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<Ko?this.offset:Ko,r=this.offset>Ko?this.offset-Ko:0;t.set(this.ringBuffer.subarray(r,r+n),0),Ca(this.stream,t,0,n),s=n}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Aa.prototype.compress=function(e,t){var s=e.length;if(s<=0)return zo.PARAM_ERROR;if(s>this.maxBufferSize-Ko)return zo.PARAM_ERROR;if(s>this.ringBufferSize-Ko){var n=jo(s),r=Ko+n;if(r>this.maxBufferSize&&(r=this.maxBufferSize),!this._resizeBuffer(r))return zo.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(Ca(this.stream,this.ringBuffer,0,Ko),this.offset=Ko);var i=this.offset;this.ringBuffer.set(e,i);var o=va(this.stream,this.ringBuffer,t,i,s,0,t.length,!0);return o<=0?zo.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),o)},Aa.prototype.reset=function(){this.offset=0,Ia(this.stream)},Aa.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Aa.prototype._tryAutoShrink=function(){this.shrinkMode!==Ho.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ho.AUTO_IMMEDIATE||this.shrinkMode===Ho.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Aa.prototype.getWorkArea=function(){return this.ringBufferSize-Ko},Aa.prototype.getRingBufferSize=function(){return this.ringBufferSize},Aa.prototype.getBaseBufferSize=function(){return this.minBufferSize},Aa.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Aa.prototype.getCurrentOffset=function(){return this.offset},Aa.prototype.getShrinkMode=function(){return this.shrinkMode},Aa.prototype.setShrinkMode=function(e){this.shrinkMode=e},Aa.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Aa.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Ko,s=this.maxBufferSize-Ko;if(e<t||e>s)return zo.PARAM_ERROR;this.shrinkThreshold=Ko+e},Ta.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<Ko?this.offset:Ko,r=this.offset>Ko?this.offset-Ko:0;t.set(this.ringBuffer.subarray(r,r+n),0),s=n,Ea(this.streamDecode,0,0,n)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Ta.prototype.decompress=function(e,t,s){var n=e.length;if(n<=0||s<=0)return zo.PARAM_ERROR;if(s>this.maxBufferSize-Ko)return zo.PARAM_ERROR;if(s>this.ringBufferSize-Ko){var r=jo(s),i=Ko+r;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return zo.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var o=this.offset-Ko;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+Ko),0),Ea(this.streamDecode,this.ringBuffer,0,Ko),this.offset=Ko}var a=ba(this.streamDecode,e,this.ringBuffer,0,n,this.offset,s);return a<=0?zo.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Ta.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Ta.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Ta.prototype._tryAutoShrink=function(){this.shrinkMode!==Ho.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ho.AUTO_IMMEDIATE||this.shrinkMode===Ho.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Ta.prototype.getWorkArea=function(){return this.ringBufferSize-Ko},Ta.prototype.getRingBufferSize=function(){return this.ringBufferSize},Ta.prototype.getBaseBufferSize=function(){return this.minBufferSize},Ta.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Ta.prototype.getCurrentOffset=function(){return this.offset},Ta.prototype.getShrinkMode=function(){return this.shrinkMode},Ta.prototype.setShrinkMode=function(e){this.shrinkMode=e},Ta.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Ta.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Ko,s=this.maxBufferSize-Ko;if(e<t||e>s)return zo.PARAM_ERROR;this.shrinkThreshold=Ko+e};const wa={LZ4_MAX_INPUT_SIZE:qo,BLOCK_MAX_SIZE:65536,DICT_SIZE:Ko,DEFAULT_WORK_AREA:Go,DEFAULT_MAX_WORK:Vo,SHRINK_MODE:Ho,LZ4_ERROR:zo,alignToPowerOf2:jo,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".');sa=e},getHashStrategy:function(){return sa},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>qo)return 0;if(0===n)return t.length>r?(t[r]=0,1):0;var i=n<Fo?Wo.byU16:Wo.byU32;return ua({hashTable:new Uint32Array(i===Wo.byU16?8192:xo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,0,!1,i,Qo,Jo)},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>qo)return 0;if(i<1)return 0;if(0===n)return t[r]=0,1;var o=n<Fo?Wo.byU16:Wo.byU32;return ua({hashTable:new Uint32Array(o===Wo.byU16?8192:xo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,i,!0,o,Qo,Jo)},compressBound:function(e){return e<0||e>qo?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:ga(e,t,s,n,r,i,!0,0,0,Qo,r,null,0))},decompressFast:function(e,t,s,n,r){return ga(e,t,s=s||0,0,n=n||0,r,!1,0,0,$o,n-65536,0,65536)},createStream:ya,resetStream:Ia,loadDict:function(e,t,s,n){if(e.initCheck&&Ia(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;)aa(t,i,e.hashTable,Wo.byU32,r),i+=3;return n},compressContinue:va,saveDict:Ca,createStreamDecode:Sa,setStreamDecode:Ea,decompressSafeContinue:ba,RingBufferEncoder:Aa,RingBufferDecoder:Ta,_hashU16:ra,_hashU32:na,_TABLE_TYPE:Wo},Na=268435455,Ma=new Uint32Array(256);let Ra=!1;function _a(e){!function(){if(!Ra){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;Ma[e]=t>>>0}Ra=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const n=e[s]??0;t=t>>>8^(Ma[255&(t^255&n)]??0)}return(4294967295^t)>>>0}var Ua=/* @__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))(Ua||{});const Da=268435455;class Oa{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:wa.DEFAULT_WORK_AREA,maxWorkArea:wa.DEFAULT_MAX_WORK,shrinkMode:wa.SHRINK_MODE.MANUAL};this.encoder=new wa.RingBufferEncoder(e),this.decoder=new wa.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>Da)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=wa.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>Na)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=_a(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>Da)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=_a(o);if(c!==r)throw new Error(`CRC32 checksum mismatch: expected ${r}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const La=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ka=(e,t)=>$e(e,t).finish();class Pa{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=qi({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=Pi(),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,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=ka(t,r),o={version:0,guid:Ki({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 ka(s,o)}encodeHeartbeat(){const e=Pi(),t=e.lookupType("easemob.pb.CommUnreadUL"),s=e.lookupType("easemob.pb.MSync"),r=ka(t,{}),i={version:0,encryptType:[Ts],command:Ht,payload:r,traceId:n()};return ka(s,i)}encodeStatisticRebuild(){const e=Pi(),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=ka(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=ka(r,c);return ka(i,{version:0,encryptType:[Ts],command:Vt,payload:d,traceId:n()})}decodeProvision(e){const t=Pi().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=Pi().lookupType("easemob.pb.Logout").decode(e),s=t.status&&"object"==typeof t.status?t.status:void 0;return{sessionId:"string"==typeof t.sessionId?t.sessionId:void 0,reason:"string"==typeof t.reason?t.reason:void 0,statusCode:"number"==typeof s?.errorCode?s.errorCode:void 0}}decodeSyncStatisticOperations(e){const t=Pi().lookupType("easemob.pb.CommSyncDL").decode(e),s=Array.isArray(t.metas)?t.metas:[],n=[];for(const r of s){const e=this.decodeStatisticMeta(r);e&&n.push(e)}return n}decodeMsync(e){const t=Pi().lookupType("easemob.pb.MSync").decode(e);return{command:"number"==typeof t.command?t.command:-1,payload:this.normalizeBinaryPayload(t.payload)}}normalizeBinaryPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array}decodeSync(e){const t=Pi(),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=Gi(i.metaId),d=Gi(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(Gi(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=>Gi(e)).filter(e=>Boolean(e)),t=Gi(r.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!h)return null;const n=Hi(Array.isArray(r.ext)?r.ext.filter(La):void 0),i=La(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=Gi(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=Gi(r.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=Gi(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:Hi(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=Pi(),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(!La(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(!La(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=Pi(),t=e.lookupType("easemob.pb.StatisticsBody").decode(n);return{operation:"number"==typeof t.operation?t.operation:-1,reason:"string"==typeof t.reason?t.reason:void 0}}catch{return null}}decodeRosterMeta(e,t){try{const s=Pi(),n=s.lookupType("easemob.pb.RosterBody").decode(t),r="number"==typeof n.operation?n.operation:-1,i=this.readRosterJid(n.from),o=this.readRosterJidList(n.to),a="string"==typeof n.reason?n.reason:"",c="string"==typeof n.rosterVer&&n.rosterVer.trim().length>0?n.rosterVer:void 0,d=i.name??"",l=o[0]?.name??"";if(!d&&!l)return[];const u=Uo({operation:r,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:n},this.msyncCodecContext());if(u)return[this.createMultiDeviceNotify(u)];const h=this.mapRosterOperationToEvent(r,{from:d,to:l,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const s=Pi(),n=s.lookupType("easemob.pb.MUCBody").decode(t),r="number"==typeof n.operation?n.operation:-1,i=!0===n.isChatroom,o=!0===n.isThread,a=this.readJid(n.from),c=Array.isArray(n.to)?n.to.map(e=>this.readJid(e)):[],d=n.eventInfo&&"object"==typeof n.eventInfo?n.eventInfo:void 0,l=Array.isArray(n.members)?n.members.filter(e=>"string"==typeof e):[],u=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=Oo({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=Do({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?eo({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}):ho({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&&yo.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:La(r.data)?r.data:r}}]}if("conv"===i){const e=La(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=Lo({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=La(r.data)?r.data:r,t=ko({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(!To(n))continue;const e=wo(n.operator_resource,n.resource,n.clientResource);if(No(e,t.clientResource))continue;const r=Eo(n.group)??Eo(n.user);if(!r||!To(n.data))continue;const i=Eo(n.group)?Co:vo,o=n.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:r,conversationType:i,remindType:Eo(o.type),silentMode:o,deviceId:e,raw:n})}return s})(La(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(Gi(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:Po(e.category),data:e}}decodeNotice(e){const t=Pi().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Pi().lookupType("easemob.pb.CommUnreadDL").decode(e);return{queues:(Array.isArray(t.unread)?t.unread:[]).map(e=>e&&"object"==typeof e?e:null).map(e=>e?.queue&&"object"==typeof e.queue?e.queue:null).filter(e=>Boolean(e))}}encodeBackQueue(e){const t=Pi(),s=t.lookupType("easemob.pb.CommSyncUL"),r=t.lookupType("easemob.pb.MSync"),i=ka(s,{queue:e}),o={version:0,encryptType:[Ts],command:Vt,payload:i,traceId:n()};return ka(r,o)}encodeLastSession(e,t){const s=Pi(),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o=ka(r,{queue:e,key:t}),a={version:0,encryptType:[Ts],command:Vt,payload:o,traceId:n()};return ka(i,a)}encodeChatMessage(e,t){const s=Pi(),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:Vi(e.ext??{}),...d?{meta:d}:{},...c,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},h=ka(r,u),p="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",m=this.resolveDirectedUsers(e),f=this.resolveMetaExt(e),g={id:t,to:Ki({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=ka(i,{meta:g}),I={version:0,encryptType:[Ts],command:Vt,payload:y,traceId:n()};return ka(o,I)}encodeActionMessage(e,t){const r=Pi(),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:Vi(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=ka(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:Ki({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=ka(o,{meta:p}),f={version:0,encryptType:[Ts],command:Vt,payload:m,traceId:n()};return ka(a,f)}encodeChatRoomOperation(e,t){const s=Pi(),r=s.lookupType("easemob.pb.MUCBody"),i=s.lookupType("easemob.pb.CommSyncUL"),o=s.lookupType("easemob.pb.MSync"),a={mucId:Ki({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=ka(r,a),d={id:t,from:Ki({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=ka(i,{meta:d}),u={version:0,encryptType:[Ts],command:Vt,payload:l,traceId:n()};return ka(o,u)}decodeServerMessageMeta(e){const t=Pi(),s=t.lookupType("easemob.pb.Meta"),n=t.lookupType("easemob.pb.MessageBody");try{const t=s.decode(e);return this.decodeChatMeta(t,n)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?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=Qe.fromString("1099511628211",!0);let s=Qe.fromString("1469598103934665603",!0);for(let n=0;n<e.length;n+=1)s=s.xor(Qe.fromInt(e.charCodeAt(n),!0)).multiply(t).toUnsigned();return s.isZero()?"1":s.toString()})(e)}decodeChatRoomJoinInfo(e){const t=Pi().lookupType("easemob.pb.MUCBody");for(const r of e){if(!La(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(!La(e)||!La(e.status))continue;const s=e.status.chatroomInfo;if("string"!=typeof s||""===s)continue;const n=JSON.parse(s);if(!La(n))continue;const r=n[this.context.userId];if(!La(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=Gi(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:Gi(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=Hi(t.ext),h=Hi(e.ext),p=Number(Gi(e.timestamp))||Date.now(),m=Gi(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)};mo(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=fo(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(Gi(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(Gi(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?Kt.ERROR:e===hs?Kt.START:e===ps?Kt.START_COMPLETED:e===fs?Kt.COMPLETED:e===gs?Kt.FULL:Kt.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:Vi(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=Hi(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?Vi({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(!La(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(!La(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(!La(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(!La(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=La(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:La(r?.ext)?r.ext:{},timestamp:n,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(La(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:La(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 La(e)?e:null}catch{return null}}if(La(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return La(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(La).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 Oa);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===Ua.UPLINK_ONLY||s===Ua.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===Ua.DOWNLINK_ONLY||s===Ua.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Ua.UPLINK_ONLY:1===e?Ua.DOWNLINK_ONLY:2===e?Ua.BIDIRECTIONAL:Ua.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Ua.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}class xa{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 Pa({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 Ui({maxAttempts:this.config.autoReconnectNumMax,initialDelay:h,maxDelay:u,backoffMultiplier:l}),this.heartbeatManager=new Li({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 Ke("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 Fa=new Uint8Array([99,109]),Ba=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qa=e=>Array.isArray(e)&&e.every(Ba),Ka=e=>"string"==typeof e?e:void 0,Ga=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Va=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},Ha=(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},za=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},ja=(e,t)=>{const s=Pi().lookupType(e).decode(t);if(!Ba(s))throw new Error(`${e} decoded result is invalid`);return s},Wa=e=>Ba(e)&&"string"==typeof e.name?e.name:"",Qa=(e,t,s)=>{const n=(qa(e.contents)?e.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const r=(e=>{const t=Ga(e.type)??ns,s=Boolean(Ka(e.remotePath))||Boolean(Ka(e.title))||Boolean(Ka(e.summary))||(Ga(e.combineLevel)??0)>0,n=t===ns&&0===e.subType&&s;if(t===us||n){const t=Ga(e.combineLevel)??0;return{type:"combine",body:{title:Ka(e.title)??"",summary:Ka(e.summary)??"",filename:Ka(e.displayName)??"combine",filetype:"application/octet-stream",url:Ka(e.remotePath),secret:Ka(e.secretKey),fileLength:Ga(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ns)return{type:"text",body:{content:Ka(e.text)??""}};if(t===ds)return{type:"cmd",body:{action:Ka(e.action)??""}};if(t===ls){const t=Hi(qa(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:Ka(e.customEvent)??"",params:t}}}if(t===os)return{type:"location",body:{latitude:Ga(e.latitude)??0,longitude:Ga(e.longitude)??0,address:Ka(e.address),buildingName:Ka(e.buildingName)}};if(t===rs){const t=Ba(e.size)?e.size:{},s=Ka(e.remotePath)??"",n=a(s),r=Ka(e.thumbnailRemotePath),c=i(e.imageType)===o;return{type:"image",body:{localUrl:"",filename:Ka(e.displayName)??"image",filetype:"application/octet-stream",width:Ga(t.width)??0,height:Ga(t.height)??0,isGif:1===e.subType,isOriginalImage:c,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:Ka(e.secretKey),fileLength:Ga(e.fileLength),thumbnailUrl:r??n.thumbnailUrl}}}if(t===is){const t=Ba(e.size)?e.size:{};return{type:"video",body:{url:Ka(e.remotePath)??"",filename:Ka(e.displayName)??"video",filetype:"application/octet-stream",duration:Ga(e.duration)??0,width:Ga(t.width),height:Ga(t.height),secret:Ka(e.secretKey),fileLength:Ga(e.fileLength),thumbnailUrl:Ka(e.thumbnailRemotePath)}}}if(t===as)return{type:"voice",body:{url:Ka(e.remotePath)??"",filename:Ka(e.displayName)??"voice",filetype:"application/octet-stream",duration:Ga(e.duration)??0,secret:Ka(e.secretKey),fileLength:Ga(e.fileLength)}};if(t===cs)return{type:"file",body:{url:Ka(e.remotePath)??"",filename:Ka(e.displayName)??"file",filetype:"application/octet-stream",secret:Ka(e.secretKey),fileLength:Ga(e.fileLength)}};return null})(n);if(!r)throw new Error("MessageBody content type is unsupported");const c=Wa(e.from)||Wa(s?.from)||`unknown-${t}`,d=Wa(e.to)||Wa(s?.to)||`unknown-${t}`,l=(u=e.type)===Yt?"groupChat":u===Jt?"chatRoom":"singleChat";var u;const h=d||c,p=Number(Gi(s?.timestamp))||Date.now(),m=Hi(qa(e.ext)?e.ext:void 0),f={msgServerId:Gi(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},$a=(e,t)=>{const s=[];try{const r=ja("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=ja("easemob.pb.MessageBody",i);return Qa(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=ja("easemob.pb.MessageBody",e);return Qa(s,t)}catch(r){s.push(r instanceof Error?r.message:String(r))}try{const s=ja("easemob.pb.MessageBody.Content",e);return Qa({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("; "))},Ya=(t,s)=>{const n=Cn(t);try{const t=JSON.parse(n);if(!Ba(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 $a(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)}})}}},Ja=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=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(Gt(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"};go(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"};go(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 go(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:Ja(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:Ja(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=Fa.length+s.reduce((e,t)=>e+4+t.length,0)+1,r=new Uint8Array(n);let i=0;r.set(Fa,i),i+=Fa.length;for(const e of s){const t=Va(e.length);r.set(t,i),i+=t.length,r.set(e,i),i+=e.length}const o=za(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 go(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};go(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"};go(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 Za{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!==Kt.START&&t.stream.status!==Kt.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 ec{constructor(e,t){this.completedIds=/* @__PURE__ */new Set,this.eventHub=e,this.cache=t??new Za}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===Kt.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?Kt.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===Kt.START_COMPLETED||o===Kt.COMPLETED||o===Kt.ERROR){const t=o===Kt.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?Kt.ERROR:o?Kt.START_COMPLETED:Kt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:r,deltaText:i});this.eventHub.dispatch(Ze.STREAM_MESSAGE,c);const d=a===Kt.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:Kt.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 tc{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 sc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class nc{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new ec(s),this.messageContexts=/* @__PURE__ */new Map,this.recentMessageIds=new tc(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(Gt(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(!sc(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(!sc(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(!sc(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(!sc(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(!sc(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(!sc(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(!sc(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(!sc(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!sc(t.message)||"string"!=typeof t.message.type||!sc(t.message.body)||!sc(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...sc(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)sc(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)!sc(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 rc=e=>e instanceof Error?e.message:String(e);class ic{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<Fa.length+1)throw new I("Combine payload is too short",{code:e.COMBINE_PARSE_FAILED});const s=t.subarray(0,Fa.length);if(s[0]!==Fa[0]||s[1]!==Fa[1])throw new I("Combine payload header is invalid",{code:e.COMBINE_PARSE_FAILED});const n=t.subarray(0,t.length-1),r=za(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=Fa.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=Ha(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=Ya(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:rc(a),url:o}})}}}const oc=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"}},ac=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 cc{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:oc(t),mimeType:ac(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 dc=(e,t,s)=>({Authorization:`Bearer ${e}`,Accept:t,[b]:n(),...s??{}}),lc=async t=>{const n=dc(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)}},uc=(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(dc(n,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{l.setRequestHeader(e,t)}),l.send(p)}),hc=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 lc({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=uc(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 lc({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},pc=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)}),mc=_r(),fc=e=>Object.prototype.toString.call(e),gc=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:fc(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}},yc=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}),Ic=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,vc=e=>"object"==typeof e&&null!==e,Cc=(e,t)=>{const s=vc(t)?t:void 0,n=s?.code===Ge.MISSING_CAPABILITY&&s.stage===Ve.RUNTIME;return"miniapp-path"===e&&(e=>{if(!vc(e))return!1;const t=vc(e.details)?e.details:void 0;return e.code===Ge.MISSING_CAPABILITY&&e.stage===Ve.RUNTIME&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&n};class Sc{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(!Ic(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:gc(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:yc(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:yc(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:yc(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:yc(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:yc(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(!Ic(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=K({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(Cc(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:yc(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:yc(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"}),mc;throw s.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),Ke("Image processor capability is missing for current platform",{code:Ge.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?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 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 Ke("Request capability is missing for current platform",{code:Ge.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(!Ic(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(!Ic(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:yc(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:yc(n.fileInfo),multipartEnabled:d,uploadMode:l?"multipart":"simple"}),l)try{return await hc(c)}catch(u){const e=u instanceof M?u.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return pc(c);throw u}return pc(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(!Ic(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:yc(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 go(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 go(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 go(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 go(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 go(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(!Cc(t.md5FileInfo.source.sourceType,i))throw i;s.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:yc(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 Ec{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 bc="__internal:core";class Ac{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 xa({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),n=e.restBaseUrl?new Sc({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 nc(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new ic(e.platformAdapter?.request),this.attachmentDownloader=new cc(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(bc,{[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 Ec(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(bc),Oe.clear()}}const Tc=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)},wc=e=>{const t=new Uint8Array(Je.util.base64.length(e));return Je.util.base64.decode(e,t,0),t};class Nc{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:Tc(n),ct:Tc(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=wc(t.iv),n=wc(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 Mc="conversationMap",Rc="userInfoMap",_c="groupNamecardMap",Uc="contactRelationMap",Dc="contactVersion",Oc="contactMeta",Lc="sessionListMap",kc="sessionListCheckpoint",Pc="joinedGroupPreview",xc="metadata",Fc=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Bc{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 qc=()=>{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 Kc{constructor(e,t){this.storage=t??Kc.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!Kc.checkAvailable())return null;const e=qc();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=qc();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(Gr(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 Gc={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Vc={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Hc{constructor(){this.items=/* @__PURE__ */new Map,this.versionState=Gc,this.meta=Vc}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"}:Gc}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"}:Vc}}const zc=(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}},jc=(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}},Wc=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 Qc{constructor(){this.items=[]}load(e,t){const s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s}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=zc(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=jc(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:Wc(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 $c=(e,t)=>`${e}:${t}`;class Yc{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($c(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,n){const r=$c(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($c(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=$c(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($c(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=zc(r,e,t),o=new Set(i.removed.map(e=>$c(e.groupId,e.userId)));this.items.clear();for(const a of n)o.has($c(a.groupId,a.userId))||this.items.set($c(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=jc(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>$c(e.groupId,e.userId)));this.items.clear();for(const o of s)i.has($c(o.groupId,o.userId))||this.items.set($c(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 Jc=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Xc=e=>{const t={...e};return delete t.type,t},Zc=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=Jc(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: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}:{}}},ed=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},td=(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 sd{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(td)}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(td)}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=Jc(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:Zc(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:ed(e.marks),readAt:"number"==typeof s.readAt?s.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class nd{constructor(){this.items=/* @__PURE__ */new Map}load(e,t){this.items.clear();for(const s of e){const e=this.normalizeItem(s,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,s){const n=[];for(const r of e){const e=this.items.get(r);e&&(n.push(e),s&&this.items.set(r,{...e,lastAccess:t}))}return n}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const n=this.items.get(e.userId),r=n?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:r,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,s=/* @__PURE__ */new Set){const n=Array.from(this.items.values()),r=n.filter(e=>!s.has(e.userId)),i=zc(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=jc(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 rd=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,id=e=>e.lastMessageAt??e.updatedAt,od=e=>[...e].sort((e,t)=>{const s=rd(t)-rd(e);if(0!==s)return s;const n=id(t)-id(e);return 0!==n?n:e.conversationId.localeCompare(t.conversationId)}),ad=e=>`${e.conversationType}:${e.conversationId}`,cd=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,dd=(e,t)=>((e,t)=>id(t)>id(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:cd(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,ld=e=>{const t=/* @__PURE__ */new Map,s=/* @__PURE__ */new Set;for(const i of e.snapshot)s.add(ad(i));for(const i of e.existing)t.set(ad(i),i);const n=e.snapshot.map(e=>{const s=t.get(ad(e));return s?dd(e,s):e}),r=e.existing.filter(t=>!s.has(ad(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return od([...n,...r])},ud=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],hd=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),pd=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 md{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,ud.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 fd=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class gd{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 Nc(e.appKey,e.userId);this.store=new Kc(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Fc(s,Mc),this.userInfoKey=Fc(s,Rc),this.groupNamecardKey=Fc(s,_c),this.sessionListKey=Fc(s,Lc),this.sessionListCheckpointKey=Fc(s,kc),this.joinedGroupPreviewKey=Fc(s,Pc),this.contactRelationKey=Fc(s,Uc),this.contactVersionKey=Fc(s,Dc),this.contactMetaKey=Fc(s,Oc),this.metadataKey=Fc(s,xc),this.metadataStore=new Bc(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Qc,this.userInfoCache=new nd,this.groupNamecardCache=new Yc,this.sessionListCache=new sd,this.joinedGroupPreviewCache=new nt,this.contactCache=new Hc,this.userInfoRuntimeStore=new md,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=ld({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?hd(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([pd(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=ad(e.nextRecord),s=e.existing.filter(e=>ad(e)!==t);return od([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(!Gr(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(!Gr(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 fd)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=>rd(e)>0),s=/* @__PURE__ */new Map;for(const r of e.incoming)s.set(ad(r),r);const n=t.length>0?e.existing.filter(e=>!s.has(ad(e))&&0===rd(e)):e.existing.filter(e=>!s.has(ad(e)));return od([...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(ld({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=fo(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?hd(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 yd{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 Id={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function vd(e,t){const s=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),n=Math.min(s,t.maxDelay);if(t.jitter){const e=.2*n,t=(2*Math.random()-1)*e;return Math.max(0,n+t)}return n}function Cd(e){return new Promise(t=>setTimeout(t,e))}const Sd=e=>{const t={...e};return delete t.type,t},Ed=(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:Sd(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},bd=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,k as s,o as n,P as r,a as i,q as o,l as a,r as c,f as d,t as l,s as u,I as h,d as p,u as m,H as f,v as g,w as y,x as I,y as v,C,z as S,B as E,M as b,D as T,F as A,G as w,J as N,V as M,b as R,e as _,A as D,N as U,S as L,K as O,U as k,p as P,L as x,O as F,Q as B,T as q,W as K,X as G,Y as V,Z as H,_ as z,$ as j,a0 as W,a1 as $,a2 as Q,a3 as Y,a4 as J,a5 as X,a6 as Z,a7 as ee,a8 as te,a9 as se,aa as ne,ab as re,h as ie,i as oe,ac as ae,ad as ce,ae as de,af as le,ag as ue,ah as he,ai as pe,aj as me,ak as fe,al as ge,am as ye,an as Ie,ao as ve,ap as Ce,aq as Se,ar as Ee,as as be,at as Te,au as Ae,av as we,aw as Ne,ax as Me,ay as Re,az as _e,aA as De,m as Ue,j as Le,aB as Oe,aC as ke,aD as Pe}from"./chunks/common-BvlDAw4a.js";import{R as xe,aE as Fe}from"./chunks/common-BvlDAw4a.js";import{a as Be,b as qe,g as Ke,I as Ge,c as Ve,v as He,d as ze,e as je,f as We,h as $e,i as Qe,M as Ye,j as Je,k as Xe,V as Ze}from"./chunks/chat-manager-CId_M_e5.js";import{C as et}from"./chunks/chat-manager-CId_M_e5.js";import{i as tt,a as st,L as nt,e as rt,b as it}from"./chunks/reflection-proto-codec-7r8Sei3y.js";import{l as ot}from"./chunks/light-DImBnNes.js";import{G as at,C as ct,a as dt,P as lt,L as ut}from"./chunks/event-system-B62vbKqG.js";import{b as ht}from"./chunks/event-system-B62vbKqG.js";import{n as pt,J as mt}from"./chunks/index-l_BUKi77.js";import{G as ft,a as gt}from"./chunks/index-l_BUKi77.js";import{n as yt}from"./chunks/profile-version-DLMz8lqW.js";import{m as It}from"./chunks/group-user-info-resolver-DMccCqez.js";import{a as vt,t as Ct}from"./chunks/session-list-query-Cvr6rlme.js";import{s as St,a as Et,i as bt}from"./chunks/cache-utils-B99glc0H.js";import{z as Tt}from"zod";import{c as At}from"./chunks/query-params-Bu3Xq4b6.js";import{r as wt,R as Nt}from"./chunks/index-BBFJYOM8.js";import{C as Mt}from"./chunks/index-BBFJYOM8.js";import{ChatThread as Rt,ChatThreadManager as _t}from"./managers/chat-thread/index.js";import{ChatRoom as Dt,ChatRoomManager as Ut}from"./managers/chatroom/index.js";import{PresenceManager as Lt}from"./managers/presence/index.js";import{PushManager as Ot}from"./managers/push/index.js";import{UserInfoManager as kt}from"./managers/user-info/index.js";const Pt="onChatRoomDestroyed",xt="onMembersJoined",Ft="onMembersExited",Bt="onRemovedFromChatRoom",qt="onMuteListAdded",Kt="onMuteListRemoved",Gt="onAllowListAdded",Vt="onAllowListRemoved",Ht="onAllMemberMuteStateChanged",zt="onAdminAdded",jt="onAdminRemoved",Wt="onOwnerChanged",$t="onAnnouncementChanged",Qt="onChatRoomInfoChanged",Yt="onAttributesUpdate",Jt="onAttributesRemoved",Xt={ORIGINAL:"original",LARGE:"large"},Zt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function es(e){return"object"==typeof e.stream&&null!==e.stream}const ts=0,ss=1,ns=2,rs=3,is=4,os=0,as=1,cs=2,ds=3,ls=4,us=5,hs=6,ps=7,ms=8,fs=0,gs=1,ys=2,Is=3,vs=4,Cs=5,Ss=6,Es=7,bs=8,Ts=0,As=1,ws=2,Ns=3,Ms=4,Rs=0,_s=1,Ds=2,Us=3,Ls=5,Os=0,ks=1,Ps=2,xs=0,Fs=0,Bs=2,qs=0,Ks=1,Gs=2,Vs=3,Hs=4,zs=5,js=6,Ws=7,$s=8,Qs=9,Ys=10,Js=11,Xs=12,Zs=13,en=14,tn=15,sn=16,nn=17,rn=18,on=19,an=20,cn=1,dn=2,ln=3,un=4,hn=5,pn=6,mn=7,fn=8,gn="Sorry, user register limit",yn="Sorry, user register rate limit",In="Sorry, token expired",vn="Sorry, token or password does not match login info",Cn="Sorry, user not found",Sn="Sorry, the app month live count limit",En="Sorry, the app day live count limit",bn="Sorry, the app online count limit",Tn={[Ks]:e.AUTH_UNAUTHORIZED,[Gs]:e.AUTH_UNAUTHORIZED,[Vs]:e.VALIDATION_REQUIRED,[Hs]:e.VALIDATION_INVALID_FORMAT,[zs]:e.CONNECTION_WEBSOCKET_ERROR,[js]:e.AUTH_TOKEN_EXPIRED,[Ws]:e.AUTH_FORBIDDEN,[on]:e.AUTH_FORBIDDEN,[$s]:e.CONNECTION_WEBSOCKET_ERROR,[Qs]:e.UNKNOWN,[Ys]:e.UNKNOWN,[Js]:e.AUTH_BIND_ANOTHER_DEVICE,[Xs]:e.AUTH_FORBIDDEN,[Zs]:e.AUTH_LOGIN_TOO_MANY_DEVICES,[en]:e.SERVICE_LIMIT_EXCEEDED,[tn]:e.AUTH_USER_MUTED,[sn]:e.UNKNOWN,[nn]:e.UNKNOWN,[rn]:e.MESSAGE_DECODE_FAILED,[an]:e.USER_DEVICE_CHANGED},An=/* @__PURE__ */new Set([Ks,Gs,Vs,Hs,js,Ws,on,Qs,Ys,Js,Xs,Zs,en,tn,sn,nn,rn,an]),wn={[gn]:e.SERVICE_LIMIT_EXCEEDED,[yn]:e.SERVICE_LIMIT_EXCEEDED,[In]:e.AUTH_TOKEN_EXPIRED,[vn]: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},Nn=[["limit directed users",e.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.AUTH_FORBIDDEN]],Mn={[Sn]:e.SERVICE_LIMIT_EXCEEDED,[En]:e.SERVICE_LIMIT_EXCEEDED,[bn]: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},Rn=(t,s)=>{if("number"!=typeof t)return{code:e.UNKNOWN,retryable:!0};const n=((t,s)=>{if(s){if(t===Ks){const t=wn[s];if(void 0!==t)return t;for(const[e,n]of Nn)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===Ws?Mn[s]:t===on?e.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===tn?e.AUTH_USER_MUTED:void 0}})(t,s),r=Tn[t]??e.UNKNOWN;return{code:n??r,retryable:!An.has(t)}},_n={[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"},Dn=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)},Un=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 Ln{constructor(){this.lastEventKey=null}normalize(e,t){const s=(e=>{switch(e){case Be.CONNECTING:case Be.RECONNECTING:return qe.CONNECTING;case Be.CONNECTED:return qe.CONNECTED;case Be.DISCONNECTED:return qe.DISCONNECTED;case Be.RECONNECT_FAILED:return qe.RECONNECT_FAILED;default:return null}})(e);if(!s)return null;const n=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(s,t);return this.lastEventKey===n?null:(this.lastEventKey=n,{eventName:s,payload:t})}reset(){this.lastEventKey=null}}const On={web:s.WEB,"mp-weixin":s.WECHAT_MINIAPP,"mp-alipay":s.ALIPAY_MINIAPP,"mp-baidu":s.BAIDU_MINIAPP,"mp-toutiao":s.TOUTIAO_MINIAPP,"mp-lark":s.LARK_MINIAPP,"mp-qq":s.QQ_MINIAPP,"mp-kuaishou":s.KUAISHOU_MINIAPP,"mp-jd":s.JD_MINIAPP,"mp-360":s.MINIAPP_360,"mp-harmony":s.HARMONY_MINIAPP,"quickapp-webview":s.QUICKAPP,"quickapp-webview-union":s.QUICKAPP,"quickapp-webview-huawei":s.QUICKAPP},kn=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Pn=e=>(e=>kn(e,"canIUse")&&kn(e,"getSystemInfo"))(e)||(e=>kn(e,"request")&&kn(e,"connectSocket"))(e),xn=e=>kn(e,"request")&&kn(e,"connectSocket")&&kn(e,"uploadFile"),Fn=(e,t)=>t===s.WECHAT_MINIAPP?e.wx:t===s.QQ_MINIAPP?e.qq:t===s.TOUTIAO_MINIAPP?e.tt:t===s.BAIDU_MINIAPP?e.swan:t===s.ALIPAY_MINIAPP?e.my:t===s.DINGTALK_MINIAPP?e.dd:t===s.JD_MINIAPP?e.jd:t===s.KUAISHOU_MINIAPP?e.ks:t===s.UNIAPP?e.uni:void 0,Bn=e=>{const t=e?.miniGlobal;return Pn(t)?t:e},qn=e=>{const t=Bn(e);return xn(t)?t:void 0},Kn=e=>void 0!==e.window&&void 0!==e.document,Gn=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),Vn=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(Pn(t))return!0;try{if(!kn(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},Hn=e=>xn(e.wx)?s.WECHAT_MINIAPP:xn(e.my)?s.ALIPAY_MINIAPP:xn(e.dd)?s.DINGTALK_MINIAPP:xn(e.swan)?s.BAIDU_MINIAPP:xn(e.tt)?s.TOUTIAO_MINIAPP:xn(e.qq)?s.QQ_MINIAPP:xn(e.jd)?s.JD_MINIAPP:xn(e.ks)?s.KUAISHOU_MINIAPP:void 0,zn=e=>void 0!==Hn(e),jn=e=>{const t=Hn(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),n=t?.uniPlatform;if("string"==typeof n)return On[n]??s.UNIAPP}catch{return s.UNIAPP}return Kn(e)?s.WEB:s.UNIAPP},Wn=(e,t)=>{const s=qn(Fn(e,t));if(s)return s;const n=qn(e.uni);return n||(e.uni??e)},$n=(e,n)=>{const r=e??t();if(n){const e=n===s.UNIAPP||Vn(r),t=e?jn(r):n;return{platform:n,hostPlatform:t,framework:e?"uniapp":Kn(r)?"web":"native",global:e?Wn(r,t):Bn(Fn(r,n))??r}}if(Vn(r)){const e=jn(r);return{platform:s.UNIAPP,hostPlatform:e,framework:"uniapp",global:Wn(r,e)}}return Pn(r.swan)?{platform:s.BAIDU_MINIAPP,hostPlatform:s.BAIDU_MINIAPP,framework:"native",global:Bn(r.swan)??r.swan}:Pn(r.tt)?{platform:s.TOUTIAO_MINIAPP,hostPlatform:s.TOUTIAO_MINIAPP,framework:"native",global:Bn(r.tt)??r.tt}:Pn(r.dd)?{platform:s.DINGTALK_MINIAPP,hostPlatform:s.DINGTALK_MINIAPP,framework:"native",global:Bn(r.dd)??r.dd}:Pn(r.my)?{platform:s.ALIPAY_MINIAPP,hostPlatform:s.ALIPAY_MINIAPP,framework:"native",global:Bn(r.my)??r.my}:Pn(r.wx)?{platform:s.WECHAT_MINIAPP,hostPlatform:s.WECHAT_MINIAPP,framework:"native",global:Bn(r.wx)??r.wx}:Pn(r.qq)?{platform:s.QQ_MINIAPP,hostPlatform:s.QQ_MINIAPP,framework:"native",global:Bn(r.qq)??r.qq}:Pn(r.jd)?{platform:s.JD_MINIAPP,hostPlatform:s.JD_MINIAPP,framework:"native",global:Bn(r.jd)??r.jd}:Pn(r.ks)?{platform:s.KUAISHOU_MINIAPP,hostPlatform:s.KUAISHOU_MINIAPP,framework:"native",global:Bn(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:s.REACT_NATIVE,hostPlatform:s.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:Kn(r)?s.ELECTRON_RENDERER:s.ELECTRON_MAIN,hostPlatform:Kn(r)?s.ELECTRON_RENDERER:s.ELECTRON_MAIN,framework:"electron",global:r}:Gn(r)||Kn(r)?{platform:s.WEB,hostPlatform:s.WEB,framework:Gn(r)?"worker":"web",global:r}:{platform:s.UNKNOWN,hostPlatform:s.UNKNOWN,framework:"native",global:r}},Qn=e=>e===s.WECHAT_MINIAPP||e===s.QQ_MINIAPP||e===s.TOUTIAO_MINIAPP||e===s.BAIDU_MINIAPP||e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP||e===s.LARK_MINIAPP||e===s.KUAISHOU_MINIAPP||e===s.JD_MINIAPP||e===s.MINIAPP_360||e===s.HARMONY_MINIAPP||e===s.QUICKAPP||e===s.UNIAPP,Yn=["request","upload","socket","proto"],Jn=(e,t=Yn)=>{const s=((e,t=Yn)=>t.filter(t=>!e[t]))(e,t);if(0!==s.length)throw n("Platform missing required capabilities.",{code:r.MISSING_CAPABILITY,stage:i.INIT,retryable:!1,details:{required:[...t],missing:s}})},Xn={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}}}}}}}}}},Zn=e=>{if(!e||0===e.trim().length)throw n("Proto type name is required.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e}})};class er{constructor(){this.codecMap=/* @__PURE__ */new Map}register(e,t){Zn(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:s=>{const o=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw n("Proto payload must be an object.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(s,e),a=t.fromObject(o);return t.encode(a).finish()},decode:e=>{const s=t.decode(e);return t.toObject(s,{longs:String,enums:Number,defaults:!1})}})}get(e){return Zn(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw n("Proto codec not found.",{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e}})}}let tr=!1,sr=null,nr=null,rr=null;const ir=e=>e.startsWith(".")?e.slice(1):e,or=e=>e instanceof ot.Namespace,ar=e=>e instanceof ot.Type,cr=e=>{for(const t of e.nestedArray)ar(t)?tt(t):or(t)&&cr(t)},dr=()=>{tr||(ot.util.Long=nt,ot.configure(),tr=!0),st();const e=ot.Root.fromJSON(Xn);return cr(e),e},lr=(e,t)=>{const s=e.nestedArray;for(const n of s){if(ar(n)){const e=ir(n.fullName);tt(n),t.registerType(e,n);continue}or(n)&&lr(n,t)}},ur=(e,t,s)=>{const o=t instanceof Error?t.message:String(t);return n(`Static proto ${s} failed.`,{code:r.PROTO_FAILED,stage:i.PROTO,retryable:!1,details:{typeName:e,operation:s,cause:o}})},hr=()=>sr||(sr=dr(),sr),pr=()=>{if(rr)return rr;const e=(()=>{if(nr)return nr;const e=new er,t=hr();return lr(t,e),nr=e,e})();return rr={encode(t,s){try{return e.getOrThrow(ir(t)).encode(s)}catch(n){throw ur(t,n,"encode")}},decode(t,s){try{return e.getOrThrow(ir(t)).decode(s)}catch(n){throw ur(t,n,"decode")}}},rr},mr=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,fr=e=>"function"==typeof e.on&&"function"==typeof e.off,gr=(e,t,s)=>{if(mr(e))return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)};if(fr(e)){const n=e;return n.on(t,s),()=>{n.off(t,s)}}throw n("Socket event listener API is unsupported.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!1,details:{event:t}})},yr=(e,t,s)=>{if(mr(e)){const n=(...r)=>{e.removeEventListener(t,n),s(...r)};return e.addEventListener(t,n),()=>{e.removeEventListener(t,n)}}if(fr(e)){const n=e;if("function"==typeof n.once)return n.once?.(t,s),()=>{n.off(t,s)};let r=()=>{};return r=gr(e,t,(...e)=>{r(),s(...e)}),r}throw n("Socket one-time listener API is unsupported.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!1,details:{event:t}})},Ir=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?Ir(e.data):null;var t},vr=e=>{const t=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set,a=/* @__PURE__ */new Set,c=/* @__PURE__ */new Set;return gr(e,"open",()=>{t.forEach(e=>{e()})}),gr(e,"message",(...e)=>{const t=Ir(e[0]);null!==t&&s.forEach(e=>{e(t)})}),gr(e,"error",(...e)=>{const t=e[0];a.forEach(e=>{e(t)})}),gr(e,"close",(...e)=>{const t=(e=>{const[t,s]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof s?s:ArrayBuffer.isView(s)?(new TextDecoder).decode(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)):void 0}})(e);c.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==o.OPEN)throw n("Socket is not open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,s){e.close(t,s)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(s.add(e),()=>{s.delete(e)}),onError:e=>(a.add(e),()=>{a.delete(e)}),onClose:e=>(c.add(e),()=>{c.delete(e)})}},Cr=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((s,o)=>{let a;try{a=new t(e.url,e.protocols);try{a.binaryType="arraybuffer"}catch{}}catch(m){return void o(n("Socket creation failed.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{cause:m instanceof Error?m.message:String(m)}}))}let c,d=()=>{},l=()=>{},u=!1;const h=()=>{void 0!==c&&(clearTimeout(c),c=void 0)},p=()=>{u||(u=!0,d(),l(),h(),a.close(),o(n("Socket connection timed out.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{url:e.url,reason:"timeout"}})))};d=yr(a,"open",()=>{u||(u=!0,d(),l(),h(),s(vr(a)))}),l=yr(a,"error",e=>{if(u)return;u=!0,d(),l(),h();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;o(n("Socket connection failed before open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(c=setTimeout(p,e.timeoutMs))})}},Sr=(e,t)=>{throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:"abort"!==e,details:{reason:e,url:t.url}})},Er=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,s])=>{t.append(e,s)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw n("Web upload adapter only supports web-file source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const s=t.source.file;if(!s)throw n("Upload source file is required for web-file uploads.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const o="undefined"!=typeof Blob&&s instanceof Blob,a=t.source.name??"upload.bin",c=t.fileFieldName??"file";o?e.append(c,s,a):e.append(c,s)})(t,e),t},br=(e,t,s)=>new Promise((o,a)=>{const c=e(),d=s.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const s=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:s})})})(c,s),c.addEventListener("abort",()=>{try{Sr("abort",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("timeout",()=>{try{Sr("timeout",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("error",()=>{try{Sr("network",s)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}),c.addEventListener("load",()=>{o({status:c.status,body:c.responseText})});try{const e=Er(s);c.timeout=d,c.open(s.method??"POST",s.url),((e,t)=>{Object.entries(t??{}).forEach(([t,s])=>{e.setRequestHeader(t,s)})})(c,s.headers),c.send(e)}catch(l){a(n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:s.url,reason:"invalid-config",cause:l instanceof Error?l.message:String(l)}}))}}),Tr=(e,t)=>e?"timeout":"abort",Ar=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,s=e?.fetchImpl;if("function"==typeof t||"function"==typeof s)return{upload(o){if("function"==typeof t)return br(t,e,o);if("function"==typeof s)return(async(e,t,s)=>{const o=s.timeoutMs??t?.timeoutMs??3e4;let a=!1;const c="undefined"!=typeof AbortController?new AbortController:void 0,d=c&&Number.isFinite(o)?setTimeout(()=>{a=!0,c.abort()},o):void 0,l=((e,t)=>e??t?.signal)(s.signal,c);try{const t=Er(s),n=await e(s.url,{method:s.method??"POST",headers:s.headers,body:t,signal:l}),r=await n.text(),i=s.source.size;return"number"==typeof i&&s.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:n.status,body:r}}catch(u){const e=u instanceof Error&&"AbortError"===u.name;throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!e,details:{reason:e?Tr(a):"network",url:s.url,cause:u instanceof Error?u.message:String(u)}})}finally{d&&clearTimeout(d)}})(s,e,o);throw n("Upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{reason:"missing-upload-runtime",url:o.url}})}}},wr=(e,t)=>{const s=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{s.append(e,t)}),s.append(t.fileFieldName??"file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw n("React Native upload adapter only supports rn-uri source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),s},Nr=e=>{const t=e?.fetchImpl,s=e?.formDataCtor;if("function"==typeof t&&"function"==typeof s)return{async upload(o){const a=o.timeoutMs??e?.timeoutMs??3e4,c="function"==typeof AbortController?new AbortController:void 0;let d=!1;const l=c&&Number.isFinite(a)?setTimeout(()=>{d=!0,c.abort()},a):void 0;try{const e=wr(s,o),n=await t(o.url,{method:o.method??"POST",headers:o.headers,body:e,signal:o.signal??c?.signal}),r=await n.text(),i=o.source.size;return"number"==typeof i&&o.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:n.status,body:r}}catch(u){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===r.UPLOAD_FAILED&&t.stage===i.UPLOAD})(u))throw u;const e=u instanceof Error&&"AbortError"===u.name;throw n("React Native upload adapter execution failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!e||d,details:{url:o.url,reason:e?d?"timeout":"abort":"network",cause:u instanceof Error?u.message:String(u)}})}finally{void 0!==l&&clearTimeout(l)}}}},Mr=(e,t)=>e+t&4294967295,Rr=(e,t,s,n,r,i)=>{return Mr((o=Mr(Mr(t,e),Mr(n,i)))<<(a=r)|o>>>32-a,s);var o,a},_r=(e,t,s,n,r,i,o)=>Rr(t&s|~t&n,e,t,r,i,o),Dr=(e,t,s,n,r,i,o)=>Rr(t&n|s&~n,e,t,r,i,o),Ur=(e,t,s,n,r,i,o)=>Rr(t^s^n,e,t,r,i,o),Lr=(e,t,s,n,r,i,o)=>Rr(s^(t|~n),e,t,r,i,o),Or=(e,t)=>{let[s,n,r,i]=e;s=_r(s,n,r,i,t[0]??0,7,-680876936),i=_r(i,s,n,r,t[1]??0,12,-389564586),r=_r(r,i,s,n,t[2]??0,17,606105819),n=_r(n,r,i,s,t[3]??0,22,-1044525330),s=_r(s,n,r,i,t[4]??0,7,-176418897),i=_r(i,s,n,r,t[5]??0,12,1200080426),r=_r(r,i,s,n,t[6]??0,17,-1473231341),n=_r(n,r,i,s,t[7]??0,22,-45705983),s=_r(s,n,r,i,t[8]??0,7,1770035416),i=_r(i,s,n,r,t[9]??0,12,-1958414417),r=_r(r,i,s,n,t[10]??0,17,-42063),n=_r(n,r,i,s,t[11]??0,22,-1990404162),s=_r(s,n,r,i,t[12]??0,7,1804603682),i=_r(i,s,n,r,t[13]??0,12,-40341101),r=_r(r,i,s,n,t[14]??0,17,-1502002290),n=_r(n,r,i,s,t[15]??0,22,1236535329),s=Dr(s,n,r,i,t[1]??0,5,-165796510),i=Dr(i,s,n,r,t[6]??0,9,-1069501632),r=Dr(r,i,s,n,t[11]??0,14,643717713),n=Dr(n,r,i,s,t[0]??0,20,-373897302),s=Dr(s,n,r,i,t[5]??0,5,-701558691),i=Dr(i,s,n,r,t[10]??0,9,38016083),r=Dr(r,i,s,n,t[15]??0,14,-660478335),n=Dr(n,r,i,s,t[4]??0,20,-405537848),s=Dr(s,n,r,i,t[9]??0,5,568446438),i=Dr(i,s,n,r,t[14]??0,9,-1019803690),r=Dr(r,i,s,n,t[3]??0,14,-187363961),n=Dr(n,r,i,s,t[8]??0,20,1163531501),s=Dr(s,n,r,i,t[13]??0,5,-1444681467),i=Dr(i,s,n,r,t[2]??0,9,-51403784),r=Dr(r,i,s,n,t[7]??0,14,1735328473),n=Dr(n,r,i,s,t[12]??0,20,-1926607734),s=Ur(s,n,r,i,t[5]??0,4,-378558),i=Ur(i,s,n,r,t[8]??0,11,-2022574463),r=Ur(r,i,s,n,t[11]??0,16,1839030562),n=Ur(n,r,i,s,t[14]??0,23,-35309556),s=Ur(s,n,r,i,t[1]??0,4,-1530992060),i=Ur(i,s,n,r,t[4]??0,11,1272893353),r=Ur(r,i,s,n,t[7]??0,16,-155497632),n=Ur(n,r,i,s,t[10]??0,23,-1094730640),s=Ur(s,n,r,i,t[13]??0,4,681279174),i=Ur(i,s,n,r,t[0]??0,11,-358537222),r=Ur(r,i,s,n,t[3]??0,16,-722521979),n=Ur(n,r,i,s,t[6]??0,23,76029189),s=Ur(s,n,r,i,t[9]??0,4,-640364487),i=Ur(i,s,n,r,t[12]??0,11,-421815835),r=Ur(r,i,s,n,t[15]??0,16,530742520),n=Ur(n,r,i,s,t[2]??0,23,-995338651),s=Lr(s,n,r,i,t[0]??0,6,-198630844),i=Lr(i,s,n,r,t[7]??0,10,1126891415),r=Lr(r,i,s,n,t[14]??0,15,-1416354905),n=Lr(n,r,i,s,t[5]??0,21,-57434055),s=Lr(s,n,r,i,t[12]??0,6,1700485571),i=Lr(i,s,n,r,t[3]??0,10,-1894986606),r=Lr(r,i,s,n,t[10]??0,15,-1051523),n=Lr(n,r,i,s,t[1]??0,21,-2054922799),s=Lr(s,n,r,i,t[8]??0,6,1873313359),i=Lr(i,s,n,r,t[15]??0,10,-30611744),r=Lr(r,i,s,n,t[6]??0,15,-1560198380),n=Lr(n,r,i,s,t[13]??0,21,1309151649),s=Lr(s,n,r,i,t[4]??0,6,-145523070),i=Lr(i,s,n,r,t[11]??0,10,-1120210379),r=Lr(r,i,s,n,t[2]??0,15,718787259),n=Lr(n,r,i,s,t[9]??0,21,-343485551),e[0]=Mr(s,e[0]),e[1]=Mr(n,e[1]),e[2]=Mr(r,e[2]),e[3]=Mr(i,e[3])},kr=(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},Pr=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},xr=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)Or(t,kr(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&&(Or(t,n),n.fill(0));const o=8*e.length;return n[14]=4294967295&o,n[15]=Math.floor(o/4294967296),Or(t,n),t.map(Pr).join("")},Fr=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw n("Image decode capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,s)=>{const o=new Image;o.onload=()=>{e({image:o,width:o.naturalWidth||o.width,height:o.naturalHeight||o.height,cleanup:()=>{URL.revokeObjectURL(t)}})},o.onerror=()=>{URL.revokeObjectURL(t),s(n("Image decode failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{reason:"image load error"}}))},o.src=t})},Br=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw n("Web image processor only supports web file source",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.file},qr=()=>({async getImageInfo(e){const t=Br(e),s=await Fr(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=Br(e),o=await Fr(s);try{const s=((e,t,s)=>{const n=Math.min(e,t);if(n<=s)return{width:e,height:t};const r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}})(o.width,o.height,t.maxShortEdge),c=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const s=document.createElement("canvas");return s.width=e,s.height=t,s}throw n("Canvas capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(s.width,s.height),d=c.getContext("2d");if(!d)throw n("Canvas 2d context is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1});d.drawImage(o.image,0,0,s.width,s.height);const l="image/png"===(a=e.mimeType)||"image/webp"===a?a:"image/jpeg",u=await(async(e,t,s)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:s});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((o,a)=>{e.toBlob(e=>{e?o(e):a(n("Image encode failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,s)});throw n("Canvas encode capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"canvas encode unavailable"}})})(c,l,t.quality),h=(e=>e.name??"image")(e),p="undefined"!=typeof File?new File([u],h,{type:l,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:p??u,name:h,mimeType:l,size:p?.size??u.size},width:s.width,height:s.height,fileName:h,fileType:l,fileSize:p?.size??u.size,webFile:p}}finally{o.cleanup()}var a},async computeMd5(e){const t=Br(e),s=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw n("Binary read capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,s)=>{const o=new FileReader;o.onerror=()=>{s(n("Binary read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1}))},o.onload=()=>{o.result instanceof ArrayBuffer?t(o.result):s(n("Binary read returned invalid result",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1}))},o.readAsArrayBuffer(e)})})(t);return xr(new Uint8Array(s))}}),Kr=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)},Gr=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw n("Miniapp image processor only supports miniapp path source",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.path},Vr=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw n("Miniapp file system capability is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"getFileSystemManager"}})},Hr=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},zr=async(e,t)=>new Promise((s,n)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{n(e instanceof Error?e:new Error(Kr(e)))}})}).catch(e=>{throw n("Miniapp image info read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{src:t,cause:Kr(e)}})}),jr=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,Wr=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await zr(e,t);return jr(t,s)},$r=e=>({async getImageInfo(t){const s=Gr(t),n=await zr(e,s),r=Hr(n.type)??t.mimeType;return{width:n.width,height:n.height,mimeType:r,fileSize:t.size,isGif:"image/gif"===r}},async generateBigImage(t,s){const o=Gr(t);if("function"!=typeof e.compressImage)throw n("Miniapp image compress capability is missing",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"compressImage"}});const a=await zr(e,o),c=jr(o,a),d=((e,t,s)=>{const n=Math.min(e,t);if(n<=s)return{width:e,height:t};const r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}})(a.width,a.height,s.maxShortEdge),l=await new Promise((t,n)=>{e.compressImage?.({src:c,quality:Math.max(0,Math.min(100,Math.round(100*s.quality))),compressedWidth:d.width,compressedHeight:d.height,success:e=>{e.tempFilePath?t(e.tempFilePath):n(new Error("compressImage missing tempFilePath"))},fail:e=>{n(e instanceof Error?e:new Error(Kr(e)))}})}).catch(e=>{throw n("Miniapp image compress failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{src:c,cause:Kr(e)}})}),u=await Wr(e,l),h=await zr(e,u),p=Hr(h.type)??t.mimeType,m=await(async(e,t,s)=>{const o=Vr(e);return o.getFileInfo?new Promise((e,s)=>{o.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{s(e instanceof Error?e:new Error(Kr(e)))}})}).catch(e=>{throw n("Miniapp file info read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{filePath:t,cause:Kr(e)}})}):s})(e,u,t.size);return{source:{sourceType:"miniapp-path",path:u,name:t.name,mimeType:p,size:m},width:h.width,height:h.height,fileName:t.name,fileType:p,fileSize:m}},async computeMd5(t){const s=Gr(t),o=await Wr(e,s),a=await(async(e,t)=>{const s=Vr(e),o=await new Promise((e,n)=>{s.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{n(e instanceof Error?e:new Error(Kr(e)))}})}).catch(e=>{throw n("Miniapp file read failed",{code:r.UPLOAD_FAILED,stage:i.RUNTIME,retryable:!1,details:{filePath:t,cause:Kr(e)}})});return o instanceof ArrayBuffer?new Uint8Array(o):"function"==typeof TextEncoder?(new TextEncoder).encode(o):Uint8Array.from(Array.from(o).map(e=>255&e.charCodeAt(0)))})(e,o);return xr(a)}}),Qr=/* @__PURE__ */new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),Yr=[/\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],Jr=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},Xr=e=>{if(!e)return!1;const t=Jr(e,"name");if(t&&Qr.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Jr(e,"message"),Jr(e,"errMsg")].some(e=>null!==e&&Yr.some(t=>t.test(e)))},Zr=e=>{if(e instanceof Error)return e;const t=Jr(e,"message")??Jr(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ti=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),si=e=>e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP,ni=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=ei.indexOf(t[o]??""),s=ei.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:ei.indexOf(a),l="="===c?0:ei.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},ri=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),ii=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},oi=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(ri(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?oi(s.data,t+1):e},ai=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return ii(e);if(ri(e))try{return ii(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return ii(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=ai(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=ai(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)}},ci=(e,t)=>{if("string"==typeof e)return e;const s=e instanceof Uint8Array?e:new Uint8Array(e);if(si(t)){const n=(e=>{let t="";for(let s=0;s<e.length;s+=3){const n=e[s]??0,r=e[s+1],i=e[s+2],o=n<<16|(r??0)<<8|(i??0);t+=ei[o>>18&63],t+=ei[o>>12&63],t+=void 0===r?"=":ei[o>>6&63],t+=void 0===i?"=":ei[63&o]}return t})(s);return a.warn("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:s.byteLength,encodedCharacters:n.length,sourcePrefixHex:ti(s.subarray(0,8))}),n}const n=new ArrayBuffer(s.byteLength);return new Uint8Array(n).set(s),n},di=(e,t)=>"string"!=typeof e&&si(t),li=(e,t)=>{const s=oi(e.data);if("string"==typeof s){if(!si(t))return s;const n=ni(s),r=new Uint8Array(n);return a.warn("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:s===e.data?"string":"wrapped-string",sourceCharacters:s.length,decodedBytes:n.byteLength,decodedPrefixHex:ti(r.subarray(0,8)),decodedSuffixHex:ti(r.subarray(Math.max(0,r.length-8)))}),n}const n=ai(s);if(!n){const n="object"==typeof e.data&&null!==e.data?e.data:void 0;return void a.warn("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof s,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:n?Object.keys(n).slice(0,10):[],isBuffer:e.isBuffer})}if(!si(t))return n.buffer;const r=(e=>{let t="";for(const n of e){if(9!==n&&10!==n&&13!==n&&32!==n&&!(n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||43===n||45===n||47===n||61===n||95===n))return;t+=String.fromCharCode(n)}const s=t.replace(/\s/g,"");if(0!==s.length&&s.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(s))return s})(n);if(!r)return a.warn("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(s),sourceBytes:n.byteLength,sourcePrefixHex:ti(n.subarray(0,8))}),n.buffer;const i=ni(r),o=new Uint8Array(i);return a.warn("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(s),sourceBytes:n.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:ti(o.subarray(0,8)),decodedSuffixHex:ti(o.subarray(Math.max(0,o.length-8)))}),i},ui=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),hi=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],pi=e=>e instanceof Error?e.message:ui(e)&&"string"==typeof e.errMsg?e.errMsg:ui(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),mi=e=>e?{...e}:{},fi=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,gi=e=>fi(e.statusCode)?e.statusCode:fi(e.status)?e.status:void 0,yi=e=>{if(!ui(e))return{};const t={};return Object.entries(e).forEach(([e,s])=>{"string"==typeof s&&(t[e]=s)}),t},Ii=e=>({...yi(e.headers),...yi(e.header)}),vi=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},Ci=e=>{try{e.close()}catch{}},Si=(e,t)=>new Promise((s,o)=>{let c=!1,d=()=>{};const l=(e,s,a)=>{c||(c=!0,d(),o(n(e,{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:a,details:{url:t.url,method:"GET",cause:pi(s)}})))},u=e.downloadFile?.({url:t.url,header:mi(t.headers),timeout:t.timeoutMs??15e3,success:n=>{const r=n.tempFilePath??n.apFilePath;r?((e,t)=>new Promise((s,n)=>{const r=e.getFileSystemManager?.();r?r.readFile({filePath:t,success:e=>{const t=ai(e.data);t?s(t.buffer):n(new Error("downloaded file response is not binary"))},fail:n}):n(new Error("getFileSystemManager returned no file system manager"))}))(e,r).then(e=>{c||(c=!0,d(),a.warn("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:n.apFilePath?"apFilePath":"tempFilePath",status:n.statusCode??200,bytes:e.byteLength}),s({status:n.statusCode??200,headers:n.header??{},data:e}))}).catch(e=>{l("Mini program downloaded file read failed.",e,!1)}):l("Mini program download did not return a file path.",n,!1)},fail:e=>{l("Mini program file download failed.",e,!0)}});d=vi(t.signal,()=>{u?.abort(),l("Mini program file download aborted.","abort",!1)})}),Ei=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((s,o)=>{let a=()=>{};const c=e.request({url:t.url,method:t.method??"GET",header:mi(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{a();const c=gi(e);void 0!==c?s({status:c,headers:Ii(e),data:e.data}):o(n("Mini program request response status is invalid.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{a(),o(n("Mini program request failed.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:pi(e)}}))}});a=vi(t.signal,()=>{c.abort(),o(n("Mini program request aborted.",{code:r.REQUEST_FAILED,stage:i.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Si(e,t)}),bi=(e,t)=>({connect:a=>new Promise((c,d)=>{let l,u,h=!1;const p=()=>{void 0!==u&&(clearTimeout(u),u=void 0)},m=(e,t,s)=>{h||(h=!0,p(),l&&Ci(l),d(n(t,{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:s,details:{url:a.url,cause:pi(e)}})))},f=e=>{if(!(hi(s=e,"send")&&hi(s,"close")&&hi(s,"onOpen")&&hi(s,"onMessage")&&hi(s,"onError")&&hi(s,"onClose")))return void m(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var s;const a=e;if(h)return void Ci(a);l=a;const d=()=>{a.offOpen?.(u),a.offError?.(f)},u=()=>{h?Ci(a):(h=!0,p(),d(),c(((e,t,s=o.CONNECTING)=>{const a=/* @__PURE__ */new Set,c=/* @__PURE__ */new Set,d=/* @__PURE__ */new Set,l=/* @__PURE__ */new Set;let u=s;return e.onOpen(()=>{u=o.OPEN,a.forEach(e=>{e()})}),e.onMessage(e=>{const s=li(e,t);void 0!==s&&c.forEach(e=>{e(s)})}),e.onError(e=>{d.forEach(t=>{t(e)})}),e.onClose(e=>{u=o.CLOSED,l.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return u},send(s){if(u!==o.OPEN)throw n("Mini program socket is not open.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{readyState:u}});return new Promise((o,a)=>{e.send({data:ci(s,t),...di(s,t)?{isBuffer:!0}:{},success:o,fail:e=>{a(n("Mini program socket send failed.",{code:r.SOCKET_FAILED,stage:i.SOCKET,retryable:!0,details:{cause:pi(e)}}))}})})},close(t,s){u=o.CLOSING,e.close({code:t,reason:s})},onOpen:e=>(a.add(e),()=>{a.delete(e)}),onMessage:e=>(c.add(e),()=>{c.delete(e)}),onError:e=>(d.add(e),()=>{d.delete(e)}),onClose:e=>(l.add(e),()=>{l.delete(e)})}})(a,t,o.OPEN)))},f=e=>{d(),m(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};a.onOpen(u),a.onError(f)};let g;"number"==typeof a.timeoutMs&&a.timeoutMs>0&&(u=setTimeout(()=>{m("timeout","Mini program socket connection timed out.",!0)},a.timeoutMs));try{g=e.connectSocket({url:a.url,...t===s.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(a.protocols)?[...a.protocols]:"string"==typeof a.protocols?[a.protocols]:void 0,fail:e=>{m(e,"Mini program socket connect failed.",!0)}})}catch(I){return void m(I,"Mini program socket creation failed.",!0)}var y;"object"!=typeof(y=g)||null===y||"function"!=typeof y.then?f(g):Promise.resolve(g).then(e=>f(e),e=>m(e,"Mini program socket connect failed.",!0))})}),Ti=e=>({upload(t){const s=t.method??"POST";return"POST"!==s?Promise.reject(n("Mini program upload only supports POST.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,method:s,reason:"unsupported-method"}})):new Promise((s,o)=>{const a=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw n("Mini program upload only supports miniapp-path source.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let c=()=>{};const d=e.uploadFile({url:t.url,filePath:a.path,name:t.fileFieldName??"file",header:mi(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{c();const d=gi(e);void 0!==d?s({status:d,body:e.data}):o(n("Mini program upload response status is invalid.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,path:a.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{c(),o(n("Mini program upload failed.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!0,details:{url:t.url,path:a.path,cause:pi(e)}}))}});d.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),c=vi(t.signal,()=>{d.abort(),o(n("Mini program upload aborted.",{code:r.UPLOAD_FAILED,stage:i.UPLOAD,retryable:!1,details:{url:t.url,path:a.path,reason:"abort"}}))})})}}),Ai=(e,t)=>{const n=(e=>e===s.ALIPAY_MINIAPP||e===s.DINGTALK_MINIAPP)(t);return{async getItem(t){if(hi(e,"getStorageSync"))try{const s=(e=>ui(e)&&"data"in e?e.data:e)(e.getStorageSync(n?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return hi(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(hi(e,"setStorageSync"))try{n?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(r){if(Xr(r))throw Zr(r)}else if(hi(e,"setStorage"))return new Promise((n,i)=>{try{e.setStorage({key:t,data:s,success:n,fail:e=>{Xr(e)?i(Zr(e)):n()}})}catch(r){if(Xr(r))return void i(Zr(r));n()}})},async removeItem(t){if(hi(e,"removeStorageSync"))try{e.removeStorageSync(n?{key:t}:t)}catch{}else if(hi(e,"removeStorage"))return new Promise(s=>{try{e.removeStorage({key:t,success:s,fail:()=>{s()}})}catch{s()}})}}},wi=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>hi(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 hi(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),hi(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{hi(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},n=()=>{t(!1)};return hi(e,"onAppShow")&&e.onAppShow(s),hi(e,"onAppHide")&&e.onAppHide(n),t(!0),()=>{hi(e,"offAppShow")&&e.offAppShow(s),hi(e,"offAppHide")&&e.offAppHide(n)}}}),Ni=(e,t=s.WECHAT_MINIAPP,o=t)=>{const a=(e=>{if(hi(e,"request")&&hi(e,"connectSocket")&&hi(e,"uploadFile"))return e;throw n("Mini program platform capability is missing.",{code:r.MISSING_CAPABILITY,stage:i.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),c="function"==typeof a.getImageInfo?$r(a):void 0;return{request:Ei(a),socket:bi(a,o),upload:Ti(a),runtime:wi(a,t),storage:Ai(a,o),imageProcessor:c}},Mi=["request","upload","socket"],Ri={request:"request",upload:"upload",socket:"connect"},_i=[s.WEB,s.ELECTRON_RENDERER,s.REACT_NATIVE],Di=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Ui=e=>_i.includes(e),Li=(e,t)=>e!==s.UNIAPP?Ui(e):!zn(t)&&!ki(t)&&Kn(t),Oi=e=>Di(e,"getImageInfo")&&Di(e,"getFileSystemManager"),ki=e=>!zn(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),Pi=(e,t)=>{if(Ui(e)&&e!==s.REACT_NATIVE)return qr();if(Qn(e)&&Oi(t))return $r(t);if(e===s.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Kn(e))return qr();if(Oi(e.uni))return $r(e.uni);if(Oi(e.wx))return $r(e.wx)}},xi=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())}},Fi=(e,t,n,r)=>{if(e===s.UNIAPP&&ki(n)&&void 0!==n.uni&&Pn(n.uni))return{...Ni(n.uni,e,t),proto:pr()};if(((e,t)=>!Li(e,t)&&Qn(e))(e,n)&&Pn(r))return{...Ni(r,e,t),proto:pr()};const i=n.XMLHttpRequest,o=Li(e,n),a=o?c({fetchImpl:n.fetch}):void 0,d=o?Cr({webSocketCtor:n.WebSocket}):void 0,l=e===s.REACT_NATIVE?Nr({fetchImpl:n.fetch,formDataCtor:n.FormData}):o?Ar({xhrFactory:"function"==typeof i?()=>new i:void 0,fetchImpl:n.fetch}):void 0,u=o&&e!==s.REACT_NATIVE?(h={platform:e,windowRef:n.window,documentRef:n.document,navigatorRef:n.navigator},{getPlatform:()=>h.platform,getNetworkType:()=>!1===h.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(h.navigatorRef?.connection?.type??h.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=h.windowRef;if(!t)return()=>{};const s=()=>{e(!0)},n=()=>{e(!1)};return t.addEventListener("online",s),t.addEventListener("offline",n),"boolean"==typeof h.navigatorRef?.onLine&&e(h.navigatorRef.onLine),()=>{t.removeEventListener("online",s),t.removeEventListener("offline",n)}},onAppVisibilityChange(e){const t=h.documentRef;if(!t)return()=>{};const s=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",s),s(),()=>{t.removeEventListener("visibilitychange",s)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var h;return{request:a,upload:l,socket:d,runtime:u,proto:pr(),storage:xi(n),imageProcessor:o&&e!==s.REACT_NATIVE?qr():Pi(e,r)}},Bi=(e,t,s)=>{if(!t)return{...e,...s};const o=Mi.filter(e=>void 0!==s[e]);if(o.length>0)throw n("Transport adapter conflicts with network overrides.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{conflictingCapabilities:o}});const a=(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(s);return{...e,request:t.request,upload:t.upload,socket:t.socket,...a}},qi=(e,t)=>{if(void 0!==e)return e;throw n("Platform adapter initialization failed.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{capability:t}})},Ki=(e,t)=>$n(t,e).platform,Gi=e=>{(e=>{if(!e)return;const t=Mi.flatMap(t=>{const s=Ri[t];return Di(e[t],s)?[]:[`${t}.${s}`]});if(0!==t.length)throw n("Transport adapter has invalid capabilities.",{code:r.INIT_FAILED,stage:i.INIT,retryable:!1,details:{source:"transportAdapter",invalidCapabilities:t}})})(e?.transportAdapter);const s=t(e?.runtimeInput),o=$n(s,e?.prefer),a=o.platform,c=Fi(a,o.hostPlatform,s,o.global),d=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,c),l=Bi(c,e?.transportAdapter,d),u=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(l);Jn(u);return{platform:a,platformId:a,capability:u,request:qi(l.request,"request"),upload:qi(l.upload,"upload"),socket:qi(l.socket,"socket"),runtime:qi(l.runtime,"runtime"),proto:qi(l.proto,"proto"),storage:qi(l.storage,"storage"),imageProcessor:l.imageProcessor}},Vi=e=>{if(e)return e;const s=t(),o=Cr({webSocketCtor:s.WebSocket});if(o)return o;throw n("Socket capability is missing for current platform.",{code:r.MISSING_CAPABILITY,stage:i.SOCKET,retryable:!1,details:{capability:"socket"}})},Hi={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class zi{constructor(e={}){this.attemptCount=0,this.config={...Hi,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),s=Math.min(t,this.config.maxDelay);return s/2+s/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return a.debug(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const ji={interval:3e4,timeout:6e4},Wi="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 s=this.parseJson(t);if(!$i.isRecord(s))return;"pong"===$i.readString(s.type)&&(this.markAlive(),a.debug("Pong received"))},this.config={...ji,...e}}start(e,t,s){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=s??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),a.debug("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),a.debug("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===o.OPEN)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{a.error("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),a.debug("Ping sent")}catch(e){a.error("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?Wi?.decode(t)??Un(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{a.warn("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==o.OPEN)return!1;this.attachWebSocket(e);const s=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},s);this.probeResolvers.push(s=>{clearTimeout(t),e(s)}),this.sendPingInternal()})}catch(s){return a.warn("Heartbeat probe failed",s),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const s of t)s(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}let Qi=null;function Yi(){return Qi||(Qi=hr()),Qi}const Ji="websdk2:device-info",Xi="webim",Zi="web",eo=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(Ji);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(Ji,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===Xi){const e=`${Zi}_${s}`,t=d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e});return c(t),t}if(void 0!==r){const e=d({deviceId:`webim_${Zi}_${n}`,deviceName:n,deviceUuid:`${Zi}_${s}`});return c(e),e}const t={deviceId:`webim_${Zi}_${n}`,deviceName:`webim_${Zi}_${n}`,deviceUuid:`webim_${Zi}_${n}`};return c(t),t}if(n===Xi){const e=`random_${Zi}_${s}`;return d({deviceId:`${n}_${e}`,deviceName:n,deviceUuid:e})}if(void 0!==r){return d({deviceId:`webim_${Zi}_${n}`,deviceName:n,deviceUuid:`random_${Zi}_${s}`})}return{deviceId:`webim_${Zi}_${n}`,deviceName:`webim_${Zi}_${n}`,deviceUuid:`webim_${Zi}_${n}`}},to=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),so=e=>{if(/^\d+$/.test(e))return e;const t=nt.fromString("1099511628211",!0);let s=nt.fromString("1469598103934665603",!0);for(let n=0;n<e.length;n+=1)s=s.xor(nt.fromInt(e.charCodeAt(n),!0)).multiply(t).toUnsigned();return s.isZero()?"1":s.toString()},no=e=>{if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?`${e}`:"";if("bigint"==typeof e)return e.toString();if(e&&"object"==typeof e&&"low"in e&&"high"in e&&"number"==typeof e.low&&"number"==typeof e.high){const t=e;return new nt(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},ro=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:fn,stringValue:JSON.stringify(n)})}catch{t.push({key:s,type:mn,stringValue:Object.prototype.toString.call(n)})}else t.push({key:s,type:mn,stringValue:n});else Number.isInteger(n)?t.push({key:s,type:dn,varintValue:n}):t.push({key:s,type:pn,doubleValue:n});else t.push({key:s,type:cn,varintValue:n?1:0});return t},io=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:mn;if(n!==cn)if(n!==dn&&n!==ln&&n!==un)if(n!==hn)if(n!==pn){if(n!==fn)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},oo=/* @__PURE__ */new Set(["mute"]),ao={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},co=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},lo=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},uo=(e,t)=>{const s=e?.map(e=>co(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},ho=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=lo(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},po=e=>{const t=lo(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=ao[n];if(!e)continue;let t=r;if(oo.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},mo=e=>{const t=lo(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:co(t.operator)??co(t.username)}},fo=(e,t)=>({eventName:e,payload:t}),go=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=co(e.from?.name),n=(r=e.to,co(r?.[0]?.name));var r;switch(e.operation){case 1:return fo(Pt,t);case 10:return fo(Bt,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:n??s});case 17:return fo(xt,{...t,memberIds:uo(e.members,s),ext:e.ext??e.eventExt});case 18:return fo(Ft,{...t,memberIds:uo(e.members,s)});case 20:return fo(Wt,{...t,oldOwnerId:s,newOwnerId:n});case 21:return fo(zt,{...t,adminId:n??s});case 22:return fo(jt,{...t,adminId:n??s});case 23:{const s=(e=>{const t=lo(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):uo(e.members,n),i=46388736e5;return fo(qt,{...t,userIds:r,muteMembers:s??Object.fromEntries(r.map(e=>[e,i])),muteExpire:ho(e.reason,e.eventExt)??i})}case 24:return fo(Kt,{...t,userIds:uo(e.members,n)});case 25:return fo($t,{...t,announcement:e.reason??""});case 26:return fo($t,{...t,announcement:""});case 29:return fo(Gt,{...t,userIds:uo(e.members,n)});case 30:return fo(Vt,{...t,userIds:uo(e.members,n)});case 31:return fo(Ht,{...t,isMuted:!0});case 32:return fo(Ht,{...t,isMuted:!1});case 14:return fo(Qt,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:po(e.eventExt)});case 43:{const n=mo(e.eventExt);return fo(Yt,{...t,attributes:n.attributes,from:n.from??s})}case 44:{const n=mo(e.eventExt);return fo(Jt,{...t,keyList:n.keyList,from:n.from??s})}default:return null}},yo=/* @__PURE__ */new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Io={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},vo=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Co=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},So=(e,t)=>{const s=e?.map(e=>vo(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Eo=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const n=Co(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},bo=e=>{const t=Co(e);if(!t)return;const s={};for(const[n,r]of Object.entries(t)){const e=Io[n];if(!e)continue;let t=r;if(yo.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},To=(e,t)=>{const s=Co(t)??Co(e);return pt(s??void 0)??void 0},Ao=(e,t)=>{const s=Co(t)??Co(e);return vo(s?.fileId)??vo(s?.file_id)??vo(e)??""},wo=(e,t)=>({eventName:e,payload:t}),No=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=vo(e.from?.name),n=(r=e.to,vo(r?.[0]?.name));var r;switch(e.operation){case 4:return wo(at.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return wo(at.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return wo(at.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:n,reason:e.reason});case 7:return wo(at.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return wo(at.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return wo(at.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return wo(at.USER_REMOVED,t);case 1:return wo(at.GROUP_DESTROYED,t);case 19:return wo(at.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=Co(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=vo(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):So(e.members,n);return wo(at.MUTE_LIST_ADDED,{...t,userIds:r,muteExpire:r.map(e=>s?.[e]).find(e=>void 0!==e)??Eo(e.reason,e.eventExt)})}case 24:return wo(at.MUTE_LIST_REMOVED,{...t,userIds:So(e.members,n)});case 29:return wo(at.ALLOW_LIST_ADDED,{...t,userIds:So(e.members,n)});case 30:return wo(at.ALLOW_LIST_REMOVED,{...t,userIds:So(e.members,n)});case 31:return wo(at.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return wo(at.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return wo(at.ADMIN_ADDED,{...t,administratorId:n??s});case 22:return wo(at.ADMIN_REMOVED,{...t,administratorId:n??s});case 20:return wo(at.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:n});case 17:{const n=So(e.members,s);return wo(at.MEMBERS_JOINED,{...t,memberIds:n})}case 18:{const n=So(e.members,s);return wo(at.MEMBERS_EXITED,{...t,memberIds:n})}case 25:return wo(at.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return wo(at.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return wo(at.SHARED_FILE_ADDED,{...t,sharedFile:To(e.reason,e.eventExt)});case 28:return wo(at.SHARED_FILE_DELETED,{...t,fileId:Ao(e.reason,e.eventExt)});case 14:return wo(at.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:bo(e.eventExt)});case 41:return wo(at.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return wo(at.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const n=(e=>{const t=Co(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:vo(t.username),attribute:n}})(e.eventExt);return wo(at.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:n.userId,attribute:n.attribute,from:s,source:e.source??"direct"})}default:return null}},Mo=/* @__PURE__ */new WeakMap,Ro=(e,t)=>{Mo.set(e,t)},_o=e=>Mo.get(e)??null,Do=(e,t)=>{const s=_o(e);s&&Ro(t,s)},Uo=/* @__PURE__ */new WeakMap,Lo=e=>Uo.get(e),Oo="singleChat",ko="groupChat",Po={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},xo=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Fo=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}},Bo=e=>{if(!Array.isArray(e))return;const t=e.map(e=>xo(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},qo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ko=(...e)=>{for(const t of e){const e=xo(t);if(e)return e}},Go=(e,t)=>Boolean(e&&t&&e===t),Vo=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),Ho=(e,t,s)=>{const n=Bo(e);if(n&&n.length>0)return n;const r=(t??[]).map(e=>xo(e.name)).filter(e=>"string"==typeof e);if(r.length>0)return r;const i=xo(s?.name);return i?[i]:[]},zo=e=>{const t=Fo(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}}},jo=(e,t)=>{const s=Ko(e.to?.[0]?.clientResource);if(1!==e.to?.length||xo(e.to[0]?.name)!==t.userId||!Vo(t.userId,s,t))return null;const n=(r=e.from,xo(r?.name)??"");var r;if(!n)return a.warn("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return a.warn("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:n,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:s,timestamp:e.timestamp,raw:e.raw}},Wo=(e,t)=>{if(!e.groupId)return a.warn("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const s=Ko(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Vo(xo(e.from?.name),s,t))return null;const n=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return a.warn("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===n)return null;const r=Ho(e.members,e.to,e.from);return{category:"group",operation:n,groupId:e.groupId,userIds:r.length>0?r:void 0,operatorId:xo(e.from?.name),groupName:e.groupName,deviceId:s,timestamp:e.timestamp,raw:e.raw}},$o=(e,t)=>{if(!e.threadId)return a.warn("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const s=Ko(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Vo(xo(e.from?.name),s,t))return null;const n=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return a.warn("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===n)return null;const r=Ho(e.members,e.to,e.from);return{category:"thread",operation:n,threadId:e.threadId,parentId:e.parentId,userIds:r.length>0?r:void 0,operatorId:xo(e.from?.name),threadName:e.threadName,deviceId:s,timestamp:e.timestamp,raw:e.raw}},Qo=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const s=Ko(e.res,e.raw?.resource,e.raw?.clientResource);if(Go(s,t.clientResource))return a.debug("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const n="chat"===(r=e.type)||"singleChat"===r?Oo:ko;var r;const i=xo(e.id)??(n===Oo?xo(e.from):void 0);if(!i)return a.warn("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return a.warn("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:n,mark:"mark"===e.operation||"mark_delete"===e.operation?zo(e.ext):void 0,operatorId:xo(e.from),deviceId:s,timestamp:Fo(e.ts),raw:e.raw}},Yo=(e,t)=>{const s=Ko(e.resource,e.raw?.resource,e.raw?.clientResource);if(Go(s,t.clientResource))return a.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const n=xo(e.to);if(!n)return a.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const r=xo(e.lastMsgId),i=Bo(e.msgIdList)??(r?[r]:void 0),o=Fo(e.deleteTime);if(!i&&void 0===o)return a.warn("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:n}),null;const c=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(a.warn("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===c?null:{category:"messageRemoved",operation:c,conversationId:n,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?ko:Oo,messageIds:i,beforeTimestamp:o,deviceId:s,raw:e.raw}},Jo=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var Xo=4096,Zo=65547,ea=15,ta=2113929216,sa=65536,na=65536,ra=10485760,ia={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},oa={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function aa(e){if(!(e>0))return na;if(e<=na)return na;if(e>1073741823)return e;for(var t=na;t<e;)t*=2;return t}var ca={byU16:0,byU32:1},da=0,la=1,ua=2,ha=0,pa=1;function ma(e,t){return e[t]|e[t+1]<<8}function fa(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function ga(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var ya="fast";function Ia(e){return 2654435761*(e>>>0)>>>20&4095}function va(e){return 2654435761*(e>>>0)>>>19&8191}function Ca(e,t,s){if("fast"===ya){var n=fa(e,t);return s===ca.byU16?va(n):Ia(n)}throw new Error("Unsupported hash strategy: "+ya)}function Sa(e,t,s,n,r){s[t]=e-r}function Ea(e,t,s,n,r){Sa(t,Ca(e,t,n),s,0,r)}function ba(e,t,s,n){return t[e]+n}function Ta(e,t,s,n,r){return ba(Ca(e,t,n),s,0,r)}function Aa(e,t,s,n){for(var r=t;t<n-3;){if(fa(e,t)!==fa(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 wa(e,t,s,n,r,i,o,a,c,d){var l,u,h,p=e.hashTable,m=n,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,I=y+e.dictSize,v=e.dictSize>0?I-n:0,C=n,S=n+r,E=S-12,b=S-5,T=0,A=i>0?i:s.length,w=0;if(r>ta)return 0;switch(c){case da:default:l=n,u=n;break;case la:l=n-e.currentOffset,u=n-e.dictSize;break;case ua:l=n-e.currentOffset,u=n}if(a===ca.byU16&&r>=Zo)return 0;if(r<13)return Ra(t,s,C,S,T,A,o);Ea(t,m,p,a,l),h=Ca(t,++m,a);e:for(;;){var N,M,R=m,_=1,D=64;do{var U=h;if(m=R,R+=_,_=D++>>>6,R>E)return Ra(t,s,C,S,T,A,o);N=ba(U,p,0,l),c===ua&&(N<n?(w=v,u=y):(w=0,u=n)),h=Ca(t,R,a),Sa(m,U,p,0,l)}while(d===pa&&N<f||a!==ca.byU16&&N+65535<m||!Na(t,g,m,N,w,c,n));for(;m>C&&N+w>u;){var L=N+w-1;if(t[m-1]!==(c===ua&&N<n?g[L-y+e.dictionaryStart]:t[L]))break;m--,N--}var O=m-C;if(M=T++,o&&T+O+8+Math.floor(O/255)>A)return 0;if(O>=ea){var k=O-ea;for(s[M]=240;k>=255;)s[T++]=255,k-=255;s[T++]=k}else s[M]=O<<4;if(O>=16&&s.set&&t.subarray)s.set(t.subarray(C,C+O),T),T+=O;else for(var P=0;P<O;P++)s[T++]=t[C+P];t:for(;;){var x;if(ga(s,T,m-N),T+=2,c===ua&&N<n){var F=m+(I-(N+w));if(F>b&&(F=b),(m+=4+(x=Ma(t,g,m+4,N+w+4-y+e.dictionaryStart,F,I-y)))===F&&F<b){var B=Aa(t,m,n,b);x+=B,m+=B}}else m+=4+(x=Aa(t,m+4,N+4,b));if(o&&T+6+(x>>>8)>A)return 0;if(x>=15){for(s[M]+=15,x-=15;x>=510;)s[T++]=255,s[T++]=255,x-=510;x>=255&&(x-=255,s[T++]=255),s[T++]=x}else s[M]+=x;if(C=m,m>E)break e;if(Ea(t,m-2,p,a,l),N=Ta(t,m,p,a,l),c===ua&&(N<n?(w=v,u=y):(w=0,u=n)),Ea(t,m,p,a,l),!((d!==pa||N>=f)&&N+65535>=m&&Na(t,g,m,N,w,c,n)))break t;s[M=T++]=0}h=Ca(t,++m,a)}return Ra(t,s,C,S,T,A,o)}function Na(e,t,s,n,r,i,o){var a,c=fa(e,s);i===ua&&n+r<o?a=fa(t,n+r):a=fa(e,n+r);return c===a}function Ma(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 Ra(e,t,s,n,r,i,o){var a=n-s;if(o&&r+a+1+Math.floor((a+255-ea)/255)>i)return 0;if(a>=ea){for(t[r++]=240,a-=ea;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 _a(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 Da(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)===ea){var T=_a(e,N={ip:p},m-ea,!0);if(p=N.ip,-1===T)return-(p-s)-1;if(f+(S+=T)<f)return-(p-s)-1;if(p+S<p)return-(p-s)-1}if(E=f+S,o&&(E>g-12||p+S>m-8)||!o&&E>g-8){if(!o&&E!==g)return-(p-s)-1;if(o&&(p+S!==m||E>g))return-(p-s)-1;if(S>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+S),f);else for(var A=0;A<S;A++)t[f+A]=e[p+A];p+=S,f+=S;break}if(S>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+S),f);else for(A=0;A<S;A++)t[f+A]=e[p+A];if(f=E,(p+=S)+2>m)return-(p-s)-1;var w=ma(e,p);if(p+=2,b=E-w,v&&b+h<l)return-(p-s)-1;if(0===w)return-(p-s)-1;if(15===(S=15&C)){var N;T=_a(e,N={ip:p},m-5+1,!1);if(p=N.ip,-1===T)return-(p-s)-1;if(f+(S+=T)<f)return-(p-s)-1}if(S+=4,d===ua&&b<l){if(f+S>g-5)return-(p-s)-1;if(S<=l-b){var M=I-(l-b);for(A=0;A<S;A++)t[f+A]=t[M+A];f+=S}else{var R=l-b;for(M=I-R,A=0;A<R;A++)t[f+A]=t[M+A];var _=S-R;if(_>(f+=R)-l)for(var D=l,U=f+_;f<U;)t[f++]=t[D++];else{for(A=0;A<_;A++)t[f+A]=t[l+A];f+=_}}}else{if(b<y)return-(p-s)-1;if(E=f+S,f-b<8)for(t[f]=t[b],t[f+1]=t[b+1],t[f+2]=t[b+2],t[f+3]=t[b+3],f+=4,b+=4;f<E;)t[f++]=t[b++];else for(;f<E;)t[f++]=t[b++]}}return o?f-r:p-s}function Ua(){return{hashTable:new Uint32Array(Xo),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function La(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function Oa(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?pa:ha;return e.dictionary&&c===n?(l=wa(e,t,s,n,r,o||0,a||!1,ca.byU32,la,h),e.dictSize+=r,e.currentOffset+=r,l):(l=wa(e,t,s,n,r,o||0,a||!1,ca.byU32,ua,h),e.dictionary=t,e.dictionaryStart=n,e.dictSize=r,e.currentOffset+=r,l)}function ka(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 Pa(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function xa(e,t,s,n){return e.prefixSize=n,e.prefixEnd=s+n,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function Fa(e,t,s,n,r,i,o){var a;if(e.prefixEnd===i){if((a=Da(t,s,n,r,i,o,!0,0,0,ua,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=Da(t,s,n,r,i,o,!0,0,0,ua,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function Ba(e){var t=(e=e||{}).minWorkArea||na,s=e.maxWorkArea||ra,n=e.shrinkThreshold||t;t<na&&(t=na),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=sa+t,this.maxBufferSize=sa+s,this.shrinkThreshold=sa+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ia.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=Ua()}function qa(e){var t=(e=e||{}).minWorkArea||na,s=e.maxWorkArea||ra,n=e.shrinkThreshold||t;t<na&&(t=na),s<t&&(s=t),n<t&&(n=t),n>s&&(n=s),this.minBufferSize=sa+t,this.maxBufferSize=sa+s,this.shrinkThreshold=sa+n,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ia.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Ba.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<sa?this.offset:sa,r=this.offset>sa?this.offset-sa:0;t.set(this.ringBuffer.subarray(r,r+n),0),ka(this.stream,t,0,n),s=n}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Ba.prototype.compress=function(e,t){var s=e.length;if(s<=0)return oa.PARAM_ERROR;if(s>this.maxBufferSize-sa)return oa.PARAM_ERROR;if(s>this.ringBufferSize-sa){var n=aa(s),r=sa+n;if(r>this.maxBufferSize&&(r=this.maxBufferSize),!this._resizeBuffer(r))return oa.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(ka(this.stream,this.ringBuffer,0,sa),this.offset=sa);var i=this.offset;this.ringBuffer.set(e,i);var o=Oa(this.stream,this.ringBuffer,t,i,s,0,t.length,!0);return o<=0?oa.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),o)},Ba.prototype.reset=function(){this.offset=0,La(this.stream)},Ba.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Ba.prototype._tryAutoShrink=function(){this.shrinkMode!==ia.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ia.AUTO_IMMEDIATE||this.shrinkMode===ia.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Ba.prototype.getWorkArea=function(){return this.ringBufferSize-sa},Ba.prototype.getRingBufferSize=function(){return this.ringBufferSize},Ba.prototype.getBaseBufferSize=function(){return this.minBufferSize},Ba.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Ba.prototype.getCurrentOffset=function(){return this.offset},Ba.prototype.getShrinkMode=function(){return this.shrinkMode},Ba.prototype.setShrinkMode=function(e){this.shrinkMode=e},Ba.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Ba.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-sa,s=this.maxBufferSize-sa;if(e<t||e>s)return oa.PARAM_ERROR;this.shrinkThreshold=sa+e},qa.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var n=this.offset<sa?this.offset:sa,r=this.offset>sa?this.offset-sa:0;t.set(this.ringBuffer.subarray(r,r+n),0),s=n,xa(this.streamDecode,0,0,n)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},qa.prototype.decompress=function(e,t,s){var n=e.length;if(n<=0||s<=0)return oa.PARAM_ERROR;if(s>this.maxBufferSize-sa)return oa.PARAM_ERROR;if(s>this.ringBufferSize-sa){var r=aa(s),i=sa+r;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return oa.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var o=this.offset-sa;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+sa),0),xa(this.streamDecode,this.ringBuffer,0,sa),this.offset=sa}var a=Fa(this.streamDecode,e,this.ringBuffer,0,n,this.offset,s);return a<=0?oa.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},qa.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},qa.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},qa.prototype._tryAutoShrink=function(){this.shrinkMode!==ia.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ia.AUTO_IMMEDIATE||this.shrinkMode===ia.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},qa.prototype.getWorkArea=function(){return this.ringBufferSize-sa},qa.prototype.getRingBufferSize=function(){return this.ringBufferSize},qa.prototype.getBaseBufferSize=function(){return this.minBufferSize},qa.prototype.getMaxBufferSize=function(){return this.maxBufferSize},qa.prototype.getCurrentOffset=function(){return this.offset},qa.prototype.getShrinkMode=function(){return this.shrinkMode},qa.prototype.setShrinkMode=function(e){this.shrinkMode=e},qa.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},qa.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-sa,s=this.maxBufferSize-sa;if(e<t||e>s)return oa.PARAM_ERROR;this.shrinkThreshold=sa+e};const Ka={LZ4_MAX_INPUT_SIZE:ta,BLOCK_MAX_SIZE:65536,DICT_SIZE:sa,DEFAULT_WORK_AREA:na,DEFAULT_MAX_WORK:ra,SHRINK_MODE:ia,LZ4_ERROR:oa,alignToPowerOf2:aa,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".');ya=e},getHashStrategy:function(){return ya},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>ta)return 0;if(0===n)return t.length>r?(t[r]=0,1):0;var i=n<Zo?ca.byU16:ca.byU32;return wa({hashTable:new Uint32Array(i===ca.byU16?8192:Xo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,0,!1,i,da,ha)},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>ta)return 0;if(i<1)return 0;if(0===n)return t[r]=0,1;var o=n<Zo?ca.byU16:ca.byU32;return wa({hashTable:new Uint32Array(o===ca.byU16?8192:Xo),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,n,i,!0,o,da,ha)},compressBound:function(e){return e<0||e>ta?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:Da(e,t,s,n,r,i,!0,0,0,da,r,null,0))},decompressFast:function(e,t,s,n,r){return Da(e,t,s=s||0,0,n=n||0,r,!1,0,0,la,n-65536,0,65536)},createStream:Ua,resetStream:La,loadDict:function(e,t,s,n){if(e.initCheck&&La(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;)Ea(t,i,e.hashTable,ca.byU32,r),i+=3;return n},compressContinue:Oa,saveDict:ka,createStreamDecode:Pa,setStreamDecode:xa,decompressSafeContinue:Fa,RingBufferEncoder:Ba,RingBufferDecoder:qa,_hashU16:va,_hashU32:Ia,_TABLE_TYPE:ca},Ga=268435455,Va=new Uint32Array(256);let Ha=!1;function za(e){!function(){if(!Ha){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;Va[e]=t>>>0}Ha=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const n=e[s]??0;t=t>>>8^(Va[255&(t^255&n)]??0)}return(4294967295^t)>>>0}var ja=/* @__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))(ja||{});const Wa=268435455;class $a{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Ka.DEFAULT_WORK_AREA,maxWorkArea:Ka.DEFAULT_MAX_WORK,shrinkMode:Ka.SHRINK_MODE.MANUAL};this.encoder=new Ka.RingBufferEncoder(e),this.decoder=new Ka.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>Wa)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=Ka.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>Ga)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=za(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>Wa)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=za(o);if(c!==r)throw new Error(`CRC32 checksum mismatch: expected ${r}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const Qa=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ya=(e,t)=>rt(e,t).finish();class Ja{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=eo({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:[xs],compressType:[Fs],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=Yi(),t=e.lookupType("easemob.pb.Provision"),s=e.lookupType("easemob.pb.MSync"),n={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Fs],encryptType:[xs],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},r=Ya(t,n),i={version:0,guid:to({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:rs,deviceId:0,encryptType:[xs],payload:r,traceId:d()};return Ya(s,i)}encodeHeartbeat(){const e=Yi(),t=e.lookupType("easemob.pb.CommUnreadUL"),s=e.lookupType("easemob.pb.MSync"),n=Ya(t,{}),r={version:0,encryptType:[xs],command:ss,payload:n,traceId:d()};return Ya(s,r)}encodeStatisticRebuild(){const e=Yi(),t=e.lookupType("easemob.pb.StatisticsBody"),s=e.lookupType("easemob.pb.Meta"),n=e.lookupType("easemob.pb.CommSyncUL"),r=e.lookupType("easemob.pb.MSync"),i=Ya(t,{operation:0}),o=s.decode(new Uint8Array);o.id=Date.now(),o.ns=Rs,o.payload=i;const a=n.decode(new Uint8Array);a.meta=o;const c=Ya(n,a);return Ya(r,{version:0,encryptType:[xs],command:ts,payload:c,traceId:d()})}decodeProvision(e){const t=Yi().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},n="number"==typeof s.errorCode?s.errorCode:Ks,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===qs,statusCode:n,reason:r,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Yi().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=Yi().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=Yi().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=Yi(),s=t.lookupType("easemob.pb.CommSyncDL"),n=t.lookupType("easemob.pb.MessageBody"),r=s.decode(e);a.debug("decodeSync commSyncDl",{hasMetas:Array.isArray(r.metas)});const i=Array.isArray(r.metas)?r.metas:[],o=this.decodeAck(r);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const c=no(r.metaId),d=no(r.nextKey),l=r.queue??void 0,u="boolean"==typeof r.isLast?r.isLast:void 0,h=[],p=[];if(c&&"0"!==c){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,n):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&p.push(...e)}return{ack:o,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u,replacedMessage:e}}for(const a of i){const e=this.decodeChatMeta(a,n);e&&h.push(e);const t=this.decodeChatActionMeta(a,n);t&&p.push(t);const s=this.decodeNotifyMeta(a);s.length>0&&p.push(...s)}return{ack:o,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u}}decodeReplacedMessage(e,t){for(const s of e){const e=this.decodeChatMeta(s,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const s=e,n=s.payload;let r=null;if(n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!r)return null;if(("number"==typeof s.ns?s.ns:void 0)!==_s)return null;try{const e=t.decode(r);if(!e||"object"!=typeof e)return null;const n=e;return this.decodeMessage(s,n)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const s=e,n=s.payload;let r=null;if(n instanceof Uint8Array?r=n:n instanceof ArrayBuffer?r=new Uint8Array(n):ArrayBuffer.isView(n)&&(r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!r)return null;if(("number"==typeof s.ns?s.ns:void 0)!==_s)return null;try{const e=t.decode(r);if(!e||"object"!=typeof e)return null;const n=e,i="number"==typeof n.type?n.type:os;if(i!==ls&&i!==hs&&i!==ps&&i!==ms&&i!==us)return null;const o=this.readJid(s.to),c=Number(no(s.timestamp))||Date.now(),d=this.resolveActionConversationType(o.domain,n.meta,n),{senderId:l,receiverId:u}=this.resolveIncomingMessageParties(s,n,d),h=this.resolveActionConversationId(l,u,d);if(i===ps)return!0===n.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:c}}:h?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:c}}:null;if(i===ls){a.debug("Received READ_ACK MessageBody",n);const e=(Array.isArray(n.ackMessageIds)?n.ackMessageIds:[]).map(e=>no(e)).filter(e=>Boolean(e)),t=no(n.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!h)return null;const s=io(Array.isArray(n.ext)?n.ext.filter(Qa):void 0),r=Qa(s.group_ack_count)?s.group_ack_count:{},i=e.flatMap(e=>{const t=r[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:c,..."groupChat"===d?{receiptDetails:i}:{}}}}if(i===us){const e=no(n.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(i===hs){const e=no(n.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=no(n.editMessageId),m=(Array.isArray(n.contents)?n.contents:[])[0],f=m?this.decodeContent(m):null;if(!p||!h||!f)return null;const g=this.resolveModifiedInfo(n.meta);return{type:"message_updated",data:{messageId:p,conversationId:h,conversationType:d,timestamp:c,message:{type:f.type,body:f.body,ext:io(n.ext),...g?{modifiedInfo:g}:{}}}}}catch{return null}}decodeNotifyMeta(e){if(!e||"object"!=typeof e)return[];const t=e,s="number"==typeof t.ns?t.ns:void 0;if(s!==Ls&&s!==Us&&s!==Ds&&s!==Rs)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===Us?this.decodeRosterMeta(t,r):s===Ds?this.decodeMucMeta(t,r):s===Rs?this.decodeStatisticGroupReceiptNotifies(t,r):this.decodeNotifyPayload(r):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const s=Yi(),n=s.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof n.location||0===n.location.length)return[];const r=JSON.parse(n.location);if(!Qa(r)||!Array.isArray(r.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=/* @__PURE__ */new Map;for(const e of r.group_ack){if(!Qa(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[s,n]of Object.entries(e)){if("groupId"===s)continue;const e="number"==typeof n?n:"string"==typeof n&&n.trim().length>0?Number(n):Number.NaN;!s||!Number.isInteger(e)||e<0||o.set(s,{conversationId:t,count:e})}}return a.debug("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:s}])=>({messageId:e,conversationId:t,count:s}))}),Array.from(o,([e,{conversationId:t,count:s}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:s}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Rs)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=Yi(),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=Yi(),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=jo({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=Yi(),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=$o({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=Wo({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?go({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}):No({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&&Uo.set(e,t)})(s,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:s};case 3:return{eventName:"onContactDeleted",payload:s};case 4:return{eventName:"onContactAdded",payload:s};case 5:case 9:return{eventName:"onContactRefuse",payload:s};case 8:return{eventName:"onContactAgreed",payload:s};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const s=e[i];if(void 0===s)return[];t+=`%${s.toString(16)}`}const s=decodeURIComponent(t),n=JSON.parse(s);a.debug("Decoded MSync notify payload",{payload:n});const r="string"==typeof n.type?n.type:"";if(!r)return[];if("thread"===r){return[{type:r,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:Qa(n.data)?n.data:n}}]}if("conv"===r){const e=Qa(n.data)?n.data:n,t=[],s="string"==typeof e.op?e.op:"";if("pin"===s||"pin_delete"===s)return[{type:r,eventName:"onPinnedMessageChanged",data:e}];const i=Qo({operation:s,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===r){const e=Qa(n.data)?n.data:n,t=Yo({chatType:"string"==typeof e.chatType?e.chatType:void 0,to:"string"==typeof e.to?e.to:void 0,resource:"string"==typeof e.resource?e.resource:void 0,msgIdList:Array.isArray(e.msgIdList)?e.msgIdList.filter(e=>"string"==typeof e):void 0,deleteTime:e.deleteTime,lastMsgId:"string"==typeof e.lastMsgId?e.lastMsgId:void 0,messageRoamingType:"string"==typeof e.messageRoamingType?e.messageRoamingType:void 0,raw:e},this.msyncCodecContext());return t?[this.createMultiDeviceNotify(t)]:[]}if("user_notification_mute"===r){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const s=[];for(const n of e){if(!qo(n))continue;const e=Ko(n.operator_resource,n.resource,n.clientResource);if(Go(e,t.clientResource))continue;const r=xo(n.group)??xo(n.user);if(!r||!qo(n.data))continue;const i=xo(n.group)?ko:Oo,o=n.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:r,conversationType:i,remindType:xo(o.type),silentMode:o,deviceId:e,raw:n})}return s})(Qa(n.data)&&Array.isArray(n.data.values)?n.data.values:Array.isArray(n.values)?n.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:r,data:n.data??n}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,s=Number(no(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:Jo(e.category),data:e}}decodeNotice(e){const t=Yi().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Yi().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=Yi(),s=t.lookupType("easemob.pb.CommSyncUL"),n=t.lookupType("easemob.pb.MSync"),r=Ya(s,{queue:e}),i={version:0,encryptType:[xs],command:ts,payload:r,traceId:d()};return Ya(n,i)}encodeLastSession(e,t){const s=Yi(),n=s.lookupType("easemob.pb.CommSyncUL"),r=s.lookupType("easemob.pb.MSync"),i=Ya(n,{queue:e,key:t}),o={version:0,encryptType:[xs],command:ts,payload:i,traceId:d()};return Ya(r,o)}encodeChatMessage(e,t){const s=Yi(),n=s.lookupType("easemob.pb.CommSyncUL"),r=s.lookupType("easemob.pb.MSync"),i=this.buildChatMeta(e,t),o=Ya(n,{meta:i}),a={version:0,encryptType:[xs],command:ts,payload:o,traceId:d()};return Ya(r,a)}encodeCombineMessageMeta(e){const t=Yi().lookupType("easemob.pb.Meta"),s=so(e.msgServerId||e.msgLocalId),n=this.buildChatMeta(e,s,!0);return Ya(t,n)}buildChatMeta(e,t,s=!1){const n=Yi().lookupType("easemob.pb.MessageBody"),r=this.buildContent(e),i=this.resolveMessageProfileVersionFields(e),o=this.buildMessageMeta(e),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=s?e.from||e.sender.userId:this.context.userId,d=s&&e.to||a.name,l={type:this.resolveChatType(e),from:{name:c},to:{name:d},contents:[r],ext:ro(e.ext??{}),...o?{meta:o}:{},...i,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},u=Ya(n,l),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e);return{id:t,to:to({appKey:this.context.appKey,name:d,domain:h,clientResource:s?void 0:a.clientResource}),...s?{timestamp:e.timestamp}:{},ns:_s,payload:u,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}}}encodeActionMessage(e,t){const s=Yi(),n=s.lookupType("easemob.pb.MessageBody"),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o=s.lookupEnum("easemob.pb.MessageBody.EditScope"),c=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),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:c.name},contents:l,ext:ro(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?o.values.BODY_AND_EXT:o.values.BODY);const h=Ya(n,u);if("clearAllConversationUnreadMessageCount"===e.kind){const e=n.decode(h),s=n.fields.clearAllUnreadMessageCount;a.debug("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:u.type,fieldId:s?.id,requestedValue:u.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:h.byteLength,wireTailHex:Array.from(h.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const p={id:t,to:to({appKey:this.context.appKey,name:c.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:c.clientResource}),ns:_s,payload:h,routetype:Os,directedUsers:[],ext:[]},m=Ya(r,{meta:p}),f={version:0,encryptType:[xs],command:ts,payload:m,traceId:d()};return Ya(i,f)}encodeChatRoomOperation(e,t){const s=Yi(),n=s.lookupType("easemob.pb.MUCBody"),r=s.lookupType("easemob.pb.CommSyncUL"),i=s.lookupType("easemob.pb.MSync"),o={mucId:to({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=Ya(n,o),c={id:t,from:to({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:Ds,payload:a},l=Ya(r,{meta:c}),u={version:0,encryptType:[xs],command:ts,payload:l,traceId:d()};return Ya(i,u)}decodeServerMessageMeta(e){const t=Yi(),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?Dn(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 so(e)}decodeChatRoomJoinInfo(e){const t=Yi().lookupType("easemob.pb.MUCBody");for(const n of e){if(!Qa(n)||n.ns!==Ds)continue;const e=n.payload,r=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(r)try{const e=t.decode(r);if(!Qa(e)||!Qa(e.status))continue;const s=e.status.chatroomInfo;if("string"!=typeof s||""===s)continue;const n=JSON.parse(s);if(!Qa(n))continue;const i=n[this.context.userId];if(!Qa(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(s){a.error("Failed to decode chat room info from ACK",s)}}}decodeAck(e){const t=no(e.metaId);if(!t||"0"===t)return;const s=e.status??{},n="number"==typeof s.errorCode?s.errorCode:Ks,r="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:no(e.serverId),ok:n===qs,statusCode:n,reason:r}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:as;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=io(t.ext),h=io(e.ext),p=Number(no(e.timestamp))||Date.now(),m=no(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),T=this.resolveProfileVersionTime(t.namecardUpdateTime),A={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)};Ro(A,{userInfoUpdateTime:b,namecardUpdateTime:T});const w=this.decodeStreamMeta(t.stream,n);w&&(A.type="text",A.body={content:w.fullText},A.stream=w),void 0!==f&&(A.isBroadcast=f),void 0!==g&&(A.priority=g),void 0!==I&&(A.isContentReplaced=I),v&&(A.reactions=v),C&&(A.modifiedInfo=C),S&&(A.isChatThread=!0,A.chatThread=S);const N=this.resolvePeerRead(y,r,c);void 0!==N&&(A.isPeerRead=N);const M=this.resolveGroupReadCount(y,r);void 0!==M&&(A.groupReadCount=M),E&&(A.chatThreadOverview=E);const R=t.msgConfig;return R?.allowGroupAck&&(A.needReadReceipt=!0),A}resolveMessageProfileVersionFields(e){const t=_o(e),s={};return"number"==typeof t?.userInfoUpdateTime&&(s.userInfoUpdateTime=t.userInfoUpdateTime),"groupChat"===e.conversationType&&"number"==typeof t?.namecardUpdateTime&&(s.namecardUpdateTime=t.namecardUpdateTime),s}buildMessageMeta(e){const t={};return e.isChatThread&&(t.thread={}),Object.keys(t).length>0?JSON.stringify(t):""}resolveProfileVersionTime(e){return yt(no(e))}isPublicMessageType(e){return e===as||e===cs||e===ds}resolveMessageIsOnline(e,t){if(e===ds)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(no(s.streamSeq));if(!Number.isFinite(n))return;const r="number"==typeof s.streamStatus?s.streamStatus:ws,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?Zt.ERROR:e===Ts?Zt.START:e===As?Zt.START_COMPLETED:e===Ns?Zt.COMPLETED:e===Ms?Zt.FULL:Zt.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:fs,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:Ss,action:t.action}}if("custom"===e.type){const t=e.body;return{type:Es,customEvent:t.event,customExts:ro(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Is,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:gs,displayName:t.filename,remotePath:t.originalImageUrl??"",imageType:l(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:ys,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:vs,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:fs,subType:0,text:Ke(e)??"版本过低",displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,title:t.title,summary:t.summary,combineLevel:t.combineLevel}}const t=e.body;return{type: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:fs,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===bs||t===fs&&(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===fs)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===Ss)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===Es){const t=io(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Is)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===gs){const t=e.size??{},s="number"==typeof t.width?t.width:0,n="number"==typeof t.height?t.height:0,r=u(e.imageType)===h,i="string"==typeof e.remotePath?e.remotePath:"",o=p(i,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:s,height:n,isGif:1===e.subType,isOriginalImage:r,originalImageUrl:o.originalImageUrl,bigImageUrl:o.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??o.thumbnailUrl}}}if(t===ys){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===vs){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 cs;case"chatRoom":return ds;default:return as}}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 ps;case"sendMessageReadReceipts":return ls;case"deliveryAck":return us;case"recall":return hs;case"update":return ms;default:return as}}resolveConversationType(e){return e===cs?"groupChat":e===ds?"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?ro({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?Ps:this.resolveDeliverOnlineOnly(e)?ks:Os}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(!Qa(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(!Qa(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(!Qa(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(!Qa(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=Qa(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:Qa(r?.ext)?r.ext:{},timestamp:n,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(Qa(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=p(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:Qa(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(Un(t));return Qa(e)?e:null}catch{return null}}if(Qa(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return Qa(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(Qa).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?[]:[Bs]}configureCompression(e,t){if(!e||!e.includes(Bs))return void this.disableCompression();this.compressor||(this.compressor=new $a);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===ja.UPLINK_ONLY||s===ja.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===ja.DOWNLINK_ONLY||s===ja.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?ja.UPLINK_ONLY:1===e?ja.DOWNLINK_ONLY:2===e?ja.BIDIRECTIONAL:ja.NONE}disableCompression(){this.compressor&&(this.compressor.mode=ja.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Xa=t=>new C("Connection attempt cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:t,cancelled:!0,retryable:!0}}),Za=t=>t instanceof C&&t.code===e.CONNECTION_CANCELLED&&!0===t.details?.cancelled;class ec{constructor(e,t){this.serverUrlIndex=0,this.websocket=null,this.provisionTimeoutId=null,this.reconnectAttempts=0,this.messageReceiver=null,this.provisionPromise=null,this.provisionResolve=null,this.provisionReject=null,this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames=/* @__PURE__ */new Set,this.offlineMessageQueueReports=/* @__PURE__ */new Map,this.offlineMessageQueueCounts=/* @__PURE__ */new Map,this.offlineMessageTotalCount=0,this.reconnectTimerId=null,this.reconnectDelayReject=null,this.reconnectTask=null,this.pendingReconnectReason=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.hasEverConnected=!1,this.isOnline=!0,this.internalHandlerId="__internal:connection-manager",this.suppressNextCloseEvent=!1,this.socketDisposers=[],this.inboundMessageQueue=Promise.resolve(),this.socketGeneration=0,this.connectionAttemptGeneration=0,this.activeConnectionAttemptCancel=null,this.activeLoginDeadline=null,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:f,autoReconnectNumMax:10,connectTimeout:m,...e},this.eventHub=t,this.msyncCodec=new Ja({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 zi({maxAttempts:this.config.autoReconnectNumMax,initialDelay:I,maxDelay:y,backoffMultiplier:g}),this.heartbeatManager=new $i({interval:this.config.heartBeatWait,timeout:v}),this.connectionEventNormalizer=new Ln,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[Ge.SEND_TIMEOUT]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(t,s){const n=Date.now();if(s<=n)throw new C("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=t,this.connection.token=t,this.msyncCodec.updateToken(t),this.setupTokenLifecycle(t,s,n),a.warn("Connection token renewed",{userId:this.config.userId,expireAt:s}),{token:t,expireAt:s}}handleOnline(){if(a.warn("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0,this.terminalDisconnectError)return void a.warn("Network online recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});const e=this.offlineRecoverPending?Ve.OFFLINE_RECOVER:Ve.ONLINE;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){a.warn("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.stopHeartbeat(),this.closeWebSocket(Ve.OFFLINE,!0),a.warn("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(this.terminalDisconnectError)return void a.warn("Foreground recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void a.warn("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(Ve.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Ve.HEARTBEAT_FAILED)}}catch(t){if(a.warn("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(Ve.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(Ve.HEARTBEAT_FAILED)}}resumeReconnect(e){if(this.terminalDisconnectError)a.warn("Reconnect recovery skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()});else if(this.isLoggedIn)return this.reconnectTask||this.reconnectInProgress?(this.pendingReconnectReason=e,void a.warn("Reconnect recovery queued",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()})):void(this.connection.status===Be.CONNECTED&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),a.warn("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===Ve.SEND_TIMEOUT&&a.warn("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,terminalDisconnectCode:this.terminalDisconnectError?.code,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId,hasReconnectTask:null!==this.reconnectTask,hasActiveConnectionAttempt:null!==this.activeConnectionAttemptCancel}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof C))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(Un(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){const e=this.reconnectDelayReject;this.reconnectDelayReject=null,this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null),e?.(Xa("retry-delay"))}resolveLoginStageTimeout(e){return this.isLoginPhase&&this.activeLoginDeadline?this.activeLoginDeadline.clamp(e):e}isLoginDeadlineExpired(){return Boolean(this.isLoginPhase&&this.activeLoginDeadline&&this.activeLoginDeadline.remainingMs()<=0)}requireLoginTimeoutError(){const t=this.activeLoginDeadline;return t?(t.expire(),t.createTimeoutError()):new C("Login timeout",{code:e.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",retryable:!0}})}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay(),t=this.resolveLoginStageTimeout(e);if(t<=0)throw this.requireLoginTimeoutError();a.warn("Reconnect retry scheduled",{delayMs:Math.round(t),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise((e,s)=>{this.reconnectDelayReject=e=>{this.reconnectDelayReject=null,s(e)},this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,this.reconnectDelayReject=null,e()},t)})}buildConnectionEventPayload(e,t){const s=this.connection.error instanceof C?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:s?.code,errorMessage:s?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,t){if(e===Be.DISCONNECTED&&!this.hasEverConnected)return;if(e===Be.RECONNECT_FAILED&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===Be.DISCONNECTED||e===Be.RECONNECT_FAILED))return;const s=this.buildConnectionEventPayload(e,t),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,s,n=!1){const r=this.connection.status!==e;(r||n)&&(r&&(this.connection.status=e,this.connection.lastConnectedAt=e===Be.CONNECTED?Date.now():void 0),s&&this.dispatchConnectionEvent(e,t),a.debug("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,s=Date.now()){this.clearTokenTimers();const n=Math.max(t-s,0),r=s+Math.floor(.8*n);this.tokenLifecycle={token:e,issuedAt:s,expireAt:t,willExpireAt:r,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(r-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void a.warn("Provision auth token has invalid payload");const s=Number(t.expires_in);if(!Number.isFinite(s))return void a.warn("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,s)}catch(t){a.warn("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,a.warn("Token will expire"),this.eventHub.dispatch(qe.TOKEN_WILL_EXPIRE,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,a.warn("Token expired"),this.eventHub.dispatch(qe.TOKEN_EXPIRED,void 0))}isTokenExpiredConnectionError(t){return t instanceof C&&t.code===e.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(t){a.warn("Connection closing because token expired",{source:t}),this.connection.error=new C("Token expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:t,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(Ve.TOKEN_EXPIRED,!0,!0),this.updateStatus(Be.DISCONNECTED,Ve.TOKEN_EXPIRED,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(Ve.HEARTBEAT_FAILED)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,v)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(t){if(!this.reconnectInProgress)if(this.connection.status!==Be.CONNECTED&&this.connection.status!==Be.CONNECTING){this.isLoginPhase=!0,this.activeLoginDeadline=t??null,this.terminalDisconnectError=null,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(Ve.LOGIN,!0),this.isLoggedIn=!0}catch(s){throw this.isLoggedIn=!1,s instanceof C&&s.code===e.CONNECTION_LOGIN_TIMEOUT&&"login"===s.details?.stage&&(this.cancelActiveConnectionAttempt(),this.closeWebSocket(Ve.ERROR,!1,!1),this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!1)),s}finally{this.isLoginPhase=!1,this.activeLoginDeadline=null}}else a.warn("Connection already established or connecting")}async connectWithRetry(t,s){if(a.warn("Reconnect flow requested",{reason:t,throwOnFailure:s,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void a.warn("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:t,...this.getReconnectDiagnostic()});if(this.connection.status===Be.CONNECTED&&this.websocket)return;if(this.reconnectPaused)return void a.warn("Reconnect flow skipped",{guard:"reconnect-paused",reason:t,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let n=null,r=null,i=null;const o=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),a.warn("Reconnect flow started",{reason:t,throwOnFailure:s,maxAttempts:o,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<o;){if(this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(!this.isLoginPhase&&(this.reconnectPaused||!this.isOnline||!this.isLoggedIn)){i=Xa("ws");break}this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const e=this.isLoginPhase?Be.CONNECTING:Be.RECONNECTING;a.warn("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:o,reason:t,nextStatus:e,...this.getReconnectDiagnostic()}),this.updateStatus(e,t,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(t)}catch(c){if(n=c,this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(Za(c)){i=c,a.warn("Reconnect attempt cancelled",{attempt:this.reconnectAttempts,reason:t,...this.getReconnectDiagnostic()});break}if(a.warn("Connection attempt failed",{attempt:this.reconnectAttempts,reason:t,error:n}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(n))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(n)){r=n;break}}if(this.connectionRetry.getAttemptCount()>=o)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){a.warn("Reconnect retry loop interrupted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,...this.getReconnectDiagnostic()});break}try{await this.waitForReconnectDelay()}catch(c){if(!Za(c))throw c;i=c,a.warn("Reconnect retry delay cancelled",{reason:t,attempt:this.reconnectAttempts,...this.getReconnectDiagnostic()});break}}if(i){if(s)throw i;return}if(r){if(this.connection.error=r,s)throw this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!1),r;return this.reconnectPaused=!0,void this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!0)}if(s)throw this.updateStatus(Be.DISCONNECTED,Ve.ERROR,!1),n??new C("Connection failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,a.warn("Reconnect attempts exhausted",{reason:t,attempt:this.reconnectAttempts,maxAttempts:o,lastError:n,...this.getReconnectDiagnostic()}),this.updateStatus(Be.RECONNECT_FAILED,Ve.LIMIT,!0)}finally{this.reconnectInProgress=!1,a.warn("Reconnect flow finished",{reason:t,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.cancelActiveConnectionAttempt(),this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(Ve.RECONNECT,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(Be.CONNECTED,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),a.warn("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}triggerReconnect(e){if(a.warn("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.terminalDisconnectError)return a.warn("Reconnect trigger skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(!this.isLoggedIn)return a.warn("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectTask)return a.warn("Reconnect task reused",{reason:e,...this.getReconnectDiagnostic()}),this.reconnectTask;if(this.reconnectInProgress)return a.warn("Reconnect trigger skipped",{guard:"reconnect-in-progress-without-task",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectPaused)return a.warn("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();this.connection.status===Be.CONNECTED&&this.websocket&&this.closeWebSocket(e,!0,!0);const t=this.connectWithRetry(e,!1).finally(()=>(this.reconnectTask===t&&(this.reconnectTask=null),this.startPendingReconnectIfNeeded()??void 0));return this.reconnectTask=t,t}recoverConnectionForSend(){return this.connection.status===Be.CONNECTED&&this.websocket?Promise.resolve():this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.isLoginPhase||0===this.config.autoReconnectNumMax?(a.warn("Send connection recovery skipped",{guard:"connection-not-recoverable",...this.getReconnectDiagnostic()}),Promise.resolve()):this.reconnectTask?(a.warn("Send connection recovery reused",this.getReconnectDiagnostic()),this.reconnectTask):(this.reconnectPaused=!1,this.resetReconnectState(),a.warn("Send connection recovery requested",this.getReconnectDiagnostic()),this.triggerReconnect(Ve.RECONNECT))}startPendingReconnectIfNeeded(){const e=this.pendingReconnectReason;return this.pendingReconnectReason=null,!e||null!==this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.connection.status===Be.CONNECTED&&this.websocket?null:(this.reconnectPaused=!1,this.resetReconnectState(),a.warn("Queued reconnect recovery started",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e))}handleDisconnection(e){a.warn("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(Be.DISCONNECTED,e,!0),e!==Ve.TOKEN_EXPIRED&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,t,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(Be.DISCONNECTED,e,t)):s&&this.updateStatus(Be.DISCONNECTED,e,t)}createWebSocketConnection(){const t=this.resolveLoginStageTimeout(this.config.connectTimeout);return t<=0?Promise.reject(this.requireLoginTimeoutError()):new Promise((s,n)=>{const r=++this.connectionAttemptGeneration,i=this.pickNextServerUrl();a.debug("WebSocket connecting",{url:i}),this.clearSocketListeners();let o=!1,c=!1,d=null;const l=()=>{this.connectionAttemptGeneration===r&&(this.activeConnectionAttemptCancel=null)},u=e=>{o||(o=!0,d&&(clearTimeout(d),d=null),l(),n(e))};this.activeConnectionAttemptCancel=()=>{const e=Xa(c?"provision":"ws");this.rejectPendingProvision(e),u(e)},d=setTimeout(()=>{a.warn("WebSocket connection attempt timed out",{url:i,connectTimeout:t,...this.getReconnectDiagnostic()}),u(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new C("Connection timeout",{code:e.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},t),this.socketAdapter.connect({url:i,timeoutMs:t}).then(e=>{if(o||r!==this.connectionAttemptGeneration||this.reconnectPaused)return a.warn("WebSocket connection result discarded",{url:i,cancelled:o||r!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),e.close(),void u(Xa("ws"));d&&(clearTimeout(d),d=null),this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),c=!0,this.startProvision().then(()=>{if(this.resetProvisionHandlers(),o||r!==this.connectionAttemptGeneration||this.reconnectPaused)return a.warn("Provision result discarded",{url:i,cancelled:o||r!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),this.closeWebSocket(Ve.ERROR,!1,!1),void u(Xa("provision"));o||(o=!0,d&&(clearTimeout(d),d=null),l(),s())}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(Ve.ERROR,!1,!1),u(e instanceof Error?e:new Error(String(e)))})}).catch(t=>{if(o)return;const s=t instanceof C?t:new C("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});this.handleConnectionError(s,Ve.ERROR),u(s)})}).catch(t=>{if(t instanceof C)throw t;const s=new C("Failed to create WebSocket",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:t instanceof Error?t.message:String(t)}});throw this.handleConnectionError(s,Ve.ERROR),s})}cancelActiveConnectionAttempt(){this.activeConnectionAttemptCancel?.()}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(a.warn("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(Ve.CLOSE))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new C("Provision interrupted",{code:e.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(t,s){a.error("Connection error:",t),this.connection.error=t,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null);const n=t instanceof C?t:new C(t.message,{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",retryable:!0}});if(this.rejectPendingProvision(n)||this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(s)}handleTerminalConnectionError(e,t){if(a.warn("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.terminalDisconnectError=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.pendingReconnectReason=null,this.isLoggedIn=!1,this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(Be.DISCONNECTED,t,!0,!0)}async handleWebSocketMessage(t,s){try{if(s!==this.socketGeneration)return;a.debug("WebSocket message received",{dataType:typeof t});const r=await this.msyncCodec.normalizeIncoming(t);if(s!==this.socketGeneration)return;if(a.debug("handleWebSocketMessage data",{length:r.length}),!r.length)return;const i=this.msyncCodec.decompressIncoming(r);if(!i){const t=null!==this.provisionReject;return a.error("Failed to decompress mSync payload, closing connection",{stage:t?"provision":"connected"}),void(t?(this.rejectPendingProvision(new C("Failed to decompress Provision payload",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(Ve.ERROR,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(i))return void a.debug("Ignore server normal close payload",{length:i.length});let o=null;try{o=this.msyncCodec.decodeMsync(i)}catch(n){const e=n instanceof Error?n:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void a.warn("Discard invalid mSync payload",{length:i.length,message:e.message,prefixHex:Array.from(i.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(i.subarray(Math.max(0,i.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw a.warn("Invalid mSync payload signature",{length:i.length,prefixHex:Array.from(i.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),a.debug("handleWebSocketMessage decoded",{command:o.command}),o.command){case rs:this.handleProvisionMessage(o.payload);break;case is:this.handleLogoutMessage(o.payload);break;case ns:this.handleNoticeMessage(o.payload);break;case ss:this.handleUnreadMessage(o.payload);break;case ts:this.handleSyncMessage(o.payload)}}catch(n){const e=n instanceof Error?n:new Error("Failed to handle mSync payload");a.error("Failed to handle mSync payload",e),this.handleConnectionError(e,Ve.ERROR)}}startProvision(){const t=this.resolveLoginStageTimeout(S);if(t<=0)return Promise.reject(this.requireLoginTimeoutError());this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new C("Provision timeout",{code:e.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},t);try{const e=this.msyncCodec.encodeProvision();a.debug("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new C("Provision send failed",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(t){const s=this.msyncCodec.decodeProvision(t);if(this.isLoginPhase&&this.activeLoginDeadline?.markProvisionReceived(),this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),s.ok)this.msyncCodec.updateResource(s.resource),this.setupTokenLifecycleFromProvision(s.authToken),this.provisionResolve?.();else{a.warn("Provision rejected",{statusCode:s.statusCode,reason:s.reason});const t=Rn(s.statusCode,s.reason),n=t.code===e.UNKNOWN?e.CONNECTION_PROVISION_REJECTED:t.code;this.provisionReject?.(new C("Provision rejected",{code:n,details:{stage:"provision",reason:s.reason,statusCode:s.statusCode,retryable:t.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),s=t?this.getQueueId(t):null,n=!!t&&this.isSelfQueue(t),r=!!t&&this.isQueueInList(t);t&&s&&(n||r||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),s=t.filter(e=>this.getQueueId(e));if(s.length){s.length!==t.length&&a.warn("Unread queues without usable identity were ignored",{ignoredCount:t.length-s.length}),this.startOfflineMessageSync(s);for(const e of s)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,Ve.ERROR);if(!this.messageReceiver)return;const s=this.messageReceiver.handleSyncPayload(e);if(a.debug("handleSyncMessage result",{result:s}),!s)return;(void 0!==s.queue||void 0!==s.nextKey||void 0!==s.isLast)&&this.handleSyncQueueState(s)}handleSyncQueueState(e){a.debug("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:s,queueId:n}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(n)){const t=this.offlineMessageQueueCounts.get(n)??0;this.offlineMessageQueueCounts.set(n,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const r=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(n),this.removeQueueEntry(s),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(r){if(r!==this.nextKey||!this.isSameQueue(s,this.currentQueue))return this.nextKey=r,this.currentQueueId=n,this.currentQueue=s,void this.sendLastSession(s,r);this.removeQueueEntry(s),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,s=t?this.getQueueName(t):null,n=t?this.getQueueId(t):null,r=void 0!==t&&null!==n&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&n&&r)return{queue:t,queueId:n};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,c=i??o??this.queues[0],d=c?this.getQueueName(c):null,l=c?this.getQueueId(c):null;return c&&l?(a.warn("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:s,responseQueueId:n,fallbackQueueName:d,fallbackQueueId:l,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:c,queueId:l}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);a.warn("Logout message received",t)}resolveStatisticDisconnectError(t){for(const s of t)switch(s.operation){case 1:return new C("User has been removed",{code:e.USER_REMOVED,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 2:return new C("The user is already logged on another device",{code:e.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1,...s.reason?{loginInfoCustomExt:s.reason}:{}}});case 3:return new C("The user was kicked by changing password",{code:e.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 4:return new C("The user was kicked by other device",{code:e.USER_KICKED_BY_OTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.closeWebSocket(Ve.CLOSE,!0,!0),this.updateStatus(Be.DISCONNECTED,Ve.CLOSE,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),a.warn("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){return Vi(e.socketAdapter)}attachSocketListeners(t,s){this.clearSocketListeners(),this.socketDisposers=[t.onMessage(e=>{this.websocket===t&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(e,s)))}),t.onError(()=>{if(this.websocket!==t)return;a.warn("WebSocket error",{stage:"ws"});const s=new C("WebSocket connection error",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(s,Ve.ERROR)}),t.onClose(e=>{this.websocket===t&&this.handleWebSocketClose(e)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===o.OPEN)try{const t=this.msyncCodec.prepareOutgoing(e);a.debug("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{a.error("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){a.error("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);a.debug("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){a.debug("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const s=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(s)}sendNextQueue(){a.debug("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=/* @__PURE__ */new Set;for(const s of e){const e=this.getQueueId(s);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=E({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of t){this.offlineMessageQueueCounts.set(e,0);const t=this.offlineMessageReport?.startRequest({requestName:"MSYNC_SYNCOFFLINEMESSAGE",method:"WS",url:e});t&&this.offlineMessageQueueReports.set(e,t)}this.offlineMessageSyncLifecycleActive&&this.eventHub.dispatch(qe.OFFLINE_MESSAGE_SYNC_START,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const t=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:t}),this.offlineMessageQueueReports.delete(e),this.offlineMessageQueueNames.delete(e),this.offlineMessageQueueNames.size>0||(this.offlineMessageSyncing=!1,this.offlineMessageReport?.finish({code:0,success:!0,resultCount:this.offlineMessageTotalCount}),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleActive=!1,this.eventHub.dispatch(qe.OFFLINE_MESSAGE_SYNC_FINISH,void 0)))}isQueueInList(e){return this.queues.some(t=>this.isSameQueue(t,e))}isSelfQueue(e){const t=this.getQueueName(e),s=this.getQueueResource(e),n=this.msyncCodec.getContext();return t===n.userId&&s===n.clientResource}getQueueName(e){return"string"==typeof e.name&&e.name.trim().length>0?e.name:null}getQueueResource(e){return this.getQueueField(e,"clientResource")}getQueueId(e){const t=this.getQueueName(e);if(t)return`name:${t}`;const s=this.getQueueField(e,"domain"),n=this.getQueueResource(e);if(s)return`domain:${s}|resource:${n??""}`;if(n)return`resource:${n}`;const r=this.getQueueField(e,"appKey");return r?`appKey:${r}`:null}getQueueField(e,t){const s=e[t];return"string"==typeof s&&s.trim().length>0?s:null}isSameQueue(e,t){if(!e||!t)return!1;const s=this.getQueueId(e),n=this.getQueueId(t);return null!==s&&s===n}resetSyncState(){this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames.clear(),this.offlineMessageReport?.discard(),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageTotalCount=0}}const tc=new Uint8Array([99,109]),sc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nc=e=>Array.isArray(e)&&e.every(sc),rc=e=>"string"==typeof e?e:void 0,ic=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,oc=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},ac=(t,s)=>{const n=t[s],r=t[s+1],i=t[s+2],o=t[s+3];if("number"!=typeof n||"number"!=typeof r||"number"!=typeof i||"number"!=typeof o)throw new T("Combine payload length header is invalid",{code:e.COMBINE_PARSE_FAILED});return n<<24|r<<16|i<<8|o},cc=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},dc=(e,t)=>{const s=Yi().lookupType(e).decode(t);if(!sc(s))throw new Error(`${e} decoded result is invalid`);return s},lc=e=>sc(e)&&"string"==typeof e.name?e.name:"",uc=(e,t,s)=>{const n=(nc(e.contents)?e.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const r=(e=>{const t=ic(e.type)??fs,s=Boolean(rc(e.remotePath))||Boolean(rc(e.title))||Boolean(rc(e.summary))||(ic(e.combineLevel)??0)>0,n=t===fs&&0===e.subType&&s;if(t===bs||n){const t=ic(e.combineLevel)??0;return{type:"combine",body:{title:rc(e.title)??"",summary:rc(e.summary)??"",filename:rc(e.displayName)??"combine",filetype:"application/octet-stream",url:rc(e.remotePath),secret:rc(e.secretKey),fileLength:ic(e.fileLength),combineLevel:t},combineLevel:t}}if(t===fs)return{type:"text",body:{content:rc(e.text)??""}};if(t===Ss)return{type:"cmd",body:{action:rc(e.action)??""}};if(t===Es){const t=io(nc(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:rc(e.customEvent)??"",params:t}}}if(t===Is)return{type:"location",body:{latitude:ic(e.latitude)??0,longitude:ic(e.longitude)??0,address:rc(e.address),buildingName:rc(e.buildingName)}};if(t===gs){const t=sc(e.size)?e.size:{},s=rc(e.remotePath)??"",n=p(s),r=rc(e.thumbnailRemotePath),i=u(e.imageType)===h;return{type:"image",body:{localUrl:"",filename:rc(e.displayName)??"image",filetype:"application/octet-stream",width:ic(t.width)??0,height:ic(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:rc(e.secretKey),fileLength:ic(e.fileLength),thumbnailUrl:r??n.thumbnailUrl}}}if(t===ys){const t=sc(e.size)?e.size:{};return{type:"video",body:{url:rc(e.remotePath)??"",filename:rc(e.displayName)??"video",filetype:"application/octet-stream",duration:ic(e.duration)??0,width:ic(t.width),height:ic(t.height),secret:rc(e.secretKey),fileLength:ic(e.fileLength),thumbnailUrl:rc(e.thumbnailRemotePath)}}}if(t===vs)return{type:"voice",body:{url:rc(e.remotePath)??"",filename:rc(e.displayName)??"voice",filetype:"application/octet-stream",duration:ic(e.duration)??0,secret:rc(e.secretKey),fileLength:ic(e.fileLength)}};if(t===Cs)return{type:"file",body:{url:rc(e.remotePath)??"",filename:rc(e.displayName)??"file",filetype:"application/octet-stream",secret:rc(e.secretKey),fileLength:ic(e.fileLength)}};return null})(n);if(!r)throw new Error("MessageBody content type is unsupported");const i=lc(e.from)||lc(s?.from)||`unknown-${t}`,o=lc(e.to)||lc(s?.to)||`unknown-${t}`,a=(c=e.type)===cs?"groupChat":c===ds?"chatRoom":"singleChat";var c;const d=o||i,l=Number(no(s?.timestamp))||Date.now(),m=io(nc(e.ext)?e.ext:void 0),f={msgServerId:no(s?.id),msgLocalId:"",type:r.type,sender:{userId:i},conversationId:d,conversationType:a,timestamp:l,body:r.body,ext:m};return"number"==typeof r.combineLevel&&(f.body.combineLevel=r.combineLevel),f},hc=(e,t)=>{const s=[];try{const r=dc("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=dc("easemob.pb.MessageBody",i);return uc(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=dc("easemob.pb.MessageBody",e);return uc(s,t)}catch(r){s.push(r instanceof Error?r.message:String(r))}try{const s=dc("easemob.pb.MessageBody.Content",e);return uc({type:as,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("; "))},pc=(t,s)=>{const n=Un(t);try{const t=JSON.parse(n);if(!sc(t))throw new T("Combine payload item is invalid",{code:e.COMBINE_PARSE_FAILED,details:{index:s}});return t}catch(r){if(r instanceof T)throw r;try{return hc(t,s)}catch(i){throw new T("Combine payload item parse failed",{code:e.COMBINE_PARSE_FAILED,details:{index:s,cause:r instanceof Error?r.message:String(r),protobufCause:i instanceof Error?i.message:String(i)}})}}},mc=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class fc{constructor(e,t,s,n){this.websocket=null,this.pendingMessages=/* @__PURE__ */new Map,this.ackTimeout=A,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=s,this.msyncCodec=e,this.attachmentUploader=n??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(t,s){const n=this.msyncCodec.toProtocolId(t.msgLocalId);if(es(t))throw new b("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==o.OPEN){const s=this.msyncCodec.toProtocolId(t.msgLocalId);throw new b("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:s,retryable:!0}})}let r={...t,sendStatus:"sending"};Do(t,r),a.debug("Message send queued",{msgLocalId:t.msgLocalId,protocolId:n,type:t.type,conversationType:t.conversationType,conversationId:t.conversationId});try{const e="combine"===r.type?this.prepareCombineMessage(r):r,t={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,s):e,sendStatus:"sending"};Do(r,t),r=t,s?.onSending?.(t);const n=await this.doSendMessage(t);return s?.onSuccess?.(n),n}catch(i){const e={...r,sendStatus:"failed"};throw Do(r,e),s?.onFailed?.(e,i instanceof Error?i:new Error(String(i))),i}}async sendAction(e,t){const s=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&a.debug("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:s,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const n=this.msyncCodec.encodeActionMessage(e,s);"clearAllConversationUnreadMessageCount"===e.kind&&a.debug("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:s,payloadBytes:n.byteLength});const r="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(s,n,t,this.createPendingDataReport({category:"message",operationName:r,operationType:"MESSAGE",requestName:r,msgId:e.messageId,messageType:mc(e.conversationType)}))}async sendChatRoomOperation(e,t){const s=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),n=this.msyncCodec.encodeChatRoomOperation(e,s),r="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(s,n,t,this.createPendingDataReport({category:"chatroom",operationName:r,operationType:"CHATROOM",requestName:r,msgId:e.chatRoomId}))}async doSendMessage(t){const s=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:t.msgLocalId,messageType:mc(t.conversationType)});return new Promise((n,r)=>{const i=this.msyncCodec.toProtocolId(t.msgLocalId),c=setTimeout(()=>{this.pendingMessages.delete(i),this.finishPendingDataReport(s,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),r(new b("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(i,{kind:"message",message:t,protocolId:i,timeoutId:c,resolve:e=>{clearTimeout(c),n(e)},reject:e=>{clearTimeout(c),r(e)},report:s});try{if(!this.websocket||this.websocket.readyState!==o.OPEN)throw new b("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}});const n=this.msyncCodec.encodeChatMessage(t,i),d=this.msyncCodec.prepareOutgoing(n);Promise.resolve(this.websocket.send(d)).catch(n=>{const o=n instanceof Error?n.message:String(n);this.pendingMessages.delete(i),clearTimeout(c),this.finishPendingDataReport(s,{code:-1,success:!1,description:o}),a.warn("Message send socket failure",{msgLocalId:t.msgLocalId,protocolId:i,websocketReadyState:this.websocket?.readyState??null,cause:o}),r(new b(`WebSocket send failed: ${o}`,{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0,cause:o}}))}),a.debug("Message sent",{msgLocalId:t.msgLocalId,protocolId:i})}catch(d){if(this.pendingMessages.delete(i),clearTimeout(c),this.finishPendingDataReport(s,{code:d instanceof b?d.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof b)throw d;throw new b("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}})}})}async sendProtocolPayload(t,s,n,r){return new Promise((i,a)=>{const c=setTimeout(()=>{this.pendingMessages.delete(t),this.finishPendingDataReport(r,{code:e.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),a(new b("Message ACK timeout",{code:e.MESSAGE_ACK_TIMEOUT,details:{protocolId:t,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(t,{kind:"action",protocolId:t,timeoutId:c,createAckError:n,resolve:i,reject:a,report:r});try{if(!this.websocket||this.websocket.readyState!==o.OPEN)throw new b("WebSocket is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0}});const n=this.msyncCodec.prepareOutgoing(s);Promise.resolve(this.websocket.send(n)).catch(s=>{const n=s instanceof Error?s.message:String(s);this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(r,{code:-1,success:!1,description:n}),a(new b(`WebSocket action send failed: ${n}`,{code:e.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0,cause:n}}))})}catch(d){if(this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(r,{code:d instanceof b?d.code:e.MESSAGE_ENCODE_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof b)throw d;a(new b("Message encode failed",{code:e.MESSAGE_ENCODE_FAILED,details:{protocolId:t,retryable:!1}}))}})}prepareCombineMessage(t){const s=t.body,n=s.messageList??[];He(n);const r=ze(n);je(r);const i=((t,s)=>{try{const n=t.map((t,n)=>{const r=s(t,n);if(0===r.length)throw new b("Combine payload item encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{index:n}});return r}),r=tc.length+n.reduce((e,t)=>e+4+t.length,0)+1,i=new Uint8Array(r);let o=0;i.set(tc,o),o+=tc.length;for(const e of n){const t=oc(e.length);i.set(t,o),o+=t.length,i.set(e,o),o+=e.length}const a=cc(i.subarray(0,i.length-1));return i[i.length-1]=a,i}catch(n){if(n instanceof b)throw n;throw new b("Combine payload encode failed",{code:e.COMBINE_ENCODE_FAILED,details:{cause:n instanceof Error?n.message:String(n)}})}})(n,e=>this.msyncCodec.encodeCombineMessageMeta(e)),o=new ArrayBuffer(i.byteLength);new Uint8Array(o).set(i);const a=new File([o],s.filename||"combine",{type:s.filetype||"application/octet-stream"}),c=We(a);if(!c&&!this.attachmentUploader)throw new b("Combine payload local url generation failed",{code:e.COMBINE_ENCODE_FAILED});$e.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 Do(t,d),Qe(t,d),d}handleAck(e,t,s,n){const r=this.pendingMessages.get(e);if(!r)return void a.debug("Received ACK without a tracked pending message",{protocolId:e});if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:200,success:!0}),void r.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:n});const i={...r.message,...this.resolveReplacedMessage(r.message,s),sendStatus:"sent",msgServerId:t||s?.msgServerId||r.message.msgServerId};Do(r.message,i),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:200,success:!0}),"image"!==i.type&&"video"!==i.type&&"voice"!==i.type&&"file"!==i.type&&"combine"!==i.type||$e.delete(i.msgLocalId),a.debug("Message ACK matched",{protocolId:e,msgLocalId:i.msgLocalId,msgServerId:i.msgServerId??null,type:i.type,conversationType:i.conversationType,conversationId:i.conversationId}),this.eventHub.dispatch(Ge.MESSAGE_SENT,i),r.resolve(i)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const s=this.pendingMessages.get(e);if(!s)return;if("action"===s.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(s.report,{code:t instanceof b?t.code:-1,success:!1,description:t.message}),void s.reject(t);const n={...s.message,sendStatus:"failed"};Do(s.message,n),this.pendingMessages.delete(e),this.finishPendingDataReport(s.report,{code:t instanceof b?t.code:-1,success:!1,description:t.message}),a.warn("Message send failed after ACK/error",{protocolId:e,msgLocalId:n.msgLocalId,type:n.type,conversationType:n.conversationType,conversationId:n.conversationId,error:t.message}),s.reject(t)}handleAckFailure(e,t,s,n){const r=this.pendingMessages.get(e);if(r)return"action"===r.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t,success:!1,description:s??n.message}),void r.reject(r.createAckError?.(t,s)??n)):void this.handleSendError(e,n)}setWebSocket(e){this.websocket=e}destroy(){for(const[t,s]of this.pendingMessages)clearTimeout(s.timeoutId),this.finishPendingDataReport(s.report,{code:-1,success:!1,description:"Message sender destroyed"}),s.reject(new b("Message sender destroyed",{code:e.MESSAGE_SENDER_DESTROYED,details:"message"===s.kind?{msgLocalId:s.message.msgLocalId,protocolId:t,retryable:!1}:{protocolId:t,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=w){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(a.warn("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=E({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(t)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:t,request:t.startRequest({requestName:e.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(e,t){e&&!e.released&&(e.released=!0,e.request.finish(t),e.operation.finish(t),"message"===e.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<w&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<w&&(this.chatRoomReportSaturated=!1)))}}class gc{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!==Zt.START&&t.stream.status!==Zt.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 yc{constructor(e,t){this.completedIds=/* @__PURE__ */new Set,this.eventHub=e,this.cache=t??new gc}handle(e){const t=this.resolveMessageId(e);if(!t)return void a.warn("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void a.debug("stream message already completed, ignore",{msgId:t});if(e.stream.status===Zt.FULL)return void this.handleFullChunk(t,e);const s=this.cache.get(t);if(s?.completed)return void a.debug("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:n}=this.cache.addChunk(t,e);n?a.debug("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const s of t){const t=this.cache.get(e);if(!t)return;const n=t.fullText,r=s.stream.deltaText,i=`${n}${r}`,o=s.stream.errorType>0?Zt.ERROR:s.stream.status,a=this.buildDispatchMessage(s,{status:o,fullText:i,deltaText:r});if(this.eventHub.dispatch(ct.STREAM_MESSAGE,a),this.cache.markDispatched(e,s,i),o===Zt.START_COMPLETED||o===Zt.COMPLETED||o===Zt.ERROR){const t=o===Zt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else a.debug("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const s=this.cache.get(e),n=s?.fullText??"",r=this.resolveFullText(t,n),i=this.resolveDeltaText(n,r,t.stream.deltaText),o=!s||-1===s.lastDispatchedSeq&&0===s.chunksBySeq.size,a=t.stream.errorType>0?Zt.ERROR:o?Zt.START_COMPLETED:Zt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:r,deltaText:i});this.eventHub.dispatch(ct.STREAM_MESSAGE,c);const d=a===Zt.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:Zt.ERROR,fullText:r,deltaText:i});this.eventHub.dispatch(ct.STREAM_MESSAGE,o),this.cache.markCompleted(e,"timeout_error",r),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const s=e.stream.fullText;if(s&&s.length>=t.length)return s;const n=e.body.content;return n&&n.length>=t.length?n:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,s){return t.startsWith(e)?t.slice(e.length):s}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class Ic{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 vc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Cc{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new yc(s),this.messageContexts=/* @__PURE__ */new Map,this.recentMessageIds=new Ic(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{a.debug("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);a.debug("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:s,messages:n}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),s&&(a.debug("Decoded sync ACK",{ok:s.ok,protocolId:s.protocolId,serverId:s.serverId??null,statusCode:s.statusCode??null,reason:s.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(s,t.replacedMessage));for(const e of n)this.dispatchMessage(e);return t}catch(t){a.error("Failed to decode sync payload",t)}return null}handleAck(t,s){if(t.ok)return a.debug("ACK accepted",{protocolId:t.protocolId,serverId:t.serverId??null,hasReplacedMessage:Boolean(s)}),void(t.chatRoomInfo?this.messageSender.handleAck(t.protocolId,t.serverId,s,t.chatRoomInfo):this.messageSender.handleAck(t.protocolId,t.serverId,s));a.warn("ACK rejected",{protocolId:t.protocolId,statusCode:t.statusCode,reason:t.reason,hasReplacedMessage:Boolean(s)});const n=((t,s)=>{const n=Rn(t,s),r=n.code===e.UNKNOWN?e.MESSAGE_SEND_FAILED:n.code;return{code:r,message:_n[r]??(s?`Message send failed: ${s}`:"Message send failed for an unknown reason"),retryable:n.retryable}})(t.statusCode,t.reason),r=new b(n.message,{code:n.code,details:{protocolId:t.protocolId,serverCode:t.statusCode,reason:t.reason,retryable:!1}});this.messageSender.handleAckFailure(t.protocolId,t.statusCode,t.reason,r)}dispatchMessage(e){if(es(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?a.debug("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(ct.MESSAGE,e),a.debug("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{a.warn("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const s of e)if("presence"===s.type)this.handlePresenceNotify(s);else if("contact"===s.type)this.handleContactNotify(s);else if("group"===s.type)this.handleGroupNotify(s);else if("thread"===s.type)this.handleChatThreadNotify(s);else if("chatroom"===s.type)this.handleChatRoomNotify(s);else if("reaction"===s.type)this.handleReactionNotify(s);else if("conv"===s.type)this.handleConversationNotify(s);else if("multiDevice"===s.type)this.handleMultiDeviceNotify(s);else if("message_receipts"===s.type){const e=this.toMessageReceiptPayload(s);e&&t.push(e)}else"message_recalled"===s.type?this.handleMessageRecalledNotify(s):"message_updated"===s.type?this.handleMessageUpdatedNotify(s):"message_delivered"===s.type?this.handleMessageDeliveredNotify(s):this.handleUserInfoNotify(s);t.length>0&&this.eventHub.dispatch(ct.MESSAGE_READ_RECEIPTS,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const s=e.data;if(!s||"object"!=typeof s)return;const n=s,r="string"==typeof n.username?n.username:"string"==typeof n.userId?n.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=n.metadata&&"object"==typeof n.metadata&&!Array.isArray(n.metadata)?n.metadata:null,o="number"==typeof n.lastModified?n.lastModified:"string"==typeof n.lastModified?Number(n.lastModified):Number.NaN;if(!r||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:r,metadata:i,lastModified:o};this.eventHub.dispatch(Ge.USER_INFO_NOTIFY,a)}handleContactNotify(e){if(a.debug("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==dt.INVITED&&e.eventName!==dt.DELETED&&e.eventName!==dt.ADDED&&e.eventName!==dt.REFUSE&&e.eventName!==dt.AGREED)return;const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.from&&s.from&&"string"==typeof s.to&&s.to&&"string"==typeof s.message&&this.eventHub.dispatch(e.eventName,s)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t,n=Array.isArray(s.values)?s.values:[];if(0===n.length)return;const r=[];for(const i of n){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),s="string"==typeof e.uid?e.uid:"";s&&r.push({userId:s,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==r.length&&this.eventHub.dispatch(lt.STATUS_CHANGE,r)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(Ge.GROUP_NOTIFY,s)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"string"==typeof s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(Ge.CHATROOM_NOTIFY,s)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const s of t){if(!vc(s)||"string"!=typeof s.messageId)continue;const e=this.resolveReactionConversationContext(s);e&&this.eventHub.dispatch(ct.REACTION_CHANGED,{messageId:s.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(s.reactions),timestamp:this.normalizeTimestamp(s.ts)})}}handleConversationNotify(e){if(!vc(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const s=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===s.clientResource&&"string"==typeof t.from&&t.from===s.userId)return;const n="string"==typeof t.ext?t.ext:"",r="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";n&&i&&o&&this.eventHub.dispatch(ct.PINNED_MESSAGE_CHANGED,{messageId:n,conversationId:"chat"===r?i:o,conversationType:"chat"===r?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!vc(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(!vc(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(!vc(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(!vc(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(ct.MESSAGE_DELIVERED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!vc(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(ct.MESSAGE_RECALLED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}handleMessageUpdatedNotify(e){if(!vc(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!vc(t.message)||"string"!=typeof t.message.type||!vc(t.message.body)||!vc(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...vc(t.message.modifiedInfo)?{modifiedInfo:{operatorId:"string"==typeof t.message.modifiedInfo.operatorId?t.message.modifiedInfo.operatorId:"",operationCount:"number"==typeof t.message.modifiedInfo.operationCount?t.message.modifiedInfo.operationCount:0,operationTime:"number"==typeof t.message.modifiedInfo.operationTime?t.message.modifiedInfo.operationTime:0}}:{}};this.eventHub.dispatch(ct.MESSAGE_UPDATED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",message:s,timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}normalizeUpdatedMessageBody(e,t){if("text"!==e)return t;const s="string"==typeof t.content?t.content:"string"==typeof t.message?t.message:void 0;if(void 0===s)return t;const{message:n,...r}=t;return{...r,content:s}}handleChatThreadNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t;"onChatThreadChange"===s.eventName&&s.payload&&"object"==typeof s.payload&&this.eventHub.dispatch(Ge.CHAT_THREAD_NOTIFY,s)}normalizePresenceStatus(e){if(!e||"object"!=typeof e)return[];return Object.entries(e).map(([e,t])=>({device:e,status:Number(t)||0}))}destroy(){this.streamMessageHandler.destroy(),this.recentMessageIds.clear(),this.messageContexts.clear()}rememberMessageContext(e){const t=this.resolveMessageContextId(e),s=this.resolveMessageConversationContext(e);if(t&&s)for(this.messageContexts.delete(t),this.messageContexts.set(t,s);this.messageContexts.size>500;){const e=this.messageContexts.keys().next().value;if(!e)break;this.messageContexts.delete(e)}}resolveMessageReceiptContext(e,t,s){const n=this.messageContexts.get(e);return n||("groupChat"===s?{conversationId:t,conversationType:"groupChat"}:{conversationId:t,conversationType:"singleChat"})}resolveMessageContextId(e){return"string"==typeof e.msgServerId&&e.msgServerId.length>0?e.msgServerId:"string"==typeof e.msgLocalId&&e.msgLocalId.length>0?e.msgLocalId:""}resolveMessageConversationContext(e){if("string"!=typeof e.conversationId||!e.conversationId)return null;if("groupChat"===e.conversationType)return{conversationId:e.conversationId,conversationType:"groupChat"};if("chatRoom"===e.conversationType)return{conversationId:e.conversationId,conversationType:"chatRoom"};if("singleChat"!==e.conversationType)return null;const t=this.msyncCodec.getContext().userId,s="SEND"===e.direct||e.sender.userId===t?e.conversationId:e.sender.userId;return s?{conversationId:s,conversationType:"singleChat"}:null}resolveReactionConversationContext(e){const t="string"==typeof e.from?e.from:"",s="string"==typeof e.to?e.to:"",n="string"==typeof e.channel_type?e.channel_type:"";if(!t||!s)return null;if("groupChat"===n||"groupchat"===n||"group"===n)return{conversationId:s,conversationType:"groupChat",from:t,to:s};if(""!==n&&"chat"!==n&&"singleChat"!==n)return null;return{conversationId:t===this.msyncCodec.getContext().userId?s:t,conversationType:"singleChat",from:t,to:s}}normalizeReactionList(e){if(!Array.isArray(e))return[];const t=[];for(const s of e)vc(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)!vc(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 Sc=e=>e instanceof Error?e.message:String(e);class Ec{constructor(e){this.requestAdapter=N(e)}async downloadAndParse(t){const s=t.url.trim();if(!s)throw new M("Combine message url is required",{code:e.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const n="number"==typeof t.maxItems?t.maxItems:Ye;Je(1,n);const r=R(s,t.secret);try{const s=await this.requestAdapter.request({url:r,method:"GET",responseType:"arraybuffer",timeoutMs:t.timeoutMs??15e3,headers:{[_]:d()}});if(401===s.status||403===s.status)throw new D(401===s.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===s.status?e.AUTH_UNAUTHORIZED:e.AUTH_FORBIDDEN,details:{url:r,httpStatus:s.status}});if(s.status>=400)throw new T("Combine payload download failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{status:s.status,url:r}});const i=(t=>{if(t.length<tc.length+1)throw new T("Combine payload is too short",{code:e.COMBINE_PARSE_FAILED});const s=t.subarray(0,tc.length);if(s[0]!==tc[0]||s[1]!==tc[1])throw new T("Combine payload header is invalid",{code:e.COMBINE_PARSE_FAILED});const n=t.subarray(0,t.length-1),r=cc(n),i=t[t.length-1]??0;if(i!==r)throw new T("Combine payload checksum failed",{code:e.COMBINE_PARSE_FAILED,details:{expectedChecksum:r,actualChecksum:i}});const o=[];let a=tc.length;const c=t.length-1;for(;a<c;){if(a+4>c)throw new T("Combine payload length header is incomplete",{code:e.COMBINE_PARSE_FAILED});const s=ac(t,a);if(a+=4,s<=0||a+s>c)throw new T("Combine payload item length is invalid",{code:e.COMBINE_PARSE_FAILED,details:{itemLength:s}});const n=t.subarray(a,a+s);a+=s;const r=pc(n,o.length);o.push(r)}if(a!==c)throw new T("Combine payload has unexpected trailing bytes",{code:e.COMBINE_PARSE_FAILED,details:{offset:a,expected:c}});return o})((t=>{if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if("string"==typeof t)return Dn(t);throw new T("Combine payload response type is invalid",{code:e.COMBINE_DOWNLOAD_FAILED})})(s.data));return Je(i.length,n),He(i),i.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(i){if(i instanceof M||i instanceof D||i instanceof T)throw i;throw new T("Combine payload download or parse failed",{code:e.COMBINE_DOWNLOAD_FAILED,details:{cause:Sc(i),url:r}})}}}const bc=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"}},Tc=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 Ac{constructor(e){this.requestAdapter=N(e)}async download(t,s=15e3){if("image"!==t.type&&"video"!==t.type&&"voice"!==t.type&&"file"!==t.type)throw new M("message does not contain downloadable attachment",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:n,secret:i}=(e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}})(t);if(!n)throw new M("attachment url is required",{code:e.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});let o;try{o=await this.requestAdapter.request({url:R(n,i),method:"GET",responseType:"arraybuffer",timeoutMs:s,headers:{[_]:d()}})}catch(a){if("object"==typeof a&&null!==a&&a.code===r.MISSING_CAPABILITY)throw new U("request adapter is required for attachment download");throw a}if(401===o.status)throw new D("attachment download unauthorized",{code:e.AUTH_UNAUTHORIZED,details:{url:n,httpStatus:o.status}});if(403===o.status)throw new D("attachment download forbidden",{code:e.AUTH_FORBIDDEN,details:{url:n,httpStatus:o.status}});if(404===o.status){const t=("string"==typeof o.data?o.data:"").includes("expired");throw new L(t?"attachment file is expired":"attachment not found",t?e.ATTACHMENT_EXPIRED:e.ATTACHMENT_NOT_FOUND)}if(429===o.status)throw new L("attachment download rate limited",e.SERVICE_LIMIT_EXCEEDED);if(o.status>=400)throw new L("attachment download failed",e.FILE_DOWNLOAD_FAILED,{details:{status:o.status,url:n}});return{filename:bc(t),mimeType:Tc(t),size:(()=>{switch(t.type){case"image":case"video":case"voice":return t.body.fileLength;case"file":return t.body.fileLength??t.body.fileSize;default:return}})(),data:new Uint8Array(o.data),downloadUrl:n}}}const wc=(e,t,s)=>({Authorization:`Bearer ${e}`,Accept:t,[_]:d(),...s??{}}),Nc=async t=>{const s=wc(t.token,"application/json",t.headers),n=Date.now(),r="upload.multipart.init"===t.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===t.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",i=t.dataReportOperation?.startRequest({requestName:r,method:t.method,url:t.url});let o=0;a.debug("Upload request start",{operation:t.operation,method:t.method});try{const r=await t.requestAdapter.request({url:t.url,method:t.method,headers:s,responseType:"json",timeoutMs:K});o=r.status;const d=Date.now()-n;if(r.status<200||r.status>=300)throw a.warn("Upload response error",{operation:t.operation,method:t.method,status:r.status,duration:d}),new k("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:r.status}});a.debug("Upload response success",{operation:t.operation,method:t.method,status:r.status,duration:d});const l="string"==typeof(c=r.data)?JSON.parse(c):c;return i?.finish({code:r.status,success:!0}),l}catch(d){if(i?.finish({code:0!==o?o:d instanceof k?d.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof k)throw d;throw a.warn("Upload request failed",{operation:t.operation,method:t.method}),new k("Upload request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}var c},Mc=async t=>{const s=Date.now(),n=t.dataReportOperation?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:t.url});a.debug("Upload part start",{operation:"upload.multipart.part",partNumber:t.partNumber});try{const r=await t.uploadAdapter.upload({url:t.url,method:"PUT",headers:wc(t.token,"*/*",{"restrict-access":"true"}),source:{sourceType:"web-file",file:t.part,name:`${t.fileName}.part-${t.partNumber}`,mimeType:t.fileType,size:t.part.size},fields:{part_number:t.partNumber},fileFieldName:"part_file",timeoutMs:K,onProgress:e=>t.onProgress?.(e.loaded)}),i=Date.now()-s;if(r.status<200||r.status>=300)throw new k("Upload part failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:t.url,partNumber:t.partNumber,status:r.status,response:r.body}});a.debug("Upload part success",{operation:"upload.multipart.part",partNumber:t.partNumber,duration:i}),n?.finish({code:r.status,success:!0})}catch(r){const e=It(r),s=e.details&&"object"==typeof e.details?e.details:void 0;throw n?.finish({code:e.code,success:!1,description:e.message}),a.warn("Upload part failed",{operation:"upload.multipart.part",partNumber:t.partNumber}),new k(e.message,{code:e.code,details:{...s,url:t.url,partNumber:t.partNumber}})}},Rc=async t=>{if(t.fileSize<=O)throw new k("Multipart not required",{code:e.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:s,file:n,conversationId:r,conversationType:i,fileName:o,fileType:a,fileSize:c,messageType:d,imageType:l,md5:u,width:h,height:p}=t,m=(e=>N(e))(s.requestAdapter),f=(t=>{if(t)return t;const s=Ar();if(s)return s;throw new k("Upload adapter is required for multipart upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:g,appName:y}=P(s.appKey),I=`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload`;let v;try{v=await Nc({url:I,method:"POST",token:s.token,operation:"upload.multipart.init",requestAdapter:m,dataReportOperation:t.dataReportOperation})}catch(U){throw new k("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:U,url:I}})}const C=(t=>{const s=t.entities?.[0],n="number"==typeof s?.file_upper_limit?s.file_upper_limit:0,r="number"==typeof s?.part_lower_limit?s.part_lower_limit:G,i="string"==typeof s?.uuid?s.uuid:"";if(!i)throw new k("Multipart init failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{fileMaxSize:n,partMinSize:r,uuid:i}})(v);if(C.fileMaxSize&&c>C.fileMaxSize)throw new k("File size exceeds limit",{code:e.UPLOAD_SIZE_EXCEEDED,details:{fileSize:c,maxSize:C.fileMaxSize}});const S=C.partMinSize||G,E=Math.ceil(c/S),b=Array.from({length:E},()=>0),T=`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload/${C.uuid}`,A=[],w=(e,s)=>{b[e]=s;const n=b.reduce((e,t)=>e+t,0),r=c?n/c*100:void 0;t.callbacks?.onFileUploadProgress?.({loaded:n,total:c,percent:r})};for(let e=0;e<E;e+=1){const r=e*S,i=Math.min(c,r+S),d=n.slice(r,i),l=String(e+1),u=Mc({url:T,token:s.token,partNumber:l,part:d,fileName:o,fileType:a,uploadAdapter:f,onProgress:t=>w(e,t),dataReportOperation:t.dataReportOperation}).finally(()=>{const e=A.indexOf(u);e>=0&&A.splice(e,1)});A.push(u),A.length>=x&&await Promise.race(A)}await Promise.all(A);const M=V(i),R=F(`${s.restBaseUrl}/${g}/${y}/sdk/chatfiles/part-upload/${C.uuid}`,{"restrict-access":"true","chat-type":M,"chat-target":r,"thumbnail-width":t.thumbnailWidth,"thumbnail-height":t.thumbnailHeight,md5:u??"",..."image"===d?{imageType:B(l),width:h,height:p}:{}}),_=await Nc({url:R,method:"POST",token:s.token,operation:"upload.multipart.complete",requestAdapter:m,dataReportOperation:t.dataReportOperation}),D=q({response:_,restBaseUrl:s.restBaseUrl,orgName:g,appName:y,fileType:a,fileName:o,fallbackSize:c,messageType:d,imageType:l,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(D),D},_c=async t=>{const{config:s,file:n,conversationId:r,conversationType:i,messageType:o,imageType:c,md5:l,width:u,height:h,fileName:p,fileType:m,fileSize:f}=t,g=(t=>{if(t)return t;const s=Ar();if(s)return s;throw new k("Upload adapter is required for simple upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:y,appName:I}=P(s.appKey),v=V(i),C=F(`${s.restBaseUrl}/${y}/${I}/chatfiles`,{"chat-type":v,"chat-target":r,md5:l??"",..."image"===o?{imageType:B(c),width:u,height:h}:{}}),S=Date.now(),E=t.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:C});a.debug("Upload request start",{operation:"upload.simple",method:"POST",fileSize:f,messageType:o});const b={};let T;void 0!==t.thumbnailWidth&&(b["thumbnail-width"]=String(t.thumbnailWidth)),void 0!==t.thumbnailHeight&&(b["thumbnail-height"]=String(t.thumbnailHeight));try{T=await g.upload({url:C,method:"POST",headers:{"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${s.token}`,[_]:d()},source:{sourceType:"web-file",file:n,name:p,mimeType:m,size:f},fields:b,fileFieldName:"file",timeoutMs:K,onProgress:e=>t.callbacks?.onFileUploadProgress?.(e)})}catch(A){const s=It(A),n=s.details&&"object"==typeof s.details?s.details:void 0,r=new k(s.message,{code:s.code,details:{...n,url:C,...s.code===e.UPLOAD_TIMEOUT?{timeout:K}:{}}});throw E?.finish({code:r.code,success:!1,description:r.message}),r.code===e.UPLOAD_ABORTED?(a.warn("Upload request aborted",{operation:"upload.simple"}),t.callbacks?.onFileUploadCanceled?.()):r.code===e.UPLOAD_TIMEOUT?a.warn("Upload request timeout",{operation:"upload.simple",timeout:K}):a.warn("Upload request failed",{operation:"upload.simple"}),r}try{const n=JSON.parse(T.body),r=Date.now()-S;if(T.status>=400)throw a.warn("Upload response error",{operation:"upload.simple",status:T.status,duration:r}),new k("Upload failed",{code:e.UPLOAD_REQUEST_FAILED,details:{status:T.status,response:n}});a.debug("Upload response success",{operation:"upload.simple",status:T.status,duration:r});const i=q({response:n,restBaseUrl:s.restBaseUrl,orgName:y,appName:I,fileType:m,fileName:p,fallbackSize:f,messageType:o,imageType:c,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(i),E?.finish({code:T.status||200,success:!0}),i}catch(A){throw E?.finish({code:A instanceof k?A.code:e.UPLOAD_REQUEST_FAILED,success:!1,description:A instanceof Error?A.message:String(A)}),A instanceof Error?A:new Error(String(A))}},Dc=qr(),Uc=e=>Object.prototype.toString.call(e),Lc=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}},Oc=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}),kc=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Pc=e=>"object"==typeof e&&null!==e,xc=(e,t)=>{const s=Pc(t)?t:void 0,n=s?.code===r.MISSING_CAPABILITY&&s.stage===i.RUNTIME;return"miniapp-path"===e&&(e=>{if(!Pc(e))return!1;const t=Pc(e.details)?e.details:void 0;return e.code===r.MISSING_CAPABILITY&&e.stage===i.RUNTIME&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&n};class Fc{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(t,s){if(!kc(t.type))return t;const n=t.body;if(this.hasUploadedRemoteResource(t.type,n))return t;const r=this.resolveUploadUrl(t.type,n),i=$e.get(t.msgLocalId),o=Boolean(i);if(a.warn("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:t.msgLocalId,messageType:t.type,conversationType:t.conversationType,hasFile:o,uploadUrl:r,cachedFile:Lc(i),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!H(r,o))return t;if(!i)throw new k("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:t.msgLocalId,url:r}});if(!this.config?.restBaseUrl)throw new k("REST base url is required for upload",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let c,d,l;try{c=await this.prepareAttachmentUpload(t,n,i),c.precheck?.hit||(l=E({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:t.msgLocalId,messageType:t.type})),d=c.precheck?.hit?this.buildPrecheckedUploadResult(t,c,s):await this.uploadAttachment(t,c,s,l),l?.finish({code:0,success:!0})}catch(u){const t=It(u);throw l?.finish({code:t.code,success:!1,description:t.message}),t.code===e.UPLOAD_ABORTED&&s?.onFileUploadCanceled?.(),s?.onFileUploadError?.(t),t}return this.buildPreparedMessage(t,c,d)}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&z(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&z(t.url)}async prepareAttachmentUpload(e,t,s){const n=j(s,t);if(a.warn("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Oc(n)}),"image"!==e.type){return{body:t,fileInfo:n,md5FileInfo:n,precheck:await this.maybePrecheck(e,n,n,void 0)}}const r=t,i=await this.resolveImageCandidate(r,n),o={...r,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===h},c=await this.maybePrecheck(e,i.fileInfo,n,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:n,imageType:i.imagePolicy.resolvedImageType,precheck:c,originalWidth:r.width,originalHeight:r.height}}async resolveImageCandidate(e,t){const s=W(e);if(a.warn("Image send policy resolved",{operation:"upload.image.policy",reason:s.reason,imageType:s.resolvedImageType,isGif:e.isGif,source:Oc(t)}),s.resolvedImageType===h){let n=e.width,r=e.height;if(!n||!r){const e=this.resolveImageProcessor(t.source.sourceType);a.warn("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Oc(t)});const s=await e.getImageInfo(t.source);n=s.width,r=s.height}return{imagePolicy:s,sourceKind:"origin",fileInfo:t,width:n,height:r}}try{const e=this.resolveImageProcessor(t.source.sourceType);a.warn("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Oc(t)});const n=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:s,sourceKind:"big",fileInfo:{source:n.source,fileName:n.fileName??t.fileName,fileType:n.fileType??t.fileType,fileSize:n.fileSize??t.fileSize,webFile:n.webFile},width:n.width,height:n.height}}catch(n){return a.warn("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:s.reason,error:n instanceof Error?n.message:String(n),source:Oc(t)}),{imagePolicy:{resolvedImageType:h,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,s,n){if(!kc(e.type))return;if(!0!==this.config?.enableMd5Check)return void a.debug("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:n,fileSize:t.fileSize});const r=$({messageType:e.type,fileSize:t.fileSize,imageType:n});if(!r.shouldPrecheck)return void a.debug("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:n,fileSize:t.fileSize,thresholdBytes:r.thresholdBytes});let i;try{i=await this.computeMd5(s)}catch(c){if(xc(s.source.sourceType,c))return void a.warn("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:n,thresholdType:r.thresholdType,source:Oc(s),error:c instanceof Error?c.message:String(c)});throw c}const o=await this.requestPrecheck(e,r.thresholdType,i,n);return a.debug(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:n,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return a.warn("Attachment md5 compute start",{operation:"upload.md5.start",source:Oc(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return a.warn("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return a.warn("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Dc;throw a.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),n("Image processor capability is missing for current platform",{code:r.MISSING_CAPABILITY,stage:i.RUNTIME,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(t,s,n,r){if(!this.config)throw new k("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:o}=P(this.config.appKey),c=F(`${this.config.restBaseUrl}/${i}/${o}/chatfiles/exists`,{md5:n,..."image"===t.type?{imageType:B(r)}:{}}),d=await this.requestJson({url:c,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(e=>{a.warn("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:t.type,imageType:r,thresholdType:s,md5:n,error:e instanceof Error?e.message:String(e)})});return d?Q(d):{exists:!1,hit:!1}}async requestJson(e){return this.requestByAdapter(N(this.config?.requestAdapter),e)}async requestByAdapter(t,s){const n=await t.request({url:s.url,method:s.method,headers:s.headers,responseType:"json",timeoutMs:K});if(n.status>=400)throw new k("Upload precheck request failed",{code:e.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:n.status,operation:s.operation}});return"string"==typeof n.data?JSON.parse(n.data):n.data}buildPrecheckedUploadResult(t,s,n){if(!this.config||!s.precheck)throw new k("Precheck result is required",{code:e.UPLOAD_REQUEST_FAILED});if(!s.precheck.uuid)throw new k("Precheck hit missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{precheck:s.precheck}});if(!kc(t.type))throw new k("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const{orgName:r,appName:i}=P(this.config.appKey),o="image"===t.type?s.precheck.existsType??s.imageType:void 0,a="image"===t.type&&o===h?s.md5FileInfo:s.fileInfo,c="image"===t.type&&o===h?s.originalWidth:"image"===t.type?s.body.width:void 0,d="image"===t.type&&o===h?s.originalHeight:"image"===t.type?s.body.height:void 0,l={entities:[{uuid:s.precheck.uuid,...s.precheck.shareSecret?{"share-secret":s.precheck.shareSecret}:{}}]},u=q({response:l,restBaseUrl:this.config.restBaseUrl,orgName:r,appName:i,fileType:a.fileType,fileName:a.fileName,fallbackSize:a.fileSize,messageType:t.type,imageType:o,width:c,height:d,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(u),u}async uploadAttachment(t,s,n,r){if(!this.config)throw new k("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});if(!kc(t.type))throw new k("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const i=t.type,o=await this.resolveUploadMetadata(i,s);if(!s.fileInfo.webFile){if(this.config.uploadAdapter)return this.uploadByAdapter(this.config.uploadAdapter,t,s,o,n);throw new k("Upload adapter is required for non-web file source",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:s.fileInfo.source.sourceType}})}const c={message:t,file:s.fileInfo.webFile,conversationId:t.conversationId,conversationType:t.conversationType,messageType:i,imageType:s.imageType,md5:o.md5,width:o.width,height:o.height,fileName:s.fileInfo.fileName,fileType:s.fileInfo.fileType,fileSize:s.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(i,s.body),thumbnailHeight:this.resolveThumbnailHeight(i,s.body),callbacks:n,config:this.config,dataReportOperation:r},d=!1!==this.config?.enableMultipartUpload,l=d&&s.fileInfo.fileSize>O;if(a.warn("Attachment web upload selected",{operation:"upload.web.selected",messageType:i,source:Oc(s.fileInfo),multipartEnabled:d,uploadMode:l?"multipart":"simple"}),l)try{return await Rc(c)}catch(u){const e=u instanceof k?u.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return _c(c);throw u}return this.config.uploadAdapter?(a.warn("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:i,source:Oc(s.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,t,s,o,n)):_c(c)}async uploadByAdapter(t,s,n,r,i){if(!this.config)throw new k("Upload config is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:o,appName:c}=P(this.config.appKey),l=V(s.conversationType);if(!kc(s.type))throw new k("Attachment message type is invalid",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:s.type}});const u=s.type,h=F(`${this.config.restBaseUrl}/${o}/${c}/chatfiles`,{"chat-type":l,"chat-target":s.conversationId,md5:r.md5,..."image"===u?{imageType:B(n.imageType),width:r.width,height:r.height}:{}}),p={},m={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[_]:d()},f=this.resolveThumbnailWidth(u,n.body),g=this.resolveThumbnailHeight(u,n.body);void 0!==f&&(p["thumbnail-width"]=String(f)),void 0!==g&&(p["thumbnail-height"]=String(g)),a.warn("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:u,source:Oc(n.fileInfo),uploadUrl:h,fields:p});const y=await t.upload({url:h,headers:m,source:n.fileInfo.source,fields:p,onProgress:e=>{i?.onFileUploadProgress?.(e)}});if(y.status>=400){const t=y.body??"",s=413===y.status?e.FILE_TOO_LARGE:"string"==typeof t&&t.includes("content improper")?e.FILE_CONTENT_IMPROPER:e.UPLOAD_REQUEST_FAILED;throw new k("Upload failed",{code:s,details:{status:y.status,response:y.body}})}let I;try{I=JSON.parse(y.body)}catch(C){throw new k("Upload response parse failed",{code:e.UPLOAD_REQUEST_FAILED,details:{response:y.body,cause:C instanceof Error?C.message:String(C)}})}const v=q({response:I,restBaseUrl:this.config.restBaseUrl,orgName:o,appName:c,fileType:n.fileInfo.fileType,fileName:n.fileInfo.fileName,fallbackSize:n.fileInfo.fileSize,messageType:u,imageType:n.imageType,width:r.width,height:r.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return i?.onFileUploadComplete?.(v),v}buildPreparedMessage(e,t,s){if("image"===e.type){const n=t.body,r={...e,body:{...n,isOriginalImage:s.isOriginalImage??n.isOriginalImage,originalImageUrl:s.originalImageUrl??n.originalImageUrl,bigImageUrl:s.bigImageUrl??n.bigImageUrl,secret:s.secret??n.secret,fileLength:s.fileLength??n.fileLength??t.fileInfo.fileSize,filetype:s.filetype??n.filetype,filename:s.filename??n.filename,thumbnailUrl:s.thumbnailUrl??n.thumbnailUrl,width:s.width??n.width,height:s.height??n.height}};return Do(e,r),Qe(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 Do(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 Do(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 Do(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 Do(e,r),r}resolveThumbnailWidth(e,t){if("video"===e){const e="width"in t?t.width:void 0;return"number"==typeof e&&e>0?e:void 0}}resolveThumbnailHeight(e,t){if("video"===e){const e="height"in t?t.height:void 0;return"number"==typeof e&&e>0?e:void 0}}async resolveUploadMetadata(e,t){let s=t.precheck?.md5??"";if(!t.precheck)try{s=await this.computeMd5(t.md5FileInfo)}catch(r){if(!xc(t.md5FileInfo.source.sourceType,r))throw r;a.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Oc(t.md5FileInfo),error:r instanceof Error?r.message:String(r)})}const n=t.body;return{md5:s,width:"image"===e&&"number"==typeof n.width&&n.width>0?n.width:void 0,height:"image"===e&&"number"==typeof n.height&&n.height>0?n.height:void 0}}}class Bc{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 qc="__internal:core";class Kc{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 ec({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),n=e.restBaseUrl?new Fc({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 fc(s,null,this.eventHub,n),this.messageReceiver=new Cc(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Ec(e.platformAdapter?.request),this.attachmentDownloader=new Ac(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(qc,{[qe.CONNECTED]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[qe.DISCONNECTED]:e=>{this.messageSender.setWebSocket(null)},[qe.RECONNECT_FAILED]:e=>{this.messageSender.setWebSocket(null)},[Ge.MESSAGE_SENT]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new Bc(e,{onOnline:this.handleOnline,onOffline:this.handleOffline,onForeground:()=>{this.handleForegroundChange(!0)},onBackground:()=>{this.handleForegroundChange(!1)}}),this.runtimeEventBridge.start()}unregisterNetworkListeners(){this.runtimeEventBridge?.stop(),this.runtimeEventBridge=null}resolveRuntimeAdapter(){return this.platformAdapter?this.platformAdapter.runtime:this.createBrowserRuntimeAdapter()}createBrowserRuntimeAdapter(){return{getPlatform:()=>"web",onNetworkChange(e){if("undefined"==typeof window)return()=>{};const t=()=>{e(!0)},s=()=>{e(!1)};return window.addEventListener("online",t),window.addEventListener("offline",s),"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine&&e(navigator.onLine),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}},onAppVisibilityChange(e){if("undefined"==typeof document)return()=>{};const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),t(),()=>{document.removeEventListener("visibilitychange",t)}}}}async connect(e){return this.connectionManager.connect(e)}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}recoverConnectionForSend(){return this.connectionManager.recoverConnectionForSend()}getClientResource(){return this.connectionManager.getClientResource()}renewToken(e,t){const s=this.connectionManager.renewToken(e,t);return this.messageSender.updateAuthToken(e),s}async sendMessage(e,t){return this.messageSender.sendMessage(e,t)}async sendMessageAction(e,t){return this.messageSender.sendAction(e,t)}async sendChatRoomOperation(e,t){return this.messageSender.sendChatRoomOperation(e,t)}async downloadAndParseCombineMessage(e){return this.combineMessageDownloader.downloadAndParse(e)}async downloadAttachment(e,t){return this.attachmentDownloader.download(e,t)}decodeServerMessageMeta(e){return this.connectionManager.getMsyncCodec().decodeServerMessageMeta(e)}destroy(){this.unregisterNetworkListeners(),this.connectionManager.destroy(),this.messageSender.destroy(),this.messageReceiver.destroy(),this.eventHub.removeEventHandler(qc),$e.clear()}}const Gc=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)},Vc=e=>{const t=new Uint8Array(ot.util.base64.length(e));return ot.util.base64.decode(e,t,0),t};class Hc{getCrypto(){return t().crypto}constructor(e,n){if(this.enabled=(()=>{const e=t();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const n=$n(e);if("web"!==n.framework&&"worker"!==n.framework&&n.platform!==s.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const t=`${e}:${n}`;this.keyPromise=this.deriveKey(t)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,s=new TextEncoder,n=this.getCrypto().getRandomValues(new Uint8Array(12)),r=s.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:n},t,r),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:Gc(n),ct:Gc(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=Vc(t.iv),n=Vc(t.ct),r=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:s},e,n);return(new TextDecoder).decode(r)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),s=this.getCrypto(),n=await s.subtle.digest("SHA-256",t);return s.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const zc="conversationMap",jc="userInfoMap",Wc="groupNamecardMap",$c="contactRelationMap",Qc="contactVersion",Yc="contactMeta",Jc="sessionListMap",Xc="sessionListCheckpoint",Zc="joinedGroupPreview",ed="metadata",td=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class sd{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 nd=()=>{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 rd{constructor(e,t){this.storage=t??rd.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!rd.checkAvailable())return null;const e=nd();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=nd();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 St(n,t)}catch(s){return a.warn("CacheStore read failed",s),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,s){if(!this.storage)return;const n=Et(t);if(null!==n)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(n):n;await this.storage.setItem(e,t)}catch(r){if(Xr(r))throw r;if(s)throw r;a.warn("CacheStore write failed",r)}else if(s)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){a.warn("CacheStore remove failed",t)}}}const id={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},od={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class ad{constructor(){this.items=/* @__PURE__ */new Map,this.versionState=id,this.meta=od}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(!bt(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 bt(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"}:id}normalizeMeta(e){return bt(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"}:od}}const cd=(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}},dd=(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}},ld=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 ud{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=cd(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=dd(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:ld(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(!bt(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=bt(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 hd=(e,t)=>`${e}:${t}`;class pd{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(hd(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,n){const r=hd(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(hd(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=hd(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(hd(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=cd(r,e,t),o=new Set(i.removed.map(e=>hd(e.groupId,e.userId)));this.items.clear();for(const a of n)o.has(hd(a.groupId,a.userId))||this.items.set(hd(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=dd(n,Math.min(e,n.length)),i=new Set(r.removed.map(e=>hd(e.groupId,e.userId)));this.items.clear();for(const o of s)i.has(hd(o.groupId,o.userId))||this.items.set(hd(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||!bt(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 md=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,fd=e=>{const t={...e};return delete t.type,t},gd=e=>{if(!bt(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!bt(e.body))return null;const s=((e,t)=>{if(bt(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=md(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(bt(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:fd(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}:{}}},yd=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},Id=(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 vd{constructor(){this.items=[]}load(e,t){const s=[];for(const n of e){const e=this.normalizeItem(n,t);e&&s.push(e)}this.items=s.sort(Id)}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(Id)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!bt(e))return null;const s=e,n="string"==typeof s.conversationId?s.conversationId:"";if(!n)return null;const r=md(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:gd(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:yd(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 Cd{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=cd(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=dd(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(!bt(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 Sd=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Ed=e=>e.lastMessageAt??e.updatedAt,bd=e=>[...e].sort((e,t)=>{const s=Sd(t)-Sd(e);if(0!==s)return s;const n=Ed(t)-Ed(e);return 0!==n?n:e.conversationId.localeCompare(t.conversationId)}),Td=e=>`${e.conversationType}:${e.conversationId}`,Ad=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,wd=(e,t)=>((e,t)=>Ed(t)>Ed(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Ad(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,Nd=e=>{const t=/* @__PURE__ */new Map,s=/* @__PURE__ */new Set;for(const i of e.snapshot)s.add(Td(i));for(const i of e.existing)t.set(Td(i),i);const n=e.snapshot.map(e=>{const s=t.get(Td(e));return s?wd(e,s):e}),r=e.existing.filter(t=>!s.has(Td(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return bd([...n,...r])},Md=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Rd=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),_d=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 Dd{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,Md.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 Ld{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 rd(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=td(s,zc),this.userInfoKey=td(s,jc),this.groupNamecardKey=td(s,Wc),this.sessionListKey=td(s,Jc),this.sessionListCheckpointKey=td(s,Xc),this.joinedGroupPreviewKey=td(s,Zc),this.contactRelationKey=td(s,$c),this.contactVersionKey=td(s,Qc),this.contactMetaKey=td(s,Yc),this.metadataKey=td(s,ed),this.metadataStore=new sd(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new ud,this.userInfoCache=new Cd,this.groupNamecardCache=new pd,this.sessionListCache=new vd,this.joinedGroupPreviewCache=new mt,this.contactCache=new ad,this.userInfoRuntimeStore=new Dd,this.loadPromise=this.loadFromStorage()}getConfig(){return this.config}async prepare(){await this.loadPromise}loadConversationSummaries(){return this.conversationCache.getAll()}loadSessionList(){return this.sessionListCache.exportItems()}loadJoinedGroupPreviewSnapshot(){return this.joinedGroupPreviewCache.getSnapshot()}applyJoinedGroupPreviewSnapshot(e){this.joinedGroupPreviewCache.setSnapshot(e),this.scheduleFlush(["joinedGroupPreview"])}async commitJoinedGroupPreviewSnapshot(e){this.activeFlushPromise&&await this.activeFlushPromise;const t=this.getDomainRevision("joinedGroupPreview"),s=new mt;if(s.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,s.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const n=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==n&&n<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),s=t.items.filter(t=>t.groupId!==e);return s.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:s,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let s=!1,n=!1;const r=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:(s=!0,0===r.unreadCount?r:(n=!0,{...r,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(n=>n.conversationId!==e.conversationId||n.conversationType!==e.type?n:(s=!0,0===n.unreadCount&&n.readAt===t?n:(i=!0,{...n,unreadCount:0,readAt:t,updatedAt:t})));return n||i?(n&&this.conversationCache.setAll(r),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:s}):{items:this.sessionListCache.exportItems(),changed:!1,matched:s}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),s=this.conversationCache.getAll(),n=s.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),r=this.sessionListCache.getAll(),i=r.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(s,n),a=!this.isSessionListEqual(r,i);return o||a?(o&&this.conversationCache.setAll(n),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),s=this.conversationCache.getAll(),n=this.conversationCache.getAll().map(s=>s.conversationId!==e.conversationId||s.type!==e.type?s:{...s,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),r=this.sessionListCache.getAll(),i=r.map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:{...s,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(s,n),a=!this.isSessionListEqual(r,i);return o||a?(o&&this.conversationCache.setAll(n),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),s=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,s,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),s=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(s,e.deletedAt))}const n=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),r=s.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=n.length!==t.length,o=r.length!==s.length;return i||o?(i&&this.conversationCache.setAll(n),o&&this.sessionListCache.setAll(r),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),r=this.conversationCache.getAll(),i=r.map(e=>{const r=`${e.type}:${e.conversationId}`;if(!t.has(r))return e;const i=n(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:s}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const r=`${e.conversationType}:${e.conversationId}`;if(!t.has(r))return e;const i=n(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:s}}),c=!this.isConversationListEqual(r,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,s){const n=Date.now(),r=e.map(e=>({...e,updatedAt:e.lastMessageAt??n})),i=Nd({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?Rd(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([_d(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=Td(e.nextRecord),s=e.existing.filter(e=>Td(e)!==t);return bd([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&&bt(r)&&Array.isArray(r.items)?r.items:[];this.sessionListCache.load(i,e);const o=(r&&bt(r)&&bt(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&&bt(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&bt(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=/* @__PURE__ */new Map,e}restoreDirtyBatch(e){for(const[t,s]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(s,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(/* @__PURE__ */new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const n=6;for(let r=0;r<=n;r+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!Xr(t))return this.restoreDirtyBatch(e),void a.warn("Cache flush failed",t);const n=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,n),"none"===n)return void a.warn("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(n)}catch(s){if(!Xr(s))return this.restoreDirtyBatch(e),void a.warn("Cache quota cleanup persistence failed",s)}}a.warn("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of 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=>Sd(e)>0),s=/* @__PURE__ */new Map;for(const r of e.incoming)s.set(Td(r),r);const n=t.length>0?e.existing.filter(e=>!s.has(Td(e))&&0===Sd(e)):e.existing.filter(e=>!s.has(Td(e)));return bd([...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(Nd({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=_o(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?Rd(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 Od{constructor(){this.handlers=/* @__PURE__ */new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const s=[],n=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?s.push(i):n.push(i)}const r=this.dispatchToHandlers(e,t,s);r?r.then(()=>{this.dispatchToHandlers(e,t,n)}):this.dispatchToHandlers(e,t,n)}dispatchToHandlers(e,t,s){let n=null;for(const[,r]of s){const s=r[e];s&&(n=n?n.then(async()=>{await this.invokeHandler(e,t,s)}):this.invokeHandler(e,t,s))}return n}invokeHandler(e,t,s){try{const n=s(t);return this.isPromiseLike(n)?Promise.resolve(n).then(()=>{}).catch(t=>{this.reportHandlerError(e,t)}):null}catch(n){return this.reportHandlerError(e,n),null}}reportHandlerError(e,t){e!==ut.LOG&&a.error(`Event handler error for ${e}`,t)}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const kd={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Pd(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 xd(e){return new Promise(t=>setTimeout(t,e))}const Fd=e=>{const t={...e};return delete t.type,t},Bd=(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:Fd(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},qd=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},Ad=async(e,t)=>{const s=await bd(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:Ed(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 Td{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 wd=0,Nd=5,Md=10,Rd=11,_d=1,Ud=2,Dd=1,Od=2,Ld=3,kd=e=>e===_d?"groupChat":e===Ud?"chatRoom":"singleChat",Pd=()=>Pi().lookupType("easemob.pb.MessageBody"),xd=e=>{const t=Pd().toObject(Pd().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:""}:{}},Fd=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}},Bd=e=>{const t={...e};return delete t.type,t},qd=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,Kd=(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:qd({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:Bd(t)};var i},Gd=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},Vd=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return xd(e)}catch{return{}}})(e.last_message?.payload),n=e.session_id??"",r=kd(e.session_type),i=(e=>{const t=e.session_id??"",s=kd(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Fd(e)})(e);return{conversationId:n,conversationType:r,unreadCount:e.unread_count??0,lastMessage:Kd(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:Gd(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===Dd?"ALL":o===Od?"AT":o===Ld?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),Hd={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 zd=null,jd=!1;const Wd=()=>zd||(jd||(Je.util.Long=Qe,Je.configure(),jd=!0),We(),zd=Je.Root.fromJSON(Hd),Ye(zd),zd),Qd=e=>Wd().lookupType(e),$d=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}},Yd=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:$d(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:$d(t.protocol_version)??$d(t.protocolVersion)??0}},Jd=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!==$d(t.id)?String($d(t.id)):void 0,from:Jd(t.from),timestamp:$d(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 Zd{constructor(){this.requestType=Qd("easemob.sessionlist.GetSessionListRequest"),this.responseType=Qd("easemob.sessionlist.GetSessionListResponse"),this.errorType=Qd("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:wd}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=$d(t.type);return s!==Md?null:{type:s,header:Yd(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:$d(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=$d(t.type);return s!==Rd?null:{type:s,header:Yd(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:$d(t.session_type),last_message:Xd(t.last_message),updated_at:$d(t.updated_at),pinned_time:$d(t.pinned_time),unread_count:$d(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:$d(t.read_receipt),remind_type:$d(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:$d(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=$d(t.type);return s!==Nd?null:{type:s,header:Yd(t.header),code:$d(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const el=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 Zd;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=Vd(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}}}})},tl=()=>Date.now(),sl={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},nl=(e,t)=>({status:e,determinedAt:tl(),reason:t}),rl=t=>t instanceof w&&(t.code===e.SERVER_BUSY||1103===t.code),il=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:rl(e)});class ol{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 Td,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={...Id,...s};let r;for(let o=1;o<=n.maxAttempts;o++)try{return await e()}catch(i){if(r=i,!t(i))throw i;if(o>=n.maxAttempts)throw i;const e=vd(o,n);await Cd(e)}throw r}(async()=>{r+=1;const e=1===r?t:this.createRetrySession();e.start();try{return await el({client:this.client,session:e,params:s})}catch(n){throw e.fail(),n}},rl,sl),a={result:o,syncStartedAt:t.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:tl()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:tl()};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:il(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:nl("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:il(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=nl("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new Td}async buildFallbackSessionList(e){return await(async(e,t)=>await Ad(e,t))(e.loadConversationSummaries(),this.client)}}const al=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),cl=async t=>{if("string"==typeof t||al(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):al(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}})},dl=e=>{const t=Math.max(e-1,0),s=Y*Math.pow(J,t);return Math.min(s,$)},ll=async e=>{await new Promise(t=>{setTimeout(t,e)})},ul=e=>e instanceof Error?e:new Error(String(e));class hl{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,ul(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=ul(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=dl(this.attempt);s.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:e,reason:t.message})),await ll(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 cl(e);if(!(await this.routeFrame(t)))return}catch(t){const e=ul(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(ul(i)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||r||(r={pending:e,frame:s.frame})}catch(i){n.push(ul(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(ul(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 pl=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}})}},ml=e=>ht.string().regex(/^https?:\/\/\S+$/i,e),fl=e=>ht.string().regex(/^wss?:\/\/\S+$/i,e),gl=ht.object({appKey:ht.string().min(1,"appKey is required").optional(),appId:ht.string().min(1,"appId is required").optional(),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(ml("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:ht.object({restApiUrl:ml("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:fl("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:ml("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:fl("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)=>{const s=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===s?t.addIssue({code:ht.ZodIssueCode.custom,path:["appKey"],message:"appKey or appId is required"}):s>1&&t.addIssue({code:ht.ZodIssueCode.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"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 n=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,r=n?.serverUrls&&"object"==typeof n.serverUrls?n.serverUrls:void 0;n?.dnsConfigUrls&&r&&t.addIssue({code:ht.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),r&&(void 0!==e.appId&&t.addIssue({code:ht.ZodIssueCode.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),r?.restApiUrl||t.addIssue({code:ht.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),r?.wsUrl||t.addIssue({code:ht.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),yl=ht.object({userId:ht.string().min(1,"userId is required"),token:ht.string().min(1,"token is required")}),Il=ht.string().trim().min(1,"token is required"),vl=ht.object({channelName:ht.string().trim().min(1,"channelName is required").optional()}).optional(),Cl=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))),Sl=ht.object({protocol:ht.string(),domain:ht.string().optional(),ip:ht.string().optional(),port:ht.union([ht.string(),ht.number()]).optional()}).passthrough(),El=ht.object({app_key:ht.string().optional(),rest:ht.object({hosts:ht.array(Sl).nonempty()}),"msync-wx":ht.object({hosts:ht.array(Sl).nonempty()}),"sync-ws":ht.object({hosts:ht.array(Sl).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(),bl="5.1.0",Al=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Tl=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],wl=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function Nl(e){return"object"==typeof e&&null!==e}function Ml(e){return Array.isArray(e)?{hosts:e}:function(e){return Nl(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Rl(e,t,s){for(const n of t){const t=Ml(e[n]);if(t)return{key:n,section:t}}for(const[n,r]of Object.entries(e)){if(!s(n))continue;const e=Ml(r);if(e)return{key:n,section:e}}}function _l(e){if(!Nl(e))return Fe.validateOrThrow(El,e);const t=Ml(e.rest),n=Rl(e,Tl,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),r=Rl(e,wl,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&&!Ml(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(El,i)}function Ul(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 Dl(e,t){return"https"===e?"https":"http"===e?"http":t}function Ol(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 Ll(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function kl(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 Pl(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}?${(void 0!==t.appId?pt({app_id:t.appId,sdk_version:bl,file_version:"1"}):pt({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return _l(await n.get(r))}function xl(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,Dl(t.protocol,s))).filter(e=>"string"==typeof e&&e.length>0):[]}async function Fl(t){const n=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:Al;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=void 0!==t.appId?{appId:t.appId}:{appKey:t.appKey},n=await Pl(c,s,t.requestAdapter),i=void 0!==t.appId?n.app_key:t.appKey;if("string"!=typeof i||0===i.length)throw new S("DNS app_key is required for appId initialization",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const o=kl(Ll(n["msync-wx"].hosts,r));if(0===o.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 a=o[0];if(!a)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 d=Ll(n.rest.hosts,r);if(0===d.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 l=d[0];if(!l)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 u=o.map(e=>Ul(e,Dl(e.protocol,r))),h=Ul(a,Dl(a.protocol,r)),p=xl(n,r);return{appKey:i,websocketUrl:h,websocketUrls:u,syncWebsocketUrls:p,baseUrl:c,restBaseUrl:Ol(l,Dl(l.protocol,r)),dnsConfig:n}}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 Bl=t=>new S(t,{code:e.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),ql=e=>{if(!ut(e))throw Bl("Invalid REST response");return ut(e.data)?e.data:e},Kl=(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}}},Gl=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},Vl=e=>{const{orgName:t,appName:s}=R(e.appKey);return`/${t}/${s}`},Hl=async(e,t)=>{const s=await e.get((e=>`${Vl(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=ql(e),s=Kl(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw Bl("Invalid token expires response");return s})(s)},zl=async(e,t,s)=>{const n=await e.get(((e,t)=>{const s=pt({channelName:t?.channelName??"*"});return`${Vl(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${s.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=ql(e);return{appId:Gl(t,["app_id","appId"])??"",rtcToken:Gl(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Gl(t,["channel_name","channelName"])??"",rtcUid:Kl(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:Kl(t,["expires_in","expire","expireAt"])??0}})(n)},jl=async(e,t,s)=>{const n=await e.post((e=>`${Vl(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=ql(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)},Wl=async(e,t)=>{const s=await e.get((e=>`${Vl(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=Gl(r,["res","resource","clientResource"]);e&&e!==t.clientResource&&n.push(`${t.userId}/${e}`)}return n})(s,t)};class Ql{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 $l{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 Yl=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.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=/* @__PURE__ */new Set,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=Ri(this.config.platformAdapterOptions)),this.managerRegistry=/* @__PURE__ */new Map,this.managerCapabilities=/* @__PURE__ */new Map,this.eventHub=new yd,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 $l({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:te,maxRetries:ee,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Ql({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(gl,s),r=n.customOSPlatform,i=t.normalizeServiceConfig(n.serviceConfig),o={appKey:n.appKey,appId:n.appId,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:t.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==r?n.customDeviceName:void 0,customOSPlatform:r,uiKitVersion:n.uiKitVersion,loginExtensionInfo:n.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs: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(yl,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;let o=this.config.appKey??null;this.activeAppKey=o,s.warn("Login started",{userId:r.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const a=this.platformAdapter??Ri(this.config.platformAdapterOptions);this.platformAdapter=a,ce({requestAdapter:a.request,onDiagnostic:(e,t)=>{s.warn(e,t)}});const c=de({appKey:o??"default#appkey",uid:r.userId,sdkVersion:bl,platform:a.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),d=a.runtime.getNetworkType?.();d&&d.then(e=>{Ie(e)}).catch(()=>{Ie("unknown")});const l=g({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:r.userId});let u,h,p;this.updateState(Ae.CONNECTING),this.logReportEnabled=!1,le("unknown");let f,y=!1,I=!1,v=!0;if("dns"===this.config.serviceConfig.mode){const e=l?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await Fl(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:a.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:a.request});o=t.appKey,this.activeAppKey=o,ue({appKey:o}),s.warn("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),u=t.websocketUrl,h=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,p=t.restBaseUrl,y="true"===t.dnsConfig.enableReportLogs,f=t.dnsConfig.reportInterval,I="true"===t.dnsConfig.enableMd5Check,v="false"!==t.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),he(t.dnsConfig.enableDataReport),s.debug("DNS report switch resolved",{enabled:y})}catch(E){const t=E instanceof w?E.code:-1,s=E instanceof Error?E.message:String(E);throw e?.finish({code:t,success:!1,description:s}),l?.finish({code:t,success:!1,description:s}),he(void 0),le("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(Ae.DISCONNECTED),E}}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 l?.finish({code:t.code,success:!1,description:t.message}),he(void 0),this.updateState(Ae.DISCONNECTED),t}u=t.wsUrl,p=t.restApiUrl,I=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=t.syncWsUrl?[t.syncWsUrl]:[],this.contactSyncDnsResolved=!1,he(void 0)}if(!o){const t=new S("appKey is unavailable after service discovery",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(Ae.DISCONNECTED),fe(),t}if(pe({restBaseUrl:p,appKey:o,userId:r.userId,token:r.token,requestAdapter:a.request}),me(f),this.logReportEnabled=y,le(y?"enabled":"disabled"),this.resetCore(),i!==this.loginAttempt){const t=new m("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}});throw l?.finish({code:e.CONNECTION_CANCELLED,success:!1,description:t.message}),this.updateState(Ae.DISCONNECTED),this.activeAppKey=this.config.appKey??null,fe(),t}this.core=new Ac({serverUrl:u,serverUrls:h,userId:r.userId,token:r.token,appKey:o,restBaseUrl:p,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:I,enableMultipartUpload:v,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:c,platformAdapter:a,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),pe({resource:this.core.getClientResource()});const C=l?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:u});try{if(s.warn("Connecting core websocket",{serverUrl:u,restBaseUrl:p,userId:r.userId}),await this.core.connect(),C?.finish({code:200,success:!0}),l?.finish({code:0,success:!0}),s.warn("Core websocket connected",{userId:r.userId,resource:this.core.getClientResource()}),this.currentUserId=r.userId,ue({uid:r.userId}),this.restBaseUrl=p??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 ge()}catch(E){s.warn("Report logs on login failed",E)}}catch(E){const e=E instanceof w?E.code:-1,t=E instanceof Error?E.message:String(E);throw C?.finish({code:e,success:!1,description:t}),l?.finish({code:e,success:!1,description:t}),this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(Ae.DISCONNECTED),fe(),E}}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.activeAppKey=this.config.appKey??null,this.resetManagerSessionRuntimes(),this.updateState(Ae.DISCONNECTED),this.logReportEnabled=!1,le("disabled"),ye(),void fe();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await ge()}catch(n){s.warn("Report logs on logout failed",n)}await this.core.disconnect()}finally{this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(Ae.DISCONNECTED),this.logReportEnabled=!1,le("disabled"),ye(),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 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.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(t){const n=Fe.validateOrThrow(Il,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:Yl,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});o.setAuthToken(n),s.warn("Renew token started",{userId:r.userId});const a=await Hl(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,pe({token:n}),s.warn("Renew token succeeded",{userId:r.userId,expireAt:a}),c}async getRTCTokenInfo(e){const t=Fe.validateOrThrow(vl,e),n=this.getRestContext(),r=new X(n.restBaseUrl,{errorMap:Yl,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)}),zl(r,n,t)}async getUserIdsWithRTCUids(e){const t=Fe.validateOrThrow(Cl,e),n=this.getRestContext(),r=new X(n.restBaseUrl,{errorMap:Yl,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}),jl(r,n,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new X(e.restBaseUrl,{errorMap:Yl,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}),Wl(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 hl({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===Kt.START_COMPLETED||e.stream.status===Kt.FULL||e.stream.status===Kt.COMPLETED||e.stream.status===Kt.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:Io(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=fo(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=>{po.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};mo(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(Gt(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 gd({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const s=this.cacheManager.loadSessionList().map(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 ol(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 pl(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 Fl(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=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())}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new S("appKey is unavailable before DNSConfig resolution",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new S("appKey is unavailable for the current session",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){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&&(e.appId===s.appId&&(!!t.isSameStringArray(e.enableSyncData,s.enableSyncData)&&(e.useCustomAttachmentUpload===s.useCustomAttachmentUpload&&(e.enableMd5Check===s.enableMd5Check&&(!!t.isSameServiceConfig(e.serviceConfig,s.serviceConfig)&&(e.useFixedDeviceId===s.useFixedDeviceId&&(e.deviceId===s.deviceId&&(e.useReplacedMessageContents===s.useReplacedMessageContents&&(e.customDeviceName===s.customDeviceName&&(e.customOSPlatform===s.customOSPlatform&&(e.platformAdapterOptions?.prefer===s.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===s.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.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??Al,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 Xl=Jl;export{A as AuthenticationError,So as CONVERSATION_MARK,gd as CacheManager,Xl 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,Kt as StreamMessageStatus,M as UploadError,bt as UserInfoManager,S as ValidationError,Ri as createPlatformAdapter,Mi as detectRuntimePlatform,Ee as isSDKError,be 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},Kd=async(e,t)=>{const s=await qd(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:Bd(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 Gd{constructor(e=`session-list-${Xe()}`){this.status="idle",this.seenBatchKeys=/* @__PURE__ */new Set,this.itemsByConversation=/* @__PURE__ */new Map,this.batchCount=0,this.requestId=e,this.startedAt=Date.now()}getRequestId(){return this.requestId}getStartedAt(){return this.startedAt}start(){"idle"===this.status&&(this.status="connecting")}markSyncing(){if("completed"===this.status||"failed"===this.status||"cancelled"===this.status)throw new L("Session-list sync session cannot re-enter syncing state after completion",e.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(t){if(t.requestId!==this.requestId)throw new L("Session-list sync requestId mismatch",e.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:t.requestId}});if(this.isTerminal())throw new L("Session-list sync batch received after terminal state",e.CONTACT_SYNC_CURSOR_INVALID,{details:{requestId:t.requestId,status:this.status}});const s=(n=t.requestId,r=t.batchSequence,`${n}:${r}`);var n,r;if(this.seenBatchKeys.has(s))return{accepted:!1,done:t.isLastBatch};this.markSyncing(),this.seenBatchKeys.add(s);for(const e of t.sessions)this.itemsByConversation.set(`${e.conversationType}:${e.conversationId}`,e);return this.batchCount+=1,t.isLastBatch&&(this.status="completed",this.finishedAt=Date.now()),{accepted:!0,done:t.isLastBatch}}fail(){this.status="failed",this.finishedAt=Date.now()}cancel(){this.status="cancelled",this.finishedAt=Date.now()}getItems(){return[...this.itemsByConversation.values()]}getBatchCount(){return this.batchCount}getStatus(){return this.status}buildSnapshot(){return{requestId:this.requestId,status:this.status,pageCount:this.batchCount,startedAt:this.startedAt,finishedAt:this.finishedAt,seenBatchKeys:[...this.seenBatchKeys]}}isTerminal(){return"completed"===this.status||"failed"===this.status||"cancelled"===this.status}}const Vd=0,Hd=5,zd=10,jd=11,Wd=1,$d=2,Qd=1,Yd=2,Jd=3,Xd=e=>e===Wd?"groupChat":e===$d?"chatRoom":"singleChat",Zd=()=>Yi().lookupType("easemob.pb.MessageBody"),el=e=>{const t=Zd().toObject(Zd().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:fs,o="string"==typeof n.remotePath&&n.remotePath.length>0||"string"==typeof n.title&&n.title.length>0||"string"==typeof n.summary&&n.summary.length>0||"number"==typeof n.combineLevel&&n.combineLevel>0,a=Object.prototype.hasOwnProperty.call(n,"subType")&&0===n.subType;return i===bs||i===fs&&(a||o)?{type:"combine",title:"string"==typeof n.title?n.title:"",summary:"string"==typeof n.summary?n.summary:"",filename:"string"==typeof n.displayName?n.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof n.remotePath?n.remotePath:void 0,secret:"string"==typeof n.secretKey?n.secretKey:void 0,fileLength:"number"==typeof n.fileLength?n.fileLength:void 0,combineLevel:"number"==typeof n.combineLevel?n.combineLevel:0}:i===fs?{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:""}:{}},tl=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}},sl=e=>{const t={...e};return delete t.type,t},nl=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,rl=(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:nl({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:sl(t)};var i},il=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},ol=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return el(e)}catch{return{}}})(e.last_message?.payload),n=e.session_id??"",r=Xd(e.session_type),i=(e=>{const t=e.session_id??"",s=Xd(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:tl(e)})(e);return{conversationId:n,conversationType:r,unreadCount:e.unread_count??0,lastMessage:rl(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:il(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===Qd?"ALL":o===Yd?"AT":o===Jd?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),al={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 cl=null,dl=!1;const ll=()=>cl||(dl||(ot.util.Long=nt,ot.configure(),dl=!0),st(),cl=ot.Root.fromJSON(al),it(cl),cl),ul=e=>ll().lookupType(e),hl=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}},pl=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:hl(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:hl(t.protocol_version)??hl(t.protocolVersion)??0}},ml=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}},fl=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==hl(t.id)?String(hl(t.id)):void 0,from:ml(t.from),timestamp:hl(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 gl{constructor(){this.requestType=ul("easemob.sessionlist.GetSessionListRequest"),this.responseType=ul("easemob.sessionlist.GetSessionListResponse"),this.errorType=ul("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:Vd}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=hl(t.type);return s!==zd?null:{type:s,header:pl(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:hl(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=hl(t.type);return s!==jd?null:{type:s,header:pl(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:hl(t.session_type),last_message:fl(t.last_message),updated_at:hl(t.updated_at),pinned_time:hl(t.pinned_time),unread_count:hl(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:hl(t.read_receipt),remind_type:hl(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:hl(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=hl(t.type);return s!==Hd?null:{type:s,header:pl(t.header),code:hl(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const yl=async t=>{const s=t.client.getCacheManager(),n=t.client.getRestContext(),r=t.client.getSessionListSyncWsUrls();if(!s||0===r.length)throw new C("session-list sync websocket is unavailable",{code:e.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[i,o]=n.appKey.split("#");if(!i||!o)throw new M("session-list appKey is invalid",{code:e.VALIDATION_INVALID_FORMAT,details:{appKey:n.appKey}});const c=s.loadSessionListCheckpoint(),d=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:t.session.getRequestId(),resource:n.clientResource,org:i,app:o,username:n.userId,lastSyncTime:(l=c.sessionsLastSyncTs,Math.max(0,l-Y)),params:t.params});var l;const u=new gl;let h=0,p=c.sessionsLastSyncTs;return await t.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:t.session.getRequestId(),encode:()=>u.encodeRequest(d),decode:e=>{const t=u.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:s=>{if(5===s.type&&"code"in s&&"message"in s)throw 1002===(r=s).code?new D(r.message,{code:e.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:r.code}}):1003===r.code?new L(r.message,e.SERVER_BUSY,{details:{protocol:"session-list",responseCode:r.code}}):1501===r.code||1001===r.code?new M(r.message,{code:e.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:r.code}}):1503===r.code?new L(r.message,e.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:r.code}}):(r.code,new L(r.message,e.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:r.code}}));var r;if(11!==s.type)throw new L("session-list response type is invalid",e.MESSAGE_DECODE_FAILED,{details:{responseType:s.type}});const i=s,o=i.header?.requestId;if(o&&o!==t.session.getRequestId())return;h+=1,a.debug("Decoded session-list sync raw response",{requestId:t.session.getRequestId(),batchSequence:h,response:i});const c=ol(i,n.userId),d=t.session.pushBatch({requestId:t.session.getRequestId(),batchSequence:h,sessions:c,isLastBatch:!0===i.isLastBatch,lastSyncFinishedTs:i.lastSyncFinishedTs});if("number"==typeof i.lastSyncFinishedTs&&(p=i.lastSyncFinishedTs),!d.done)return;return{done:!0,result:{items:t.session.getItems(),lastSyncFinishedTs:p}}}})},Il=()=>Date.now(),vl={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Cl=(e,t)=>({status:e,determinedAt:Il(),reason:t}),Sl=t=>t instanceof L&&(t.code===e.SERVER_BUSY||1103===t.code),El=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Sl(e)});class bl{constructor(e){this.running=null,this.currentSession=null,this.activeFinish=null,this.cancelled=!1,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}cancel(){this.cancelForTeardown()?.()}cancelForTeardown(){this.cancelled=!0,this.currentSession?.cancel();const t=this.activeFinish;return this.activeFinish=null,t?()=>{t({dataType:"conversation",status:"failed",error:{dataType:"conversation",code:e.SESSION_LIST_CANCELLED,stage:"cancelled",message:"session-list sync cancelled",retryable:!1}})}:null}refresh(e){return this.cancelled?Promise.resolve([]):(this.running||(this.currentSession=new Gd,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running)}async runRefresh(t,s){const n=this.client.getCacheManager();if(!n)return[];let r=!1;const i=e=>{r||(r=!0,this.client.emitSyncDataFinished(e))};this.activeFinish=i;try{this.client.emitSyncDataStart("conversation");const e=await this.tryDirectFallback(n);if(this.cancelled)return[];if(e)return this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"success"}),e;const r=n.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let a=0;const c=await async function(e,t,s={}){const n={...kd,...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=Pd(o,n);await xd(e)}throw r}(async()=>{if(this.cancelled)throw new L("session-list sync controller is cancelled");a+=1;const e=1===a?t:this.createRetrySession();e.start();try{return await yl({client:this.client,session:e,params:s})}catch(n){throw this.cancelled||e.fail(),n}},e=>!this.cancelled&&Sl(e),vl);if(this.cancelled)return[];const d={result:c,syncStartedAt:t.getStartedAt()},l=d.result.items;this.capabilityState={status:"available",determinedAt:Il()};const u={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Il()};try{if(await n.commitSessionListSync({items:l,mode:r,checkpoint:u,syncStartedAt:d.syncStartedAt}),this.cancelled)return[]}catch(o){if(this.cancelled)return[];t.fail();const e=new J("Session-list final persistence failed",{details:{cause:o instanceof Error?o.message:String(o)}});return this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"failed",error:El(e)}),n.loadSessionList()}const h=n.loadSessionList();return n.updateConversationsFromServer(h.map(vt),{syncStartedAt:d.syncStartedAt}),await n.flushPending(),this.cancelled?[]:(this.client.emitConversationListUpdate("conversation","full"===r),i({dataType:"conversation",status:"success"}),h)}catch(o){if(this.cancelled)return[];const s=o instanceof L?o:new L(o instanceof Error?o.message:String(o));t.fail();const r=(t=>t.code===e.OPERATION_UNSUPPORTED||t.code===e.AUTH_UNAUTHORIZED?{capabilityState:Cl("unsupported",t.message),shouldUseFallback:!0}:t.code===e.AUTH_TOKEN_EXPIRED||t.code===e.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:t.code===e.SERVER_BUSY||1103===t.code?{shouldUseFallback:!0,shouldRetry:!0}:t.code===e.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(s);r.capabilityState&&(this.capabilityState=r.capabilityState),r.shouldResetCheckpoint&&n.resetSessionListCheckpoint();const a=await this.buildFallbackSessionList(n);return this.cancelled?[]:(r.shouldUseFallback&&n.replaceSessionList(a),this.client.emitConversationListUpdate("conversation",!0),i({dataType:"conversation",status:"failed",error:El(s)}),a)}finally{this.activeFinish===i&&(this.activeFinish=null)}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}var t;const s=this.client.hasSessionListSyncWsUrl(),n=this.client.isSessionListDnsProbeAvailable();if(!s&&!n){this.capabilityState=Cl("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}return null}createRetrySession(){return new Gd}async buildFallbackSessionList(e){return await(async(e,t)=>await Kd(e,t))(e.loadConversationSummaries(),this.client)}}const Tl=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Al=async t=>{if("string"==typeof t||Tl(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Tl(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength))(t);if((e=>"undefined"!=typeof Blob&&e instanceof Blob&&"function"==typeof e.arrayBuffer||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(t))return new Uint8Array(await t.arrayBuffer());throw new L("sync websocket frame payload type is invalid",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof t}})},wl=e=>{const t=Math.max(e-1,0),s=ne*Math.pow(re,t);return Math.min(s,se)},Nl=async e=>{await new Promise(t=>{setTimeout(t,e)})},Ml=e=>e instanceof Error?e:new Error(String(e));class Rl{constructor(e){this.pending=/* @__PURE__ */new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(t){if(this.cancelled)throw new L("sync websocket session is cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:t.requestId}});if(this.pending.has(t.requestId))throw new L("sync websocket requestId is duplicated",e.VALIDATION_INVALID_FORMAT,{details:{stage:"request_send",requestId:t.requestId}});this.clearCompleteCloseTimer();const s=new Promise((e,s)=>{this.pending.set(t.requestId,{...t,resolve:e,reject:s})});s.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(t.requestId))}catch(n){this.rejectPending(t.requestId,Ml(n))}return await s}cancel(t="sync-websocket-cancelled"){this.cancelled=!0;const s=new L("sync websocket cancelled",e.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",reason:t}});this.rejectAll(s),this.closeSocket(4001,t),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==o.OPEN){if(this.connectPromise)return await this.connectPromise;this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let t=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&a.warn("sync websocket retry started",this.buildLogContext({reason:t?.message}));try{return void(await this.openSocket())}catch(s){if(t=Ml(s),this.cancelled||0===this.pending.size)throw t;if(this.attempt>=3)throw a.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),t;const e=wl(this.attempt);a.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:e,reason:t.message})),await Nl(e)}}throw new C("sync websocket retry exhausted",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:t?.message??"unknown"}})}async openSocket(){const t=await this.getUrls();if(0===t.length)throw new C("sync websocket urls are unavailable",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const s=t[this.urlIndex%t.length];if(this.urlIndex+=1,!s)throw new C("sync websocket url is invalid",{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=s,this.state="connecting",a.warn("sync websocket connect started",this.buildLogContext());const n=Vi(this.socketAdapter);let r=null;try{const e=await Promise.race([n.connect({url:s}),new Promise((e,t)=>{r=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},X)})]);r&&clearTimeout(r),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),a.warn("sync websocket connected",this.buildLogContext())}catch(i){if(r&&clearTimeout(r),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),i instanceof C)throw i;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:i instanceof Error?i.message:String(i)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await Al(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Ml(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(t){const s=[];let n=null;for(const e of this.pending.values())try{const s=e.decode(t);if(s.requestId&&s.requestId===e.requestId){try{const t=await e.onFrame(s.frame,this.socket);t?.done&&(this.pending.delete(e.requestId),e.resolve(t.result),this.closeIfComplete())}catch(r){this.pending.delete(e.requestId),e.reject(Ml(r)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||n||(n={pending:e,frame:s.frame})}catch(r){s.push(Ml(r))}if(n)return await n.pending.onFrame(n.frame,this.socket),!0;if(this.pending.size>0&&s.length===this.pending.size)throw new L("sync websocket frame decode failed",e.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:s[0]?.message}});return a.warn("sync websocket frame ignored",this.buildLogContext({reason:s[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(a.warn("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(Ml(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===o.OPEN)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),a.warn("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const s=this.pending.get(e);s&&(this.pending.delete(e),s.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(a.warn("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},Z))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},ee))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const s=this.socket;this.socket=null,!s||s.readyState>=o.CLOSING||(this.state="closing",s.close(e,t))}buildConnectionError(t,s,n={}){return new C(t,{code:e.CONTACT_SYNC_SOCKET_FAILED,details:{stage:s,url:this.activeUrl,...n}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:te(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const _l=async(t,s,n)=>{const{orgName:r,appName:i}=P(t.appKey),o=`/${r}/${i}/user/${encodeURIComponent(t.userId)}/roster/metadata/version`,a=new ie(t.restBaseUrl,{requestAdapter:n,includeRequestId:!0});a.setAuthToken(t.token);try{return((t,s)=>{const n=Date.now(),r=e=>{const t="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:t,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??t!==s,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:n}};if(bt(t))return bt(t.data)?r(t.data):r(t);throw new M("Invalid contact metadata response",{code:e.VALIDATION_INVALID_FORMAT,details:{payload:t}})})(await a.get(o),s)}catch(c){if(c instanceof M)throw c;const t=c instanceof L&&c.details?c.details:{};throw new oe("Contact metadata request failed",{code:e.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:c instanceof Error?c.message:String(c),httpStatus:"number"==typeof t.httpStatus?t.httpStatus:void 0,sourceCode:c instanceof L?c.code:void 0}})}},Dl=e=>Tt.string().regex(/^https?:\/\/\S+$/i,e),Ul=Tt.object({appKey:Tt.string().min(1,"appKey is required").optional(),appId:Tt.string().min(1,"appId is required").optional(),enableUserInfoSync:Tt.boolean().optional(),enableSyncData:Tt.array(Tt.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Tt.boolean().optional(),deleteConversationOnGroupDestroyed:Tt.boolean().optional(),syncConversationListConfig:Tt.object({includeEmpty:Tt.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:Tt.boolean().optional(),useFixedDeviceId:Tt.boolean().optional(),deviceId:Tt.string().min(1,"deviceId is required").optional(),serviceConfig:Tt.object({dnsConfigUrls:Tt.array(Dl("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:Tt.object({restApiUrl:Dl("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(Ll="serviceConfig.serverUrls.wsUrl must be a valid URL",Tt.string().regex(/^wss?:\/\/\S+$/i,Ll)).optional()}).optional()}).optional(),useReplacedMessageContents:Tt.boolean().optional(),customDeviceName:Tt.string().min(1,"customDeviceName is required").optional(),customOSPlatform:Tt.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:Tt.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Tt.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:Tt.array(Tt.unknown()).optional(),platformAdapterOptions:Tt.object({prefer:Tt.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:Tt.custom(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:Tt.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:Tt.custom(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const s=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===s?t.addIssue({code:Tt.ZodIssueCode.custom,path:["appKey"],message:"appKey or appId is required"}):s>1&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const n=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,r=n?.serverUrls&&"object"==typeof n.serverUrls?n.serverUrls:void 0;n?.dnsConfigUrls&&r&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),r&&(void 0!==e.appId&&t.addIssue({code:Tt.ZodIssueCode.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),r?.restApiUrl||t.addIssue({code:Tt.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),r?.wsUrl||t.addIssue({code:Tt.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var Ll;const Ol=Tt.object({userId:Tt.string().min(1,"userId is required"),token:Tt.string().min(1,"token is required")}),kl=Tt.object({timeoutMs:Tt.number().int("timeoutMs must be an integer").min(ae,`timeoutMs must be at least ${ae}`).max(ce,`timeoutMs must be at most ${ce}`).optional()}).strict(),Pl=Tt.string().trim().min(1,"token is required"),xl=Tt.object({channelName:Tt.string().trim().min(1,"channelName is required").optional()}).optional(),Fl=Tt.array(Tt.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))),Bl=Tt.object({protocol:Tt.string(),domain:Tt.string().optional(),ip:Tt.string().optional(),port:Tt.union([Tt.string(),Tt.number()]).optional()}).passthrough(),ql=Tt.object({app_key:Tt.string().optional(),rest:Tt.object({hosts:Tt.array(Bl).nonempty()}),"msync-wx":Tt.object({hosts:Tt.array(Bl).nonempty()}),"sync-ws":Tt.object({hosts:Tt.array(Bl).nonempty()}).optional(),enableReportLogs:Tt.enum(["true","false"]).optional(),reportInterval:Tt.number().positive().finite().optional(),enableDataReport:Tt.enum(["true","false"]).optional(),enableMd5Check:Tt.enum(["true","false"]).optional(),uploadinparts_enable:Tt.enum(["true","false"]).optional()}).passthrough(),Kl="5.1.2",Gl=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Vl=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function Hl(e){return"object"==typeof e&&null!==e}function zl(e){return Array.isArray(e)?{hosts:e}:function(e){return Hl(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function jl(e){if(!Hl(e))return Ze.validateOrThrow(ql,e);const t=zl(e.rest),s=function(e,t,s){for(const n of t){const t=zl(e[n]);if(t)return{key:n,section:t}}for(const[n,r]of Object.entries(e)){if(!s(n))continue;const e=zl(r);if(e)return{key:n,section:e}}}(e,Vl,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),n={...e,rest:t??e.rest,"msync-wx":s?.section},r="true"===(i=e.enableReportLogs)||!0===i?"true":"false"===i||!1===i?"false":void 0;var i;r&&(n.enableReportLogs=r);const o=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==o?n.reportInterval=o:delete n.reportInterval;const c=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);c?n.enableDataReport=c:delete n.enableDataReport;const d=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);d?n.enableMd5Check=d:delete n.enableMd5Check;const l=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return l?n.uploadinparts_enable=l:delete n.uploadinparts_enable,s&&"msync-wx"!==s.key&&a.warn("DNS config websocket section normalized",{sourceKey:s.key}),Ze.validateOrThrow(ql,n)}function Wl(t,s){const n=t.domain||t.ip;if(!n)throw new M("DNS host missing domain/ip",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const r=void 0!==t.port?String(t.port):"";return`${"https"===s?"wss":"ws"}://${r&&"80"!==r&&"443"!==r?`${n}:${r}`:n}/websocket`}function $l(e,t){return"https"===e?"https":"http"===e?"http":t}function Ql(t,s){const n=t.domain||t.ip;if(!n)throw new M("DNS rest host missing domain/ip",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const r=void 0!==t.port?String(t.port):"";return`${s}://${r&&"80"!==r&&"443"!==r?`${n}:${r}`:n}`}function Yl(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function Jl(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 Xl(e,t,s,n){const r=new ie(e,{requestAdapter:s,includeRequestId:!0});let i="/easemob/server.json",o=!0;try{const t=new URL(e),s=""!==t.pathname&&"/"!==t.pathname,n=""!==t.search;(s||n)&&(i="",o=!1)}catch{i="/easemob/server.json",o=!0}if(o){i=`${i}?${(void 0!==t.appId?At({app_id:t.appId,sdk_version:Kl,file_version:"1"}):At({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return jl(await r.get(i,{timeout:n}))}async function Zl(t){const s=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:Gl;if(0===s.length)throw new M("DNS_CONFIG list is empty",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const n=t.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let r;for(const c of s){const s=t.loginDeadline,i=s?.remainingMs();if(s&&void 0!==i&&i<=0)throw s.createTimeoutError();try{const s=void 0!==t.appId?{appId:t.appId}:{appKey:t.appKey},r=void 0===i?void 0:Math.min(de,i),o=await Xl(c,s,t.requestAdapter,r),a=void 0!==t.appId?o.app_key:t.appKey;if("string"!=typeof a||0===a.length)throw new M("DNS app_key is required for appId initialization",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const d=Jl(Yl(o["msync-wx"].hosts,n));if(0===d.length)throw new M("DNS msync-wx hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const l=d[0];if(!l)throw new M("DNS msync-wx hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const u=Yl(o.rest.hosts,n);if(0===u.length)throw new M("DNS rest hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const h=u[0];if(!h)throw new M("DNS rest hosts resolution failed",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const p=d.map(e=>Wl(e,$l(e.protocol,n))),m=Wl(l,$l(l.protocol,n));return{appKey:a,websocketUrl:m,websocketUrls:p,baseUrl:c,restBaseUrl:Ql(h,$l(h.protocol,n)),dnsConfig:o}}catch(o){if(s&&s.remainingMs()<=0)throw s.createTimeoutError();a.warn("DNS config candidate failed",{baseUrl:c,reason:o instanceof Error?o.message:String(o),error:o instanceof Error&&"function"==typeof o.toJSON?o.toJSON():o}),r=o}}const i={stage:"dns"};throw r&&(i.reason=r.message,"code"in r&&"number"==typeof r.code&&(i.causeCode=r.code)),new C("DNS_CONFIG exhausted",{code:e.CONNECTION_DNSLIST_FAILED,details:i})}const eu=e=>{const t=(e=>{const t=e.trim(),s=/^(https?):\/\//i.exec(t);if(!s?.[1])throw new M("REST API URL must use http or https protocol");const n=s[1].toLowerCase(),r=t.slice(s[0].length),i=r.search(/[/?#]/),o=i>=0?r.slice(0,i):r,a=o.lastIndexOf("@"),c=a>=0?o.slice(a+1):o;if(!c)throw new M("REST API URL host is required");let d,l;if(c.startsWith("[")){const e=c.indexOf("]");if(e<=1)throw new M("REST API URL IPv6 host is invalid");d=c.slice(0,e+1);const t=c.slice(e+1);if(t){if(!t.startsWith(":"))throw new M("REST API URL authority is invalid");l=t.slice(1)}}else{const e=c.lastIndexOf(":");if(e>=0){if(c.indexOf(":")!==e)throw new M("REST API URL IPv6 host must use brackets");d=c.slice(0,e),l=c.slice(e+1)}else d=c}if(!d)throw new M("REST API URL host is required");if(void 0!==l){const e=Number(l);if(!/^\d+$/.test(l)||e<1||e>65535)throw new M("REST API URL port is invalid")}return{protocol:n,host:d,port:l}})(e),s="http"===t.protocol&&"80"===t.port||"https"===t.protocol&&"443"===t.port,n="https"===t.protocol?"wss":"ws",r=t.port&&!s?`:${t.port}`:"";return`${n}://${t.host}${r}/ws`},tu=t=>new M(t,{code:e.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),su=e=>{if(!bt(e))throw tu("Invalid REST response");return bt(e.data)?e.data:e},nu=(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}}},ru=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},iu=e=>{const{orgName:t,appName:s}=P(e.appKey);return`/${t}/${s}`},ou=async(e,t)=>{const s=await e.get((e=>`${iu(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=su(e),s=nu(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw tu("Invalid token expires response");return s})(s)},au=async(e,t,s)=>{const n=await e.get(((e,t)=>{const s=At({channelName:t?.channelName??"*"});return`${iu(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${s.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=su(e);return{appId:ru(t,["app_id","appId"])??"",rtcToken:ru(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:ru(t,["channel_name","channelName"])??"",rtcUid:nu(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:nu(t,["expires_in","expire","expireAt"])??0}})(n)},cu=async(e,t,s)=>{const n=await e.post((e=>`${iu(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=su(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)},du=async(e,t)=>{const s=await e.get((e=>`${iu(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=bt(e)&&Array.isArray(e.data)?e.data:[],n=[];for(const r of s){if(!bt(r))continue;const e=ru(r,["res","resource","clientResource"]);e&&e!==t.clientResource&&n.push(`${t.userId}/${e}`)}return n})(s,t)};class lu{constructor(e){this.options=e,this.pendingGroups=/* @__PURE__ */new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=/* @__PURE__ */new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,s){if(!e||!t)return;const n=this.pendingGroups.get(e)??/* @__PURE__ */new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,n),this.pendingOrder.push(e));const r=n.get(t);n.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(r?.namecardUpdateTime,s)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const s=Array.from(t.values()),n=Math.max(1,this.options.maxBatchSize);for(let r=0;r<s.length;r+=n)this.readyGroups.push({groupId:e,targets:s.slice(r,r+n)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{a.warn("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),s=t-e;return s<=0?t:e+Math.floor(Math.random()*(s+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class uu{constructor(e){this.options=e,this.pendingTargets=/* @__PURE__ */new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let s=0;s<e.length;s+=t)this.readyBatches.push(e.slice(s,s+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const s=this.generation;this.activeCount+=1;const n=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let r;try{r=Promise.resolve(this.options.onFlush(n))}catch(t){r=Promise.reject(t instanceof Error?t:new Error(String(t)))}r.catch(t=>{const n=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(a.warn("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:n.length>0,error:t instanceof Error?t.message:String(t)}),s===this.generation&&0!==n.length){for(const e of n)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const s of this.readyBatches){const t=s.findIndex(t=>t.userId===e.userId);if(t>=0){const n=s[t];return void(n&&(s[t]=this.mergeTarget(n,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class hu{constructor(e,t,s=Date.now){this.attemptId=e,this.timeoutMs=t,this.now=s,this.timeoutId=null,this.status="active",this.expiresAt=this.now()+t,this.timeoutPromise=new Promise((e,s)=>{this.timeoutId=setTimeout(()=>{"active"===this.status&&(this.status="expired",this.timeoutId=null,s(this.createTimeoutError()))},t)}),this.timeoutPromise.catch(()=>{})}getStatus(){return this.status}remainingMs(){return"expired"===this.status?0:Math.max(0,this.expiresAt-this.now())}clamp(e){return Math.max(0,Math.min(e,this.remainingMs()))}race(e){return"expired"===this.status||0===this.remainingMs()?(e.catch(()=>{}),this.expire(),Promise.reject(this.createTimeoutError())):"active"!==this.status?e:Promise.race([e,this.timeoutPromise])}markProvisionReceived(){return"active"===this.status&&(this.status="provision-received",this.clearTimer(),!0)}expire(){"active"===this.status&&(this.status="expired",this.clearTimer())}dispose(){"active"===this.status&&(this.status="disposed"),this.clearTimer()}createTimeoutError(){return new C("Login timeout",{code:e.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",timeoutMs:this.timeoutMs,attemptId:this.attemptId,retryable:!0}})}clearTimer(){null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const pu=Ue(Le,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),mu=class t{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=Be.DISCONNECTED,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=/* @__PURE__ */new Set,this.managerSessionGeneration=0,this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null,this.postLoginTaskContext=null,this.terminalSessionCleanupTask=null,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=Gi(this.config.platformAdapterOptions)),this.managerRegistry=/* @__PURE__ */new Map,this.managerCapabilities=/* @__PURE__ */new Map,this.eventHub=new Od,Oe(e=>{this.eventHub.dispatch(ut.LOG,e)}),this.managerEventContext={addEventHandler:(e,t)=>{this.eventHub.addEventHandler(e,t)},removeEventHandler:e=>{this.eventHub.removeEventHandler(e)},dispatch:(e,t)=>{this.eventHub.dispatch(e,t)}},this.userInfoHydrationQueue=new uu({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:ue,maxRetries:le,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new lu({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:pe,maxBatchSize:he,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[qe.CONNECTING]:e=>{this.updateState(e.state)},[qe.CONNECTED]:e=>{this.updateState(e.state)},[qe.DISCONNECTED]:e=>{this.updateState(e.state),this.isTerminalManagerSessionDisconnect(e)&&this.startTerminalSessionCleanup(e)},[qe.RECONNECT_FAILED]:e=>{this.updateState(e.state)},[ct.MESSAGE]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[ct.STREAM_MESSAGE]:e=>{this.handleIncomingConversationStreamMessage(e)},[Ge.MESSAGE_SENT]:e=>{this.handleOutgoingConversationMessage(e)},[ct.MULTI_DEVICE_CONTACT]:e=>{this.handleMultiDeviceContactEvent(e)},[ct.MULTI_DEVICE_CONVERSATION]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[dt.ADDED]:e=>this.handleIncomingContactRosterEvent("add",e),[dt.AGREED]:e=>this.handleIncomingContactRosterEvent("add",e),[dt.INVITED]:e=>this.handleIncomingContactRosterEvent("none",e),[dt.REFUSE]:e=>this.handleIncomingContactRosterEvent("none",e),[dt.DELETED]:e=>this.handleIncomingContactRosterEvent("remove",e),[Ge.GROUP_NOTIFY]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===at.GROUP_DESTROYED&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[Ge.CHATROOM_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[Ge.CHAT_THREAD_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[Ge.USER_INFO_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(s){const n=Ze.validateOrThrow(Ul,s),r=n.customOSPlatform,i=t.normalizeServiceConfig(n.serviceConfig),o={appKey:n.appKey,appId:n.appId,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:t.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==r?n.customDeviceName:void 0,customOSPlatform:r,uiKitVersion:n.uiKitVersion,loginExtensionInfo:n.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:ye,userInfoBatchSize:ge,groupNamecardWindowMs:fe,groupNamecardMaxConcurrency:me},platformAdapterOptions:n.platformAdapterOptions},a=s.managers??[];if(t.instance){if(!t.isSameConfig(t.instance.config,o))throw new M("ChatClient already initialized with different config",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:t.instance.config,next:o}});return a.length>0&&t.instance.registerManagers(a),t.instance.validateOptionalCapabilityDependencies(),t.instance}return t.instance=new t(o),a.length>0&&t.instance.registerManagers(a),t.instance.validateOptionalCapabilityDependencies(),t.instance}async login(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const r=Ze.validateOrThrow(Ol,s),i=Ze.validateOrThrow(kl,n??{});if(await this.waitForTerminalSessionCleanup(),this.state===Be.CONNECTING||this.state===Be.CONNECTED){const t=this.currentUserId&&this.currentUserId!==r.userId;throw new C(t?"Another user is already logged in":"ChatClient is already connecting or connected",{code:t?e.USER_ALREADY_LOGIN_ANOTHER:e.AUTH_ALREADY_LOGIN,details:{stage:"auth",...t?{currentUserId:this.currentUserId,nextUserId:r.userId}:{}}})}const o=++this.loginAttempt,c=new hu(o,i.timeoutMs??Ie);try{let t=this.config.appKey??null;this.activeAppKey=t,a.warn("Login started",{userId:r.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const s=this.platformAdapter??Gi(this.config.platformAdapterOptions);this.platformAdapter=s,ve({requestAdapter:s.request,onDiagnostic:(e,t)=>{a.warn(e,t)}});const n=Ce({appKey:t??"default#appkey",uid:r.userId,sdkVersion:Kl,platform:s.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),i=s.runtime.getNetworkType?.();i&&i.then(e=>{Se(e)}).catch(()=>{Se("unknown")});const l=E({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:r.userId});let u,h,p;this.updateState(Be.CONNECTING),this.logReportEnabled=!1,Ee("unknown");let m,f=!1,g=!1,y=!0;if("dns"===this.config.serviceConfig.mode){const e=l?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const n=await c.race(Zl(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:c}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:c}));t=n.appKey,this.activeAppKey=t,be({appKey:t}),a.warn("DNS resolved for login",{baseUrl:n.baseUrl,websocketUrl:n.websocketUrl,restBaseUrl:n.restBaseUrl,syncWebSocketSource:"rest"}),u=n.websocketUrl,h=n.websocketUrls;const r=eu(n.restBaseUrl);this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!0,p=n.restBaseUrl,f="true"===n.dnsConfig.enableReportLogs,m=n.dnsConfig.reportInterval,g="true"===n.dnsConfig.enableMd5Check,y="false"!==n.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),Te(n.dnsConfig.enableDataReport),a.debug("DNS report switch resolved",{enabled:f})}catch(d){const t=d instanceof L?d.code:-1,s=d instanceof Error?d.message:String(d);throw e?.finish({code:t,success:!1,description:s}),l?.finish({code:t,success:!1,description:s}),Te(void 0),Ee("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),c.dispose(),d}}else{const t=this.config.serviceConfig.serverUrls;if(!t?.wsUrl||!t.restApiUrl){const t=new M("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw l?.finish({code:t.code,success:!1,description:t.message}),Te(void 0),this.updateState(Be.DISCONNECTED),c.dispose(),t}u=t.wsUrl,p=t.restApiUrl;const s=eu(p);g=this.config.enableMd5Check,this.contactSyncWsUrls=[s],this.syncConversationListConfigWsUrls=[s],this.contactSyncDnsResolved=!1,Te(void 0)}if(!t){const t=new M("appKey is unavailable after service discovery",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(Be.DISCONNECTED),Ae(),c.dispose(),t}we({restBaseUrl:p,appKey:t,userId:r.userId,token:r.token,requestAdapter:s.request}),Ne(m),this.logReportEnabled=f,Ee(f?"enabled":"disabled");const I=this.resetCore();if(I?.(),o!==this.loginAttempt){const t=new C("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}});throw l?.finish({code:e.CONNECTION_CANCELLED,success:!1,description:t.message}),this.updateState(Be.DISCONNECTED),this.activeAppKey=this.config.appKey??null,Ae(),c.dispose(),t}const v=new Kc({serverUrl:u,serverUrls:h,userId:r.userId,token:r.token,appKey:t,restBaseUrl:p,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:g,enableMultipartUpload:y,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:n,platformAdapter:s,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub);this.core=v,we({resource:v.getClientResource()});const S=l?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:u});try{a.warn("Connecting core websocket",{serverUrl:u,restBaseUrl:p,userId:r.userId});try{await c.race(v.connect(c))}finally{c.dispose()}this.throwIfLoginSessionCancelled(o,v),S?.finish({code:200,success:!0}),l?.finish({code:0,success:!0}),a.warn("Core websocket connected",{userId:r.userId,resource:v.getClientResource()}),this.currentUserId=r.userId,be({uid:r.userId}),this.restBaseUrl=p??null,this.authToken=r.token,this.clientResource=v.getClientResource(),await this.initCacheManager(r.userId),this.throwIfLoginSessionCancelled(o,v),a.warn("Cache initialized after login",{userId:r.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),this.notifyManagersSessionReady(r.userId,this.clientResource),this.startPostLoginTasks(r.userId,o)}catch(d){const e=d instanceof L?d.code:-1,t=d instanceof Error?d.message:String(d);if(S?.finish({code:e,success:!1,description:t}),l?.finish({code:e,success:!1,description:t}),this.core===v){const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),Ae()}finally{e?.()}}throw d}}finally{c.dispose()}}startPostLoginTasks(e,t){this.cancelPostLoginTasks();const s={attemptId:t,userId:e,cancelled:!1};this.postLoginTaskContext=s,this.runPostLoginTasks(s).catch(e=>{this.isPostLoginTaskActive(s)&&a.warn("Unexpected post-login task failure",{userId:s.userId,reason:e instanceof Error?e.message:String(e)})}).finally(()=>{this.postLoginTaskContext===s&&(this.postLoginTaskContext=null)})}cancelPostLoginTasks(){this.postLoginTaskContext&&(this.postLoginTaskContext.cancelled=!0,this.postLoginTaskContext=null)}isPostLoginTaskActive(e){return!e.cancelled&&this.postLoginTaskContext===e&&e.attemptId===this.loginAttempt&&this.currentUserId===e.userId}async runPostLoginTasks(e){if(!this.isPostLoginTaskActive(e))return;if(await this.runPostLoginTask(e,"self-user-info",async()=>{await this.syncSelfUserInfoAfterLogin()}),!this.isPostLoginTaskActive(e))return;if(this.config.enableSyncData.includes("conversation")&&await this.runPostLoginTask(e,"conversation",async()=>{await this.refreshSessionList(this.config.syncConversationListConfig)}),!this.isPostLoginTaskActive(e))return;const t=this.triggerConfiguredSyncDataAfterLogin(e.userId,e),s=this.logReportEnabled?this.runPostLoginTask(e,"log-report",async()=>{await Me()}):Promise.resolve();await Promise.all([t,s])}async runPostLoginTask(e,t,s){if(this.isPostLoginTaskActive(e))try{await s()}catch(n){if(!this.isPostLoginTaskActive(e))return;a.warn("Post-login synchronization step failed",{userId:e.userId,task:t,reason:n instanceof Error?n.message:String(n)})}}async logout(){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});for(this.loginAttempt+=1,this.cancelPostLoginTasks();this.terminalSessionCleanupTask;)await this.terminalSessionCleanupTask;if(this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("logout"),!this.core){const e=this.detachSessionListSyncController();try{this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.resetManagerSessionRuntimes(),Ee("disabled"),Re(),Ae()}finally{this.contactSyncController=null,this.groupSyncController=null,this.syncWebSocketSession=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),this.logReportEnabled=!1,e?.()}return}try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await Me()}catch(s){a.warn("Report logs on logout failed",s)}await this.core.disconnect()}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),this.logReportEnabled=!1,Ee("disabled"),Re(),Ae()}finally{e?.()}}}getConnectionState(){return this.state}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new M("restBaseUrl is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new M("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new M("userId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const t=this.clientResource??this.core?.getClientResource();if(!t)throw new M("clientResource is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(t){const s=Ze.validateOrThrow(Pl,t);if(!this.core||!this.currentUserId||this.state!==Be.CONNECTED)throw new C("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const n=this.getRestContext(),r={...n},i=new ie(r.restBaseUrl,{errorMap:pu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(s),a.warn("Renew token started",{userId:n.userId});const o=await ou(i,r);if(o<=Date.now())throw new C("Token is expired",{code:e.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const c=this.core.renewToken(s,o);return this.authToken=s,we({token:s}),a.warn("Renew token succeeded",{userId:n.userId,expireAt:o}),c}async getRTCTokenInfo(e){const t=Ze.validateOrThrow(xl,e),s=this.getRestContext(),n=new ie(s.restBaseUrl,{errorMap:pu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return n.setAuthToken(s.token),a.warn("Get RTC token info started",{userId:s.userId,hasChannelName:Boolean(t?.channelName)}),au(n,s,t)}async getUserIdsWithRTCUids(e){const t=Ze.validateOrThrow(Fl,e),s=this.getRestContext(),n=new ie(s.restBaseUrl,{errorMap:pu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return n.setAuthToken(s.token),a.warn("Get userIds with RTC UIDs started",{userId:s.userId,count:t.length}),cu(n,s,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new ie(e.restBaseUrl,{errorMap:pu,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),a.warn("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),du(t,e)}getCacheManager(){return this.cacheManager}getManagerByCapability(e){return this.managerCapabilities.get(e)}getUploadAdapter(){return this.platformAdapter?.upload??null}getRequestAdapter(){return this.platformAdapter?.request}addInternalEvent(e,t){this.eventHub.dispatch(e,t)}refreshSessionList(e){return this.cacheManager&&this.currentUserId?this.ensureSessionListSyncController().refresh({includeEmpty:e?.includeEmpty??this.config.syncConversationListConfig.includeEmpty,includeMark:!0}).then(e=>(this.enqueueMissingGroupSessionSenderUserInfos(e),e.map(e=>({...e})))):Promise.resolve([])}getServerUrlsConfig(){return this.config.serviceConfig.serverUrls}getSessionListSyncWsUrls(){return this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}hasSessionListSyncWsUrl(){return this.syncConversationListConfigWsUrls.length>0}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new Rl({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===Zt.START_COMPLETED||e.stream.status===Zt.FULL||e.stream.status===Zt.COMPLETED||e.stream.status===Zt.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:Lo(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 wt(t,{cacheManager:this.cacheManager,fetchUserInfos:s?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=n}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(s){return a.warn("Contact roster event user info fetch failed",{userIds:e,error:s}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&a.warn("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){a.warn("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=_o(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=>{Mo.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Ro(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const s=e.map(e=>e.userId);let n;try{n=await t.getUserInfoByUserId({userIds:s})}catch(l){throw a.warn("User info hydration failed",{userIds:s,error:l}),l}const r=this.currentUserId,i=r?n.find(e=>e.userId===r):void 0,o=n.filter(e=>e.userId!==r);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),n.length>0&&this.refreshConversationDisplayFromUserInfos(n.map(e=>({userId:e.userId})),"profile");const c=new Set(n.map(e=>e.userId)),d=s.filter(e=>!c.has(e));d.length>0&&a.warn("User info hydration returned partial result",{requestedUserIds:s,missingUserIds:d})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(s){a.warn("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:s})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(s){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(s),this}async sendMessage(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!s?.sender?.userId)throw new M("sender.userId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&s.sender.userId!==this.currentUserId)throw new M("sender.userId does not match current user",{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(es(s))throw new b("Stream message send is not supported",{code:e.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:s.msgLocalId,retryable:!1}});if(this.core&&this.state!==Be.CONNECTED&&await this.waitForSendConnectionRecovery(this.core),!this.core||this.state!==Be.CONNECTED)throw new b("ChatClient is not connected",{code:e.MESSAGE_NOT_CONNECTED,details:{msgLocalId:s.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(s),this.core.sendMessage(s,n)}async waitForSendConnectionRecovery(e){let t=null;const s=e.recoverConnectionForSend().then(()=>!0).catch(e=>(a.warn("Send connection recovery failed",{error:e instanceof Error?e.message:String(e)}),!1)),n=new Promise(e=>{t=setTimeout(()=>{e(!1)},_e)}),r=await Promise.race([s,n]);t&&clearTimeout(t),r||a.warn("Send connection recovery wait timed out",{timeoutMs:_e,state:this.state})}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",s){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),s).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=/* @__PURE__ */new Set;for(const r of e){const e="groupChat"===r.conversationType?r.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const s=this.cacheManager.getUserInfoSummaries([...t],!1),n=new Set(s.map(e=>e.userId));for(const r of t)n.has(r)||this.userInfoHydrationQueue.enqueue(r)}dispatchUserGroupNamecardUpdated(e,t,s){e&&t&&this.eventHub.dispatch(at.USER_GROUP_NAMECARD_UPDATED,{groupId:e,userId:t,namecard:s})}async downloadAndParseCombinePayload(s){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(s)}async sendMessageAction(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendMessageAction(s,n)}async sendChatRoomOperation(s,n){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(s,n)}async downloadAttachment(s){if(t.instance!==this)throw new M("ChatClient is not initialized",{code:e.VALIDATION_REQUIRED});if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.downloadAttachment(s)}decodeServerMessageMeta(t){if(!this.core)throw new M("ChatClient is not connected",{code:e.AUTH_NOT_LOGIN});return this.core.decodeServerMessageMeta(t)}registerManagers(t){if(0===t.length)return;const s=/* @__PURE__ */new Set;for(const n of t){const t=this.resolveManagerKey(n);if(s.has(t))throw this.buildManagerValidationError(`Manager key duplicated: ${t}`,e.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t});s.add(t)}for(const e of t)this.registerManagerInput(e)}registerManagerInput(e){return t.isManagerConstructor(e)?this.registerManagerConstructor(e):this.registerManagerInstance(e)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),s=this.managerRegistry.get(t);if(s){if(s.constructor===e)return s;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const n=new e;return n.bind(this,this.managerEventContext),this.managerRegistry.set(t,n),this.registerManagerCapabilities(n),this.attachManager(t,n),this.notifyManagerSessionReady(n),n}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),s=this.managerRegistry.get(t);if(s){if(s===e)return e;if(s.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),this.notifyManagerSessionReady(e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const s=this.getManagerByCapability(e);return s?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(t,s,n){return new M(`${t} requires explicit manager capability: ${s}`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} requires explicit manager capability: ${s}`,rule:"dependency"}],capability:s,requiredManagers:n}})}resolveManagerKey(s){if(t.isManagerConstructor(s))return this.getManagerKeyFromConstructor(s);if("object"!=typeof s||null===s)throw this.buildManagerValidationError("Manager must be constructor or instance",e.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof s});return this.getManagerKeyFromInstance(s)}getManagerKeyFromConstructor(t){const s=t.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.VALIDATION_REQUIRED,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(t)});return s}getManagerKeyFromInstance(t){const s=t.constructor.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.VALIDATION_REQUIRED,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(t)});return s}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,s,n,r){return new M(e,{code:t,details:{fields:[{path:s,message:e,rule:n}],...r}})}buildManagerConflictError(t,s,n,r){return this.buildManagerValidationError("Manager key conflict",e.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t,existingName:s,incomingName:n,reason:r})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}throwIfLoginSessionCancelled(t,s){if(t!==this.loginAttempt||this.core!==s)throw new C("Login cancelled",{code:e.CONNECTION_CANCELLED,details:{stage:"auth"}})}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new Ld({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const s=this.cacheManager.loadSessionList().map(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(ct.CONVERSATION_LIST_UPDATE,{version:this.conversationListVersion,items:s,reason:e,patch:n}))}buildConversationListPatch(e,t,s){const n=new Map(e.map(e=>[this.buildConversationListKey(e),e])),r=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=/* @__PURE__ */new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=n.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);r.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:s,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,s)=>e===t.marks[s])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}async triggerConfiguredSyncDataAfterLogin(e,t){const s=[];this.config.enableSyncData.includes("contact")&&(a.warn("Triggering automatic contact sync after login",{userId:e}),s.push(this.runPostLoginTask(t,"contact",async()=>{await this.triggerContactSync()}))),this.config.enableSyncData.includes("group")&&(a.warn("Triggering automatic group sync after login",{userId:e}),s.push(this.runPostLoginTask(t,"group",async()=>{await this.triggerGroupSync()}))),await Promise.all(s)}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new bl(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const t=this.managerRegistry.get("contactManager");if(!t?.createSyncController)throw new M("ContactManager is required for contact sync",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"contactManager",message:"ContactManager must be registered for enableSyncData: ['contact']",rule:"required"}]}});return this.contactSyncController=t.createSyncController({getContextState:()=>{const e=this.requireCacheManager();return{cacheMeta:e.loadContactCacheMeta(),versionState:e.loadContactVersionState(),cachedSnapshot:e.loadContactSnapshot("cache")}},queryMetadata:async e=>await _l(this.getRestContext(),e,this.platformAdapter?.request),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),buildRosterRequest:({version:e})=>this.buildContactRosterRequest(e),applySyncResult:e=>{const t=this.requireCacheManager().applyContactSync(e);return this.refreshConversationDisplayFromUserInfos(t.snapshot.items.map(e=>({userId:e.userId})),"profile"),t},onStart:()=>{this.emitSyncDataStart("contact")},onFinish:e=>{this.emitSyncDataFinished({dataType:"contact",status:e?.error?"failed":"success",error:e?.error?{dataType:"contact",code:e.error.code,stage:e.error.stage,message:e.error.message,retryable:e.error.retryable}:void 0})}}),this.contactSyncController}ensureGroupSyncController(){if(this.groupSyncController)return this.groupSyncController;const t=this.managerRegistry.get("groupManager");if(!t?.createSyncController)throw new M("GroupManager is required for group sync",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"groupManager",message:"GroupManager must be registered for enableSyncData: ['group']",rule:"required"}]}});return this.groupSyncController=t.createSyncController({getRestContext:()=>this.getRestContext(),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),getCacheManager:()=>this.requireCacheManager(),applyRuntimeSnapshot:e=>{const t=this.managerRegistry.get("groupManager");t?.applyJoinedGroupSnapshot?.(e),this.refreshConversationDisplayFromJoinedGroups(e.items,"profile")},getRuntimeSnapshot:()=>{const e=this.managerRegistry.get("groupManager");return e?.getJoinedGroupSnapshotForSync?.()??null},onStart:()=>{this.emitSyncDataStart("group")},onFinish:e=>{this.emitSyncDataFinished({dataType:"group",status:e.status,error:e.error})}}),this.groupSyncController}emitSyncDataStart(e){this.eventHub.dispatch(ct.SYNC_DATA_START,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(ct.SYNC_DATA_FINISHED,e)}requireCacheManager(){if(!this.cacheManager)throw new M("cacheManager is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw a.warn("Derived contact sync websocket is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new L("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw a.warn("Derived contact sync websocket is unavailable for fixed service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new L("Contact sync websocket urls are unavailable",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await Zl(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=[eu(e.restBaseUrl)],this.contactSyncDnsResolved=!0}catch(t){throw a.warn("Automatic contact sync REST endpoint DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new L("Contact sync websocket dns resolve failed",e.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:t instanceof Error?t.message:String(t)}})}return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new M("token is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const s=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(s))throw new M("sync websocket URL must use ws or wss protocol");const n=s.indexOf("#"),r=n>=0?s.slice(n):"",i=n>=0?s.slice(0,n):s,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,l=a.indexOf("/",d),u=l<0||"/"===a.slice(l)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${u}?${h.join("&")}${r}`}shuffleContactSyncUrls(e){const t=[...e];for(let s=t.length-1;s>0;s-=1){const e=Math.floor(Math.random()*(s+1)),n=t[s],r=t[e];n&&r&&(t[s]=r,t[e]=n)}return t}buildContactRosterRequest(e){const t=this.getRestContext(),{orgName:s,appName:n}=P(t.appKey);return{type:Nt.REQUEST,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:s,app:n,username:t.userId,version:e,cursor:0}}detachSessionListSyncController(){const e=this.syncConversationListConfigController;return this.syncConversationListConfigController=null,e?.cancelForTeardown()??null}resetCore(){const e=this.detachSessionListSyncController();try{return this.cancelPostLoginTasks(),this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core?(this.core.destroy(),this.clearCoreSessionState(),this.resetManagerSessionRuntimes(),e):e}catch(t){throw this.clearCoreSessionState(),this.updateState(Be.DISCONNECTED),e?.(),t}}clearCoreSessionState(){this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new M("appKey is unavailable before DNSConfig resolution",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new M("appKey is unavailable for the current session",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){for(const t of this.managerRegistry.values())try{t.resetSessionRuntime?.()}catch(e){a.warn("Manager session runtime reset failed",{manager:this.getManagerNameFromInstance(t),error:e instanceof Error?e.message:"unknown"})}this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null}notifyManagersSessionReady(e,t){const s={generation:++this.managerSessionGeneration,userId:e,clientResource:t};this.activeManagerSessionContext=s,this.managerSessionEndingPromise=null;for(const n of this.managerRegistry.values())this.notifyManagerSessionReady(n)}notifyManagerSessionReady(e){const t=this.activeManagerSessionContext;if(t&&e.onSessionReady)try{e.onSessionReady(t)}catch(s){a.warn("Manager session ready hook failed",{manager:this.getManagerNameFromInstance(e),error:s instanceof Error?s.message:"unknown"})}}notifyManagersSessionEnding(e){const t=this.activeManagerSessionContext;if(!t)return Promise.resolve();if(this.managerSessionEndingPromise)return this.managerSessionEndingPromise;const s={...t,reason:e},n=Array.from(this.managerRegistry.values(),e=>{if(!e.onSessionEnding)return Promise.resolve();try{return Promise.resolve(e.onSessionEnding(s)).catch(t=>{a.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"})})}catch(t){return a.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"}),Promise.resolve()}}),r=Promise.all(n).then(()=>{});let i=null;const o=new Promise(t=>{i=setTimeout(()=>{a.warn("Manager session ending hooks timed out",{timeoutMs:De,reason:e}),t()},De)});return this.managerSessionEndingPromise=Promise.race([r,o]).then(()=>{null!==i&&clearTimeout(i),this.activeManagerSessionContext?.generation===t.generation&&(this.activeManagerSessionContext=null)}),this.managerSessionEndingPromise}isTerminalManagerSessionDisconnect(t){return t.reason===Ve.TOKEN_EXPIRED||[e.AUTH_TOKEN_EXPIRED,e.AUTH_BIND_ANOTHER_DEVICE,e.AUTH_LOGIN_TOO_MANY_DEVICES,e.USER_LOGIN_ANOTHER_DEVICE,e.USER_REMOVED,e.USER_KICKED_BY_CHANGE_PASSWORD,e.USER_KICKED_BY_OTHER_DEVICE].includes(t.errorCode??-1)}startTerminalSessionCleanup(e){if(this.terminalSessionCleanupTask)return;a.warn("Terminal session cleanup started",{errorCode:e.errorCode,errorMessage:e.errorMessage,reason:e.reason});const t=this.finishTerminalSessionCleanup().catch(e=>{a.error("Terminal session cleanup failed",e instanceof Error?e:new Error(String(e)))}).finally(()=>{this.terminalSessionCleanupTask===t&&(this.terminalSessionCleanupTask=null)});this.terminalSessionCleanupTask=t}async waitForTerminalSessionCleanup(){await(this.terminalSessionCleanupTask??Promise.resolve())}async finishTerminalSessionCleanup(){this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("terminal-disconnect");try{try{await(this.cacheManager?.flushPending())}catch(e){a.warn("Cache flush on terminal disconnect failed",{error:e instanceof Error?e.message:String(e)})}if(this.logReportEnabled)try{await Me()}catch(e){a.warn("Report logs on terminal disconnect failed",e)}}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(Be.DISCONNECTED),this.logReportEnabled=!1,Ee("disabled"),Re(),Ae()}finally{e?.()}}a.warn("Terminal session cleanup finished")}static isSameConfig(e,s){return e.appKey===s.appKey&&(e.appId===s.appId&&(!!t.isSameStringArray(e.enableSyncData,s.enableSyncData)&&(e.useCustomAttachmentUpload===s.useCustomAttachmentUpload&&(e.enableMd5Check===s.enableMd5Check&&(!!t.isSameServiceConfig(e.serviceConfig,s.serviceConfig)&&(e.useFixedDeviceId===s.useFixedDeviceId&&(e.deviceId===s.deviceId&&(e.useReplacedMessageContents===s.useReplacedMessageContents&&(e.customDeviceName===s.customDeviceName&&(e.customOSPlatform===s.customOSPlatform&&(e.platformAdapterOptions?.prefer===s.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===s.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.transportAdapter===s.platformAdapterOptions?.transportAdapter&&(e.platformAdapterOptions?.overrides===s.platformAdapterOptions?.overrides&&(e.uiKitVersion===s.uiKitVersion&&(e.cacheEncryptionMode===s.cacheEncryptionMode&&(e.enableUserInfoSync===s.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===s.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===s.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===s.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===s.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===s.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===s.profileSync.groupNamecardMaxConcurrency))))))))))))))))))))}static normalizeServiceConfig(e){const s=e?.serverUrls;return{mode:s?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??Gl,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:s?{restApiUrl:s.restApiUrl,wsUrl:s.wsUrl?t.normalizeFixedWebSocketUrl(s.wsUrl):void 0}:void 0}}static normalizeFixedWebSocketUrl(e){const t=e.search(/[?#]/),s=-1===t?e:e.slice(0,t),n=-1===t?"":e.slice(t),r=s.indexOf("://")+3,i=s.indexOf("/",r);if(-1===i)return`${s}/websocket${n}`;const o=s.slice(i);return/^\/+$/u.test(o)?`${s.slice(0,i)}/websocket${n}`:e}static normalizeSyncDataTypes(e){const t=[];for(const s of e)t.includes(s)||t.push(s);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}static isSameServiceConfig(e,s){if(e.mode!==s.mode)return!1;if(e.dnsConfigUrls.length!==s.dnsConfigUrls.length)return!1;for(let t=0;t<e.dnsConfigUrls.length;t+=1)if(e.dnsConfigUrls[t]!==s.dnsConfigUrls[t])return!1;return t.isSameServerUrls(e.serverUrls,s.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl)}};mu.instance=null;let fu=mu;function gu(e){Pe(e)}function yu(e){ke(e)}export{D as AuthenticationError,Po as CONVERSATION_MARK,Ld as CacheManager,fu as ChatClient,et as ChatManager,Dt as ChatRoom,Ut as ChatRoomManager,Rt as ChatThread,_t as ChatThreadManager,C as ConnectionError,Mt as ContactManager,ft as Group,gt as GroupManager,Xt as ImageType,ut as LogEventName,T as MessageReceiveError,b as MessageSendError,U as NetworkError,Lt as PresenceManager,ht as PushEventName,Ot as PushManager,s as RUNTIME_PLATFORMS,xe as RestBusinessError,oe as RestTransportError,L as SDKError,J as StorageError,Zt as StreamMessageStatus,k as UploadError,kt as UserInfoManager,M as ValidationError,Gi as createPlatformAdapter,Ki as detectRuntimePlatform,Fe as isSDKError,yu as setConsoleLogEnabled,gu as setLogLevel};