easemob-websdk 5.1.1 → 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.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/chat-client.d.ts +42 -8
- package/chunks/{chat-manager-QJCNq-in.cjs → chat-manager-BFd2Z4oY.cjs} +1 -1
- package/chunks/{chat-manager-QxcfwVLg.js → chat-manager-CId_M_e5.js} +1 -1
- package/chunks/common-BvlDAw4a.js +1 -0
- package/chunks/common-tHGz9VBk.cjs +1 -0
- package/chunks/event-system-B62vbKqG.js +1 -0
- package/chunks/{event-system-COBJFEIq.cjs → event-system-TYhmgy4K.cjs} +1 -1
- package/chunks/group-user-info-resolver-B-dyr__b.cjs +1 -0
- package/chunks/group-user-info-resolver-DMccCqez.js +1 -0
- package/chunks/index-BBFJYOM8.js +1 -0
- package/chunks/{index-DIV5mZP8.cjs → index-DJPAjXAp.cjs} +1 -1
- package/chunks/index-DtWkVcfb.cjs +1 -0
- package/chunks/index-l_BUKi77.js +1 -0
- package/chunks/{session-list-query-rynxSxtv.js → session-list-query-Cvr6rlme.js} +1 -1
- package/chunks/{session-list-query-C4OQMvPf.cjs → session-list-query-Dslj2k3t.cjs} +1 -1
- package/chunks/{user-info-DfbCp80h.js → user-info-AlshAvdy.js} +1 -1
- package/chunks/{user-info-DsDDTJrw.cjs → user-info-DH3aE1gm.cjs} +1 -1
- package/config/timeouts.d.ts +11 -0
- package/core/connection/connection-manager.d.ts +18 -1
- package/core/connection/login-deadline.d.ts +22 -0
- package/core/events/event-hub.d.ts +1 -0
- package/core/index.d.ts +8 -1
- package/core/message/attachment-downloader.d.ts +1 -1
- package/core/session-list-sync/session-list-sync-controller.d.ts +5 -0
- package/index.cjs +1 -1
- package/index.d.ts +11 -9
- package/index.js +2 -2
- package/log.d.ts +27 -0
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-thread/index.cjs +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chatroom/chatroom.d.ts +1 -1
- package/managers/chatroom/index.cjs +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/chatroom-manager.d.ts +6 -1
- package/managers/contact/index.cjs +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.cjs +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.d.ts +2 -0
- package/managers/push/index.js +1 -1
- package/managers/push/native-push-controller.d.ts +62 -0
- package/managers/push/native-push-normalizer.d.ts +15 -0
- package/managers/push-manager.d.ts +63 -4
- package/managers/user-info/index.cjs +1 -1
- package/managers/user-info/index.js +1 -1
- package/managers/user-info-manager.d.ts +3 -2
- package/message/combine-payload-codec.d.ts +2 -1
- package/package.json +1 -1
- package/platform/index.d.ts +1 -1
- package/platform/request/default-request-adapter.d.ts +7 -0
- package/platform/socket/default-socket-adapter.d.ts +6 -0
- package/platform/types.d.ts +22 -2
- package/platform/upload/legacy-multipart-upload.d.ts +14 -0
- package/platform/upload/legacy-simple-upload.d.ts +3 -0
- package/protocol/msync/codec.d.ts +5 -0
- package/rest/client.d.ts +0 -4
- package/rest/contact-management.d.ts +1 -0
- package/rest/dns-config.d.ts +6 -1
- package/rest/error-maps/chatroom.d.ts +6 -0
- package/rest/error-maps/common.d.ts +3 -0
- package/rest/error-maps/contact.d.ts +8 -3
- package/rest/error-maps/push.d.ts +13 -1
- package/rest/error-maps/user-info.d.ts +51 -3
- package/rest/service-url.d.ts +6 -0
- package/types/chat-client.d.ts +16 -9
- package/types/chatroom.d.ts +3 -34
- package/types/event-system.d.ts +52 -1
- package/types/index.d.ts +5 -7
- package/types/log.d.ts +19 -0
- package/types/manager.d.ts +31 -0
- package/types/push.d.ts +77 -0
- package/upload/attachment-uploader.d.ts +1 -5
- package/upload/multipart-upload.d.ts +4 -14
- package/upload/simple-upload.d.ts +4 -3
- package/upload/types.d.ts +2 -1
- package/utils/error-codes.generated.d.ts +1 -0
- package/utils/log-reporter.d.ts +1 -7
- package/utils/logger.d.ts +28 -2
- package/validators/chat-client.d.ts +22 -50
- package/validators/message-create.d.ts +18 -18
- package/chunks/common-BIpcR2uQ.cjs +0 -1
- package/chunks/common-D_DfwSd3.js +0 -1
- package/chunks/event-system-D6IJA0C4.js +0 -1
- package/chunks/group-user-info-resolver-Ds35Z1Uf.cjs +0 -1
- package/chunks/group-user-info-resolver-lEtRdWli.js +0 -1
- package/chunks/index-Baofxzfc.cjs +0 -1
- package/chunks/index-CKbroPac.js +0 -1
- package/chunks/index-DPi6gEFw.js +0 -1
package/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/common-BIpcR2uQ.cjs"),t=require("./chunks/chat-manager-QJCNq-in.cjs"),s=require("./chunks/group-user-info-resolver-Ds35Z1Uf.cjs"),r=require("./chunks/reflection-proto-codec-CwrIKT1L.cjs"),n=require("./chunks/light-BcQg8h2W.cjs"),o=require("./chunks/event-system-COBJFEIq.cjs"),i=require("./chunks/index-DIV5mZP8.cjs"),a=require("./chunks/profile-version-njNs7R5-.cjs"),c=require("./chunks/session-list-query-C4OQMvPf.cjs"),d=require("./chunks/cache-utils-gowrxNr8.cjs"),l=require("zod"),u=require("./chunks/query-params-BHyPuD2k.cjs"),h=require("./chunks/index-Baofxzfc.cjs"),p=require("./managers/chat-thread/index.cjs"),m=require("./managers/chatroom/index.cjs"),g=require("./managers/presence/index.cjs"),f=require("./managers/push/index.cjs"),y=require("./managers/user-info/index.cjs"),E="onChatRoomDestroyed",R="onMembersJoined",I="onMembersExited",v="onRemovedFromChatRoom",S="onMuteListAdded",C="onMuteListRemoved",T="onAllowListAdded",A="onAllowListRemoved",O="onAllMemberMuteStateChanged",b="onAdminAdded",_="onAdminRemoved",M="onOwnerChanged",N="onAnnouncementChanged",D="onChatRoomInfoChanged",w="onAttributesUpdate",U="onAttributesRemoved",L={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function P(e){return"object"==typeof e.stream&&null!==e.stream}const k=0,x=1,F=2,B=3,G=4,q=0,K=1,V=2,z=3,H=4,W=5,j=6,Q=7,$=8,Y=0,J=1,X=2,Z=3,ee=4,te=5,se=6,re=7,ne=8,oe=0,ie=1,ae=2,ce=3,de=4,le=0,ue=1,he=2,pe=3,me=5,ge=0,fe=1,ye=2,Ee=0,Re=0,Ie=2,ve=0,Se=1,Ce=2,Te=3,Ae=4,Oe=5,be=6,_e=7,Me=8,Ne=9,De=10,we=11,Ue=12,Le=13,Pe=14,ke=15,xe=16,Fe=17,Be=18,Ge=19,qe=20,Ke=1,Ve=2,ze=3,He=4,We=5,je=6,Qe=7,$e=8,Ye="Sorry, user register limit",Je="Sorry, user register rate limit",Xe="Sorry, token expired",Ze="Sorry, token or password does not match login info",et="Sorry, user not found",tt="Sorry, the app month live count limit",st="Sorry, the app day live count limit",rt="Sorry, the app online count limit",nt={[Se]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Ce]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Te]:e.ERROR_CODES.VALIDATION_REQUIRED,[Ae]:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,[Oe]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[be]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[_e]:e.ERROR_CODES.AUTH_FORBIDDEN,[Ge]:e.ERROR_CODES.AUTH_FORBIDDEN,[Me]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[Ne]:e.ERROR_CODES.UNKNOWN,[De]:e.ERROR_CODES.UNKNOWN,[we]:e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE,[Ue]:e.ERROR_CODES.AUTH_FORBIDDEN,[Le]:e.ERROR_CODES.AUTH_LOGIN_TOO_MANY_DEVICES,[Pe]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[ke]:e.ERROR_CODES.AUTH_USER_MUTED,[xe]:e.ERROR_CODES.UNKNOWN,[Fe]:e.ERROR_CODES.UNKNOWN,[Be]:e.ERROR_CODES.MESSAGE_DECODE_FAILED,[qe]:e.ERROR_CODES.USER_DEVICE_CHANGED},ot=new Set([Se,Ce,Te,Ae,be,_e,Ge,Ne,De,we,Ue,Le,Pe,ke,xe,Fe,Be,qe]),it={[Ye]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Je]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Xe]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[Ze]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[et]:e.ERROR_CODES.AUTH_UNAUTHORIZED,blocked:e.ERROR_CODES.MESSAGE_BLOCKED_BY_RECIPIENT,"group not found":e.ERROR_CODES.GROUP_NOT_EXIST,"illegal chatroom tag":e.ERROR_CODES.VALIDATION_REQUIRED,"not in group or chatroom":e.ERROR_CODES.GROUP_NOT_JOINED,"exceed recall time limit":e.ERROR_CODES.MESSAGE_RECALL_TIME_LIMIT,"message recall disabled":e.ERROR_CODES.SERVICE_NOT_ENABLED,"group ack not open":e.ERROR_CODES.SERVICE_NOT_ENABLED,"group ack msg permission denied":e.ERROR_CODES.GROUP_PERMISSION_DENIED,"the message has expired":e.ERROR_CODES.MESSAGE_EXPIRED,"limit send group ack msg":e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,"not in group or chatroom white list":e.ERROR_CODES.MESSAGE_ILLEGAL_WHITELIST,nonroster:e.ERROR_CODES.USER_NOT_ON_ROSTER,"group is disabled":e.ERROR_CODES.GROUP_DISABLED,"roaming is not open":e.ERROR_CODES.SERVICE_NOT_ENABLED,"Sorry, message does not exist":e.ERROR_CODES.VALIDATION_REQUIRED,"Sorry, edit limit reached":e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,"Sorry, You do not have permission":e.ERROR_CODES.AUTH_FORBIDDEN,"Sorry, format is incorrect":e.ERROR_CODES.VALIDATION_REQUIRED,"Sorry, edit is not available":e.ERROR_CODES.SERVER_SERVING_DISABLED,"Sorry, edit fail":e.ERROR_CODES.MESSAGE_EDIT_FAILED},at=[["limit directed users",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.ERROR_CODES.AUTH_FORBIDDEN]],ct={[tt]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[st]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[rt]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,"sensitive words":e.ERROR_CODES.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"blocked by mod_antispam":e.ERROR_CODES.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"user is mute":e.ERROR_CODES.USER_MUTED_BY_ADMIN,"traffic limit":e.ERROR_CODES.MESSAGE_CURRENT_LIMITING,"Sorry, data is too large":e.ERROR_CODES.MESSAGE_SIZE_LIMIT},dt=(t,s)=>{if("number"!=typeof t)return{code:e.ERROR_CODES.UNKNOWN,retryable:!0};const r=((t,s)=>{if(s){if(t===Se){const t=it[s];if(void 0!==t)return t;for(const[e,r]of at)if(s.includes(e))return r;try{const t=JSON.parse(s);if("moderation"===t.error_type)return e.ERROR_CODES.THIRD_MODERATION_FAILED;if("string"==typeof t.error_type)return e.ERROR_CODES.THIRD_DEFAULT_FAILED}catch{}return}return t===_e?ct[s]:t===Ge?e.ERROR_CODES.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===ke?e.ERROR_CODES.AUTH_USER_MUTED:void 0}})(t,s),n=nt[t]??e.ERROR_CODES.UNKNOWN;return{code:r??n,retryable:!ot.has(t)}},lt={[e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED]:"Message operation exceeded a service limit",[e.ERROR_CODES.AUTH_TOKEN_EXPIRED]:"Message cannot be sent because the authentication token expired",[e.ERROR_CODES.VALIDATION_REQUIRED]:"Message cannot be sent because the request is invalid",[e.ERROR_CODES.AUTH_UNAUTHORIZED]:"Message cannot be sent because authentication failed",[e.ERROR_CODES.AUTH_FORBIDDEN]:"Message operation is forbidden",[e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE]:"Message cannot be sent because the account is bound to another device",[e.ERROR_CODES.AUTH_LOGIN_TOO_MANY_DEVICES]:"Message cannot be sent because the account is logged in on too many devices",[e.ERROR_CODES.AUTH_USER_MUTED]:"Message cannot be sent because the user is muted in the group or chat room",[e.ERROR_CODES.MESSAGE_BLOCKED_BY_RECIPIENT]:"Message cannot be sent because you are blocked by the recipient",[e.ERROR_CODES.USER_MUTED_BY_ADMIN]:"Message cannot be sent because the user is globally muted",[e.ERROR_CODES.USER_DEVICE_CHANGED]:"Message cannot be sent because the current device has changed",[e.ERROR_CODES.USER_NOT_ON_ROSTER]:"Message cannot be sent because the recipient is not in your contact list",[e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR]:"Message cannot be sent because the server is unreachable",[e.ERROR_CODES.SERVER_SERVING_DISABLED]:"Message editing is not available",[e.ERROR_CODES.MESSAGE_DECODE_FAILED]:"Message processing failed",[e.ERROR_CODES.MESSAGE_INCLUDE_ILLEGAL_CONTENT]:"Message contains prohibited content",[e.ERROR_CODES.MESSAGE_SEND_TRAFFIC_LIMIT]:"Message sending traffic limit exceeded",[e.ERROR_CODES.MESSAGE_RECALL_TIME_LIMIT]:"The message recall time limit has been exceeded",[e.ERROR_CODES.SERVICE_NOT_ENABLED]:"The required messaging service is not enabled",[e.ERROR_CODES.MESSAGE_EXPIRED]:"The message has expired",[e.ERROR_CODES.MESSAGE_ILLEGAL_WHITELIST]:"The user is not in the group or chat room allowlist",[e.ERROR_CODES.MESSAGE_EXTERNAL_LOGIC_BLOCKED]:"The message was blocked by external logic",[e.ERROR_CODES.MESSAGE_CURRENT_LIMITING]:"Message sending rate limit exceeded",[e.ERROR_CODES.MESSAGE_SIZE_LIMIT]:"Message size exceeds the limit",[e.ERROR_CODES.MESSAGE_EDIT_FAILED]:"Message editing failed",[e.ERROR_CODES.GROUP_NOT_JOINED]:"The user is not in the group or chat room",[e.ERROR_CODES.GROUP_PERMISSION_DENIED]:"The user does not have permission to perform this group message operation",[e.ERROR_CODES.GROUP_NOT_EXIST]:"The group does not exist",[e.ERROR_CODES.GROUP_DISABLED]:"The group is disabled",[e.ERROR_CODES.THIRD_MODERATION_FAILED]:"The message was rejected by content moderation",[e.ERROR_CODES.THIRD_DEFAULT_FAILED]:"The message was rejected by a third-party service"},ut=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let s=0;s<e.length;s+=1){let r=e.charCodeAt(s);if(r>=55296&&r<=56319&&s+1<e.length){const t=e.charCodeAt(s+1);t>=56320&&t<=57343&&(r=65536+(r-55296<<10)+(t-56320),s+=1)}r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|63&r):r<=65535?t.push(224|r>>12,128|r>>6&63,128|63&r):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}return new Uint8Array(t)},ht=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0;s<e.length;s+=1){const r=e[s]??0;if(r<128){t+=String.fromCharCode(r);continue}if(r>=192&&r<224){const n=e[s+1]??0;t+=String.fromCharCode((31&r)<<6|63&n),s+=1;continue}if(r>=224&&r<240){const n=e[s+1]??0,o=e[s+2]??0;t+=String.fromCharCode((15&r)<<12|(63&n)<<6|63&o),s+=2;continue}const n=((7&r)<<18|(63&(e[s+1]??0))<<12|(63&(e[s+2]??0))<<6|63&(e[s+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),s+=3}return t};class pt{constructor(){this.lastEventKey=null}normalize(e,s){const r=(e=>{switch(e){case t.ConnectionStatus.CONNECTING:case t.ConnectionStatus.RECONNECTING:return t.ConnectionEventName.CONNECTING;case t.ConnectionStatus.CONNECTED:return t.ConnectionEventName.CONNECTED;case t.ConnectionStatus.DISCONNECTED:return t.ConnectionEventName.DISCONNECTED;case t.ConnectionStatus.RECONNECT_FAILED:return t.ConnectionEventName.RECONNECT_FAILED;default:return null}})(e);if(!r)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("|"))(r,s);return this.lastEventKey===n?null:(this.lastEventKey=n,{eventName:r,payload:s})}reset(){this.lastEventKey=null}}const mt={web:s.RUNTIME_PLATFORMS.WEB,"mp-weixin":s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,"mp-alipay":s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,"mp-baidu":s.RUNTIME_PLATFORMS.BAIDU_MINIAPP,"mp-toutiao":s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,"mp-lark":s.RUNTIME_PLATFORMS.LARK_MINIAPP,"mp-qq":s.RUNTIME_PLATFORMS.QQ_MINIAPP,"mp-kuaishou":s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,"mp-jd":s.RUNTIME_PLATFORMS.JD_MINIAPP,"mp-360":s.RUNTIME_PLATFORMS.MINIAPP_360,"mp-harmony":s.RUNTIME_PLATFORMS.HARMONY_MINIAPP,"quickapp-webview":s.RUNTIME_PLATFORMS.QUICKAPP,"quickapp-webview-union":s.RUNTIME_PLATFORMS.QUICKAPP,"quickapp-webview-huawei":s.RUNTIME_PLATFORMS.QUICKAPP},gt=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},ft=e=>(e=>gt(e,"canIUse")&>(e,"getSystemInfo"))(e)||(e=>gt(e,"request")&>(e,"connectSocket"))(e),yt=e=>gt(e,"request")&>(e,"connectSocket")&>(e,"uploadFile"),Et=(e,t)=>t===s.RUNTIME_PLATFORMS.WECHAT_MINIAPP?e.wx:t===s.RUNTIME_PLATFORMS.QQ_MINIAPP?e.qq:t===s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP?e.tt:t===s.RUNTIME_PLATFORMS.BAIDU_MINIAPP?e.swan:t===s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP?e.my:t===s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP?e.dd:t===s.RUNTIME_PLATFORMS.JD_MINIAPP?e.jd:t===s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP?e.ks:t===s.RUNTIME_PLATFORMS.UNIAPP?e.uni:void 0,Rt=e=>{const t=e?.miniGlobal;return ft(t)?t:e},It=e=>{const t=Rt(e);return yt(t)?t:void 0},vt=e=>void 0!==e.window&&void 0!==e.document,St=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),Ct=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(ft(t))return!0;try{if(!gt(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},Tt=e=>yt(e.wx)?s.RUNTIME_PLATFORMS.WECHAT_MINIAPP:yt(e.my)?s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP:yt(e.dd)?s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP:yt(e.swan)?s.RUNTIME_PLATFORMS.BAIDU_MINIAPP:yt(e.tt)?s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP:yt(e.qq)?s.RUNTIME_PLATFORMS.QQ_MINIAPP:yt(e.jd)?s.RUNTIME_PLATFORMS.JD_MINIAPP:yt(e.ks)?s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP:void 0,At=e=>void 0!==Tt(e),Ot=e=>{const t=Tt(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return mt[r]??s.RUNTIME_PLATFORMS.UNIAPP}catch{return s.RUNTIME_PLATFORMS.UNIAPP}return vt(e)?s.RUNTIME_PLATFORMS.WEB:s.RUNTIME_PLATFORMS.UNIAPP},bt=(e,t)=>{const s=It(Et(e,t));if(s)return s;const r=It(e.uni);return r||(e.uni??e)},_t=(t,r)=>{const n=t??e.getRuntimeGlobal();if(r){const e=r===s.RUNTIME_PLATFORMS.UNIAPP||Ct(n),t=e?Ot(n):r;return{platform:r,hostPlatform:t,framework:e?"uniapp":vt(n)?"web":"native",global:e?bt(n,t):Rt(Et(n,r))??n}}if(Ct(n)){const e=Ot(n);return{platform:s.RUNTIME_PLATFORMS.UNIAPP,hostPlatform:e,framework:"uniapp",global:bt(n,e)}}return ft(n.swan)?{platform:s.RUNTIME_PLATFORMS.BAIDU_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.BAIDU_MINIAPP,framework:"native",global:Rt(n.swan)??n.swan}:ft(n.tt)?{platform:s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,framework:"native",global:Rt(n.tt)??n.tt}:ft(n.dd)?{platform:s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,framework:"native",global:Rt(n.dd)??n.dd}:ft(n.my)?{platform:s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,framework:"native",global:Rt(n.my)??n.my}:ft(n.wx)?{platform:s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,framework:"native",global:Rt(n.wx)??n.wx}:ft(n.qq)?{platform:s.RUNTIME_PLATFORMS.QQ_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.QQ_MINIAPP,framework:"native",global:Rt(n.qq)??n.qq}:ft(n.jd)?{platform:s.RUNTIME_PLATFORMS.JD_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.JD_MINIAPP,framework:"native",global:Rt(n.jd)??n.jd}:ft(n.ks)?{platform:s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,framework:"native",global:Rt(n.ks)??n.ks}:(e=>"ReactNative"===e.navigator?.product)(n)?{platform:s.RUNTIME_PLATFORMS.REACT_NATIVE,hostPlatform:s.RUNTIME_PLATFORMS.REACT_NATIVE,framework:"react-native",global:n}:(e=>"string"==typeof e.process?.versions?.electron)(n)?{platform:vt(n)?s.RUNTIME_PLATFORMS.ELECTRON_RENDERER:s.RUNTIME_PLATFORMS.ELECTRON_MAIN,hostPlatform:vt(n)?s.RUNTIME_PLATFORMS.ELECTRON_RENDERER:s.RUNTIME_PLATFORMS.ELECTRON_MAIN,framework:"electron",global:n}:St(n)||vt(n)?{platform:s.RUNTIME_PLATFORMS.WEB,hostPlatform:s.RUNTIME_PLATFORMS.WEB,framework:St(n)?"worker":"web",global:n}:{platform:s.RUNTIME_PLATFORMS.UNKNOWN,hostPlatform:s.RUNTIME_PLATFORMS.UNKNOWN,framework:"native",global:n}},Mt=e=>e===s.RUNTIME_PLATFORMS.WECHAT_MINIAPP||e===s.RUNTIME_PLATFORMS.QQ_MINIAPP||e===s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP||e===s.RUNTIME_PLATFORMS.BAIDU_MINIAPP||e===s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||e===s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP||e===s.RUNTIME_PLATFORMS.LARK_MINIAPP||e===s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP||e===s.RUNTIME_PLATFORMS.JD_MINIAPP||e===s.RUNTIME_PLATFORMS.MINIAPP_360||e===s.RUNTIME_PLATFORMS.HARMONY_MINIAPP||e===s.RUNTIME_PLATFORMS.QUICKAPP||e===s.RUNTIME_PLATFORMS.UNIAPP,Nt=["request","upload","socket","proto"],Dt=(e,t=Nt)=>{const r=((e,t=Nt)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw s.createPlatformError("Platform missing required capabilities.",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{required:[...t],missing:r}})},wt={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}}}}}}}}}},Ut=e=>{if(!e||0===e.trim().length)throw s.createPlatformError("Proto type name is required.",{code:s.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:s.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:e}})};class Lt{constructor(){this.codecMap=new Map}register(e,t){Ut(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:r=>{const n=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw s.createPlatformError("Proto payload must be an object.",{code:s.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:s.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(r,e),o=t.fromObject(n);return t.encode(o).finish()},decode:e=>{const s=t.decode(e);return t.toObject(s,{longs:String,enums:Number,defaults:!1})}})}get(e){return Ut(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw s.createPlatformError("Proto codec not found.",{code:s.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:s.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:e}})}}let Pt=!1,kt=null,xt=null,Ft=null;const Bt=e=>e.startsWith(".")?e.slice(1):e,Gt=e=>e instanceof n.lightExports.Namespace,qt=e=>e instanceof n.lightExports.Type,Kt=e=>{for(const t of e.nestedArray)qt(t)?r.installReflectionCodecRecursive(t):Gt(t)&&Kt(t)},Vt=()=>{Pt||(n.lightExports.util.Long=r.Long,n.lightExports.configure(),Pt=!0),r.installReflectionRuntime();const e=n.lightExports.Root.fromJSON(wt);return Kt(e),e},zt=(e,t)=>{const s=e.nestedArray;for(const n of s){if(qt(n)){const e=Bt(n.fullName);r.installReflectionCodecRecursive(n),t.registerType(e,n);continue}Gt(n)&&zt(n,t)}},Ht=(e,t,r)=>{const n=t instanceof Error?t.message:String(t);return s.createPlatformError(`Static proto ${r} failed.`,{code:s.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:s.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:e,operation:r,cause:n}})},Wt=()=>kt||(kt=Vt(),kt),jt=()=>{if(Ft)return Ft;const e=(()=>{if(xt)return xt;const e=new Lt,t=Wt();return zt(t,e),xt=e,e})();return Ft={encode(t,s){try{return e.getOrThrow(Bt(t)).encode(s)}catch(r){throw Ht(t,r,"encode")}},decode(t,s){try{return e.getOrThrow(Bt(t)).decode(s)}catch(r){throw Ht(t,r,"decode")}}},Ft},Qt=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},$t=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(r){const n=r.method??"GET",o={...r.headers??{}},i=new AbortController,a=r.timeoutMs??e?.timeoutMs??15e3,c=setTimeout(()=>{i.abort()},a),d=((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)})(r,o,n);try{const e=await t(r.url,{method:n,headers:o,body:d,signal:r.signal??i.signal});let s;if("arraybuffer"===r.responseType)s=await e.arrayBuffer();else if("text"===r.responseType)s=await e.text();else{const t=e.headers.get("content-type")??"",r=await e.text();s=t.includes("application/json")&&r?JSON.parse(r):r}return{status:e.status,headers:Qt(e.headers),data:s}}catch(l){throw s.createPlatformError("Request adapter execution failed.",{code:s.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:s.PLATFORM_ERROR_STAGE.REQUEST,retryable:!0,details:{url:r.url,method:n,cause:l instanceof Error?l.message:String(l)}})}finally{clearTimeout(c)}}}},Yt=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Jt=e=>"function"==typeof e.on&&"function"==typeof e.off,Xt=(e,t,r)=>{if(Yt(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(Jt(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw s.createPlatformError("Socket event listener API is unsupported.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:!1,details:{event:t}})},Zt=(e,t,r)=>{if(Yt(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(Jt(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=Xt(e,t,(...e)=>{n(),r(...e)}),n}throw s.createPlatformError("Socket one-time listener API is unsupported.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:!1,details:{event:t}})},es=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?es(e.data):null;var t},ts=e=>{const t=new Set,r=new Set,n=new Set,o=new Set;return Xt(e,"open",()=>{t.forEach(e=>{e()})}),Xt(e,"message",(...e)=>{const t=es(e[0]);null!==t&&r.forEach(e=>{e(t)})}),Xt(e,"error",(...e)=>{const t=e[0];n.forEach(e=>{e(t)})}),Xt(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);o.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==s.SOCKET_READY_STATE.OPEN)throw s.createPlatformError("Socket is not open.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.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=>(r.add(e),()=>{r.delete(e)}),onError:e=>(n.add(e),()=>{n.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}},ss=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((r,n)=>{let o;try{o=new t(e.url,e.protocols);try{o.binaryType="arraybuffer"}catch{}}catch(h){return void n(s.createPlatformError("Socket creation failed.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{cause:h instanceof Error?h.message:String(h)}}))}let i,a=()=>{},c=()=>{},d=!1;const l=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},u=()=>{d||(d=!0,a(),c(),l(),o.close(),n(s.createPlatformError("Socket connection timed out.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{url:e.url,reason:"timeout"}})))};a=Zt(o,"open",()=>{d||(d=!0,a(),c(),l(),r(ts(o)))}),c=Zt(o,"error",e=>{if(d)return;d=!0,a(),c(),l();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;n(s.createPlatformError("Socket connection failed before open.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(u,e.timeoutMs))})}},rs=(e,t)=>{throw s.createPlatformError("Upload adapter execution failed.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:"abort"!==e,details:{reason:e,url:t.url}})},ns=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 s.createPlatformError("Web upload adapter only supports web-file source.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw s.createPlatformError("Upload source file is required for web-file uploads.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:t.source.sourceType}});const n="undefined"!=typeof Blob&&r instanceof Blob,o=t.source.name??"upload.bin";n?e.append("file",r,o):e.append("file",r)})(t,e),t},os=(e,t,r)=>new Promise((n,o)=>{const i=e(),a=r.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,r),i.addEventListener("abort",()=>{try{rs("abort",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{rs("timeout",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{rs("network",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{n({status:i.status,body:i.responseText})});try{const e=ns(r);i.timeout=a,i.open("POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,s])=>{e.setRequestHeader(t,s)})})(i,r.headers),i.send(e)}catch(c){o(s.createPlatformError("Upload adapter execution failed.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:c instanceof Error?c.message:String(c)}}))}}),is=(e,t)=>e?"timeout":"abort",as=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,r=e?.fetchImpl;if("function"==typeof t||"function"==typeof r)return{upload(n){if("function"==typeof t)return os(t,e,n);if("function"==typeof r)return(async(e,t,r)=>{const n=r.timeoutMs??t?.timeoutMs??3e4;let o=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,a=i&&Number.isFinite(n)?setTimeout(()=>{o=!0,i.abort()},n):void 0,c=((e,t)=>e??t?.signal)(r.signal,i);try{const t=ns(r),s=await e(r.url,{method:"POST",headers:r.headers,body:t,signal:c}),n=await s.text(),o=r.source.size;return"number"==typeof o&&r.onProgress?.({loaded:o,total:o,percent:o>0?100:void 0}),{status:s.status,body:n}}catch(d){const e=d instanceof Error&&"AbortError"===d.name;throw s.createPlatformError("Upload adapter execution failed.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!e,details:{reason:e?is(o):"network",url:r.url,cause:d instanceof Error?d.message:String(d)}})}finally{a&&clearTimeout(a)}})(r,e,n);throw s.createPlatformError("Upload adapter execution failed.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{reason:"missing-upload-runtime",url:n.url}})}}},cs=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append("file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw s.createPlatformError("React Native upload adapter only supports rn-uri source.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},ds=e=>{const t=e?.fetchImpl,r=e?.formDataCtor;if("function"==typeof t&&"function"==typeof r)return{async upload(n){const o=n.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let a=!1;const c=i&&Number.isFinite(o)?setTimeout(()=>{a=!0,i.abort()},o):void 0;try{const e=cs(r,n),s=await t(n.url,{method:"POST",headers:n.headers,body:e,signal:n.signal??i?.signal}),o=await s.text(),a=n.source.size;return"number"==typeof a&&n.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:s.status,body:o}}catch(d){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===s.PLATFORM_ERROR_CODE.UPLOAD_FAILED&&t.stage===s.PLATFORM_ERROR_STAGE.UPLOAD})(d))throw d;const e=d instanceof Error&&"AbortError"===d.name;throw s.createPlatformError("React Native upload adapter execution failed.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!e||a,details:{url:n.url,reason:e?a?"timeout":"abort":"network",cause:d instanceof Error?d.message:String(d)}})}finally{void 0!==c&&clearTimeout(c)}}}},ls=(e,t)=>e+t&4294967295,us=(e,t,s,r,n,o)=>{return ls((i=ls(ls(t,e),ls(r,o)))<<(a=n)|i>>>32-a,s);var i,a},hs=(e,t,s,r,n,o,i)=>us(t&s|~t&r,e,t,n,o,i),ps=(e,t,s,r,n,o,i)=>us(t&r|s&~r,e,t,n,o,i),ms=(e,t,s,r,n,o,i)=>us(t^s^r,e,t,n,o,i),gs=(e,t,s,r,n,o,i)=>us(s^(t|~r),e,t,n,o,i),fs=(e,t)=>{let[s,r,n,o]=e;s=hs(s,r,n,o,t[0]??0,7,-680876936),o=hs(o,s,r,n,t[1]??0,12,-389564586),n=hs(n,o,s,r,t[2]??0,17,606105819),r=hs(r,n,o,s,t[3]??0,22,-1044525330),s=hs(s,r,n,o,t[4]??0,7,-176418897),o=hs(o,s,r,n,t[5]??0,12,1200080426),n=hs(n,o,s,r,t[6]??0,17,-1473231341),r=hs(r,n,o,s,t[7]??0,22,-45705983),s=hs(s,r,n,o,t[8]??0,7,1770035416),o=hs(o,s,r,n,t[9]??0,12,-1958414417),n=hs(n,o,s,r,t[10]??0,17,-42063),r=hs(r,n,o,s,t[11]??0,22,-1990404162),s=hs(s,r,n,o,t[12]??0,7,1804603682),o=hs(o,s,r,n,t[13]??0,12,-40341101),n=hs(n,o,s,r,t[14]??0,17,-1502002290),r=hs(r,n,o,s,t[15]??0,22,1236535329),s=ps(s,r,n,o,t[1]??0,5,-165796510),o=ps(o,s,r,n,t[6]??0,9,-1069501632),n=ps(n,o,s,r,t[11]??0,14,643717713),r=ps(r,n,o,s,t[0]??0,20,-373897302),s=ps(s,r,n,o,t[5]??0,5,-701558691),o=ps(o,s,r,n,t[10]??0,9,38016083),n=ps(n,o,s,r,t[15]??0,14,-660478335),r=ps(r,n,o,s,t[4]??0,20,-405537848),s=ps(s,r,n,o,t[9]??0,5,568446438),o=ps(o,s,r,n,t[14]??0,9,-1019803690),n=ps(n,o,s,r,t[3]??0,14,-187363961),r=ps(r,n,o,s,t[8]??0,20,1163531501),s=ps(s,r,n,o,t[13]??0,5,-1444681467),o=ps(o,s,r,n,t[2]??0,9,-51403784),n=ps(n,o,s,r,t[7]??0,14,1735328473),r=ps(r,n,o,s,t[12]??0,20,-1926607734),s=ms(s,r,n,o,t[5]??0,4,-378558),o=ms(o,s,r,n,t[8]??0,11,-2022574463),n=ms(n,o,s,r,t[11]??0,16,1839030562),r=ms(r,n,o,s,t[14]??0,23,-35309556),s=ms(s,r,n,o,t[1]??0,4,-1530992060),o=ms(o,s,r,n,t[4]??0,11,1272893353),n=ms(n,o,s,r,t[7]??0,16,-155497632),r=ms(r,n,o,s,t[10]??0,23,-1094730640),s=ms(s,r,n,o,t[13]??0,4,681279174),o=ms(o,s,r,n,t[0]??0,11,-358537222),n=ms(n,o,s,r,t[3]??0,16,-722521979),r=ms(r,n,o,s,t[6]??0,23,76029189),s=ms(s,r,n,o,t[9]??0,4,-640364487),o=ms(o,s,r,n,t[12]??0,11,-421815835),n=ms(n,o,s,r,t[15]??0,16,530742520),r=ms(r,n,o,s,t[2]??0,23,-995338651),s=gs(s,r,n,o,t[0]??0,6,-198630844),o=gs(o,s,r,n,t[7]??0,10,1126891415),n=gs(n,o,s,r,t[14]??0,15,-1416354905),r=gs(r,n,o,s,t[5]??0,21,-57434055),s=gs(s,r,n,o,t[12]??0,6,1700485571),o=gs(o,s,r,n,t[3]??0,10,-1894986606),n=gs(n,o,s,r,t[10]??0,15,-1051523),r=gs(r,n,o,s,t[1]??0,21,-2054922799),s=gs(s,r,n,o,t[8]??0,6,1873313359),o=gs(o,s,r,n,t[15]??0,10,-30611744),n=gs(n,o,s,r,t[6]??0,15,-1560198380),r=gs(r,n,o,s,t[13]??0,21,1309151649),s=gs(s,r,n,o,t[4]??0,6,-145523070),o=gs(o,s,r,n,t[11]??0,10,-1120210379),n=gs(n,o,s,r,t[2]??0,15,718787259),r=gs(r,n,o,s,t[9]??0,21,-343485551),e[0]=ls(s,e[0]),e[1]=ls(r,e[1]),e[2]=ls(n,e[2]),e[3]=ls(o,e[3])},ys=(e,t)=>{const s=new Array(16).fill(0);for(let r=0;r<16;r+=1){const n=t+4*r;s[r]=(e[n]??0)|(e[n+1]??0)<<8|(e[n+2]??0)<<16|(e[n+3]??0)<<24}return s},Es=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},Rs=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)fs(t,ys(e,s));const r=new Array(16).fill(0);let n=0;for(;s<e.length;s+=1){const t=n>>2;r[t]=(r[t]??0)|(e[s]??0)<<n%4*8,n+=1}const o=n>>2;r[o]=(r[o]??0)|128<<n%4*8,n>55&&(fs(t,r),r.fill(0));const i=8*e.length;return r[14]=4294967295&i,r[15]=Math.floor(i/4294967296),fs(t,r),t.map(Es).join("")},Is=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 s.createPlatformError("Image decode capability is missing for current platform",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,r)=>{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),r(s.createPlatformError("Image decode failed",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"image load error"}}))},n.src=t})},vs=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw s.createPlatformError("Web image processor only supports web file source",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.file},Ss=()=>({async getImageInfo(e){const t=vs(e),s=await Is(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 r=vs(e),n=await Is(r);try{const r=((e,t,s)=>{const r=Math.min(e,t);if(r<=s)return{width:e,height:t};const n=s/r;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(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 s.createPlatformError("Canvas capability is missing for current platform",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),a=i.getContext("2d");if(!a)throw s.createPlatformError("Canvas 2d context is missing",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1});a.drawImage(n.image,0,0,r.width,r.height);const c="image/png"===(o=e.mimeType)||"image/webp"===o?o:"image/jpeg",d=await(async(e,t,r)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:r});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((n,o)=>{e.toBlob(e=>{e?n(e):o(s.createPlatformError("Image encode failed",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw s.createPlatformError("Canvas encode capability is missing for current platform",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,c,t.quality),l=(e=>e.name??"image")(e),u="undefined"!=typeof File?new File([d],l,{type:c,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??d,name:l,mimeType:c,size:u?.size??d.size},width:r.width,height:r.height,fileName:l,fileType:c,fileSize:u?.size??d.size,webFile:u}}finally{n.cleanup()}var o},async computeMd5(e){const t=vs(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw s.createPlatformError("Binary read capability is missing for current platform",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const n=new FileReader;n.onerror=()=>{r(s.createPlatformError("Binary read failed",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1}))},n.onload=()=>{n.result instanceof ArrayBuffer?t(n.result):r(s.createPlatformError("Binary read returned invalid result",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1}))},n.readAsArrayBuffer(e)})})(t);return Rs(new Uint8Array(r))}}),Cs=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)},Ts=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw s.createPlatformError("Miniapp image processor only supports miniapp path source",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{sourceType:e.sourceType}});return e.path},As=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw s.createPlatformError("Miniapp file system capability is missing",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{capability:"getFileSystemManager"}})},Os=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},bs=async(e,t)=>new Promise((s,r)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{r(e instanceof Error?e:new Error(Cs(e)))}})}).catch(e=>{throw s.createPlatformError("Miniapp image info read failed",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{src:t,cause:Cs(e)}})}),_s=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,Ms=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await bs(e,t);return _s(t,s)},Ns=e=>({async getImageInfo(t){const s=Ts(t),r=await bs(e,s),n=Os(r.type)??t.mimeType;return{width:r.width,height:r.height,mimeType:n,fileSize:t.size,isGif:"image/gif"===n}},async generateBigImage(t,r){const n=Ts(t);if("function"!=typeof e.compressImage)throw s.createPlatformError("Miniapp image compress capability is missing",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{capability:"compressImage"}});const o=await bs(e,n),i=_s(n,o),a=((e,t,s)=>{const r=Math.min(e,t);if(r<=s)return{width:e,height:t};const n=s/r;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(o.width,o.height,r.maxShortEdge),c=await new Promise((t,s)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:a.width,compressedHeight:a.height,success:e=>{e.tempFilePath?t(e.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(Cs(e)))}})}).catch(e=>{throw s.createPlatformError("Miniapp image compress failed",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{src:i,cause:Cs(e)}})}),d=await Ms(e,c),l=await bs(e,d),u=Os(l.type)??t.mimeType,h=await(async(e,t,r)=>{const n=As(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(Cs(e)))}})}).catch(e=>{throw s.createPlatformError("Miniapp file info read failed",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{filePath:t,cause:Cs(e)}})}):r})(e,d,t.size);return{source:{sourceType:"miniapp-path",path:d,name:t.name,mimeType:u,size:h},width:l.width,height:l.height,fileName:t.name,fileType:u,fileSize:h}},async computeMd5(t){const r=Ts(t),n=await Ms(e,r),o=await(async(e,t)=>{const r=As(e),n=await new Promise((e,s)=>{r.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{s(e instanceof Error?e:new Error(Cs(e)))}})}).catch(e=>{throw s.createPlatformError("Miniapp file read failed",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{filePath:t,cause:Cs(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 Rs(o)}}),Ds=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),ws=[/\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],Us=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},Ls=e=>{if(!e)return!1;const t=Us(e,"name");if(t&&Ds.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Us(e,"message"),Us(e,"errMsg")].some(e=>null!==e&&ws.some(t=>t.test(e)))},Ps=e=>{if(e instanceof Error)return e;const t=Us(e,"message")??Us(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},ks="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",xs=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Fs=e=>e===s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||e===s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,Bs=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),s=t.endsWith("==")?2:t.endsWith("=")?1:0,r=Math.max(0,Math.floor(3*t.length/4)-s),n=new Uint8Array(r);let o=0;for(let i=0;i<t.length;i+=4){const e=ks.indexOf(t[i]??""),s=ks.indexOf(t[i+1]??""),a=t[i+2]??"=",c=t[i+3]??"=",d="="===a?0:ks.indexOf(a),l="="===c?0:ks.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])o<r&&(n[o]=u>>t&255,o+=1)}return n.buffer},Gs=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),qs=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Ks=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Gs(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?Ks(s.data,t+1):e},Vs=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return qs(e);if(Gs(e))try{return qs(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return qs(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=Vs(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=Vs(s.buffer,t+1);if(!e)return;const r="number"==typeof s.byteOffset&&Number.isInteger(s.byteOffset)?s.byteOffset:0,n="number"==typeof s.byteLength&&Number.isInteger(s.byteLength)?s.byteLength:e.byteLength-r;if(r<0||n<0||r+n>e.byteLength)return;return e.slice(r,r+n)}},zs=(t,s)=>{if("string"==typeof t)return t;const r=t instanceof Uint8Array?t:new Uint8Array(t);if(Fs(s)){const n=(e=>{let t="";for(let s=0;s<e.length;s+=3){const r=e[s]??0,n=e[s+1],o=e[s+2],i=r<<16|(n??0)<<8|(o??0);t+=ks[i>>18&63],t+=ks[i>>12&63],t+=void 0===n?"=":ks[i>>6&63],t+=void 0===o?"=":ks[63&i]}return t})(r);return e.logger.warn("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:s,sourceType:t instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:r.byteLength,encodedCharacters:n.length,sourcePrefixHex:xs(r.subarray(0,8))}),n}const n=new ArrayBuffer(r.byteLength);return new Uint8Array(n).set(r),n},Hs=(e,t)=>"string"!=typeof e&&Fs(t),Ws=(t,s)=>{const r=Ks(t.data);if("string"==typeof r){if(!Fs(s))return r;const n=Bs(r),o=new Uint8Array(n);return e.logger.warn("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:s,sourceType:r===t.data?"string":"wrapped-string",sourceCharacters:r.length,decodedBytes:n.byteLength,decodedPrefixHex:xs(o.subarray(0,8)),decodedSuffixHex:xs(o.subarray(Math.max(0,o.length-8)))}),n}const n=Vs(r);if(!n){const n="object"==typeof t.data&&null!==t.data?t.data:void 0;return void e.logger.warn("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:s,sourceType:typeof r,sourceTag:Object.prototype.toString.call(t.data),sourceKeys:n?Object.keys(n).slice(0,10):[],isBuffer:t.isBuffer})}if(!Fs(s))return n.buffer;const o=(e=>{let t="";for(const r of e){if(9!==r&&10!==r&&13!==r&&32!==r&&!(r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||43===r||45===r||47===r||61===r||95===r))return;t+=String.fromCharCode(r)}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(!o)return e.logger.warn("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:s,sourceType:Object.prototype.toString.call(r),sourceBytes:n.byteLength,sourcePrefixHex:xs(n.subarray(0,8))}),n.buffer;const i=Bs(o),a=new Uint8Array(i);return e.logger.warn("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:s,sourceType:Object.prototype.toString.call(r),sourceBytes:n.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:xs(a.subarray(0,8)),decodedSuffixHex:xs(a.subarray(Math.max(0,a.length-8)))}),i},js=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Qs=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],$s=e=>e instanceof Error?e.message:js(e)&&"string"==typeof e.errMsg?e.errMsg:js(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),Ys=e=>e?{...e}:{},Js=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,Xs=e=>Js(e.statusCode)?e.statusCode:Js(e.status)?e.status:void 0,Zs=e=>{if(!js(e))return{};const t={};return Object.entries(e).forEach(([e,s])=>{"string"==typeof s&&(t[e]=s)}),t},er=e=>({...Zs(e.headers),...Zs(e.header)}),tr=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},sr=e=>{try{e.close()}catch{}},rr=(t,r)=>new Promise((n,o)=>{let i=!1,a=()=>{};const c=(e,t,n)=>{i||(i=!0,a(),o(s.createPlatformError(e,{code:s.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:s.PLATFORM_ERROR_STAGE.REQUEST,retryable:n,details:{url:r.url,method:"GET",cause:$s(t)}})))},d=t.downloadFile?.({url:r.url,header:Ys(r.headers),timeout:r.timeoutMs??15e3,success:s=>{const o=s.tempFilePath??s.apFilePath;o?((e,t)=>new Promise((s,r)=>{const n=e.getFileSystemManager?.();n?n.readFile({filePath:t,success:e=>{const t=Vs(e.data);t?s(t.buffer):r(new Error("downloaded file response is not binary"))},fail:r}):r(new Error("getFileSystemManager returned no file system manager"))}))(t,o).then(t=>{i||(i=!0,a(),e.logger.warn("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:r.url,filePathType:s.apFilePath?"apFilePath":"tempFilePath",status:s.statusCode??200,bytes:t.byteLength}),n({status:s.statusCode??200,headers:s.header??{},data:t}))}).catch(e=>{c("Mini program downloaded file read failed.",e,!1)}):c("Mini program download did not return a file path.",s,!1)},fail:e=>{c("Mini program file download failed.",e,!0)}});a=tr(r.signal,()=>{d?.abort(),c("Mini program file download aborted.","abort",!1)})}),nr=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((r,n)=>{let o=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:Ys(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{o();const i=Xs(e);void 0!==i?r({status:i,headers:er(e),data:e.data}):n(s.createPlatformError("Mini program request response status is invalid.",{code:s.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:s.PLATFORM_ERROR_STAGE.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{o(),n(s.createPlatformError("Mini program request failed.",{code:s.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:s.PLATFORM_ERROR_STAGE.REQUEST,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:$s(e)}}))}});o=tr(t.signal,()=>{i.abort(),n(s.createPlatformError("Mini program request aborted.",{code:s.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:s.PLATFORM_ERROR_STAGE.REQUEST,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):rr(e,t)}),or=(e,t)=>({connect:r=>new Promise((n,o)=>{let i,a,c=!1;const d=()=>{void 0!==a&&(clearTimeout(a),a=void 0)},l=(e,t,n)=>{c||(c=!0,d(),i&&sr(i),o(s.createPlatformError(t,{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:n,details:{url:r.url,cause:$s(e)}})))},u=e=>{if(!(Qs(r=e,"send")&&Qs(r,"close")&&Qs(r,"onOpen")&&Qs(r,"onMessage")&&Qs(r,"onError")&&Qs(r,"onClose")))return void l(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var r;const o=e;if(c)return void sr(o);i=o;const a=()=>{o.offOpen?.(u),o.offError?.(h)},u=()=>{c?sr(o):(c=!0,d(),a(),n(((e,t,r=s.SOCKET_READY_STATE.CONNECTING)=>{const n=new Set,o=new Set,i=new Set,a=new Set;let c=r;return e.onOpen(()=>{c=s.SOCKET_READY_STATE.OPEN,n.forEach(e=>{e()})}),e.onMessage(e=>{const s=Ws(e,t);void 0!==s&&o.forEach(e=>{e(s)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{c=s.SOCKET_READY_STATE.CLOSED,a.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return c},send(r){if(c!==s.SOCKET_READY_STATE.OPEN)throw s.createPlatformError("Mini program socket is not open.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{readyState:c}});return new Promise((n,o)=>{e.send({data:zs(r,t),...Hs(r,t)?{isBuffer:!0}:{},success:n,fail:e=>{o(s.createPlatformError("Mini program socket send failed.",{code:s.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:s.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{cause:$s(e)}}))}})})},close(t,r){c=s.SOCKET_READY_STATE.CLOSING,e.close({code:t,reason:r})},onOpen:e=>(n.add(e),()=>{n.delete(e)}),onMessage:e=>(o.add(e),()=>{o.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(a.add(e),()=>{a.delete(e)})}})(o,t,s.SOCKET_READY_STATE.OPEN)))},h=e=>{a(),l(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};o.onOpen(u),o.onError(h)};let h;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(a=setTimeout(()=>{l("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{h=e.connectSocket({url:r.url,...t===s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(r.protocols)?[...r.protocols]:"string"==typeof r.protocols?[r.protocols]:void 0,fail:e=>{l(e,"Mini program socket connect failed.",!0)}})}catch(m){return void l(m,"Mini program socket creation failed.",!0)}var p;"object"!=typeof(p=h)||null===p||"function"!=typeof p.then?u(h):Promise.resolve(h).then(e=>u(e),e=>l(e,"Mini program socket connect failed.",!0))})}),ir=e=>({upload:t=>new Promise((r,n)=>{const o=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw s.createPlatformError("Mini program upload only supports miniapp-path source.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const a=e.uploadFile({url:t.url,filePath:o.path,name:"file",header:Ys(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i();const a=Xs(e);void 0!==a?r({status:a,body:e.data}):n(s.createPlatformError("Mini program upload response status is invalid.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{url:t.url,path:o.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),n(s.createPlatformError("Mini program upload failed.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!0,details:{url:t.url,path:o.path,cause:$s(e)}}))}});a.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=tr(t.signal,()=>{a.abort(),n(s.createPlatformError("Mini program upload aborted.",{code:s.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:s.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{url:t.url,path:o.path,reason:"abort"}}))})})}),ar=(e,t)=>{const r=(e=>e===s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||e===s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP)(t);return{async getItem(t){if(Qs(e,"getStorageSync"))try{const s=(e=>js(e)&&"data"in e?e.data:e)(e.getStorageSync(r?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return Qs(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(Qs(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(Ls(n))throw Ps(n)}else if(Qs(e,"setStorage"))return new Promise((r,o)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{Ls(e)?o(Ps(e)):r()}})}catch(n){if(Ls(n))return void o(Ps(n));r()}})},async removeItem(t){if(Qs(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(Qs(e,"removeStorage"))return new Promise(s=>{try{e.removeStorage({key:t,success:s,fail:()=>{s()}})}catch{s()}})}}},cr=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>Qs(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 Qs(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),Qs(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{Qs(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},r=()=>{t(!1)};return Qs(e,"onAppShow")&&e.onAppShow(s),Qs(e,"onAppHide")&&e.onAppHide(r),t(!0),()=>{Qs(e,"offAppShow")&&e.offAppShow(s),Qs(e,"offAppHide")&&e.offAppHide(r)}}}),dr=(e,t=s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,r=t)=>{const n=(e=>{if(Qs(e,"request")&&Qs(e,"connectSocket")&&Qs(e,"uploadFile"))return e;throw s.createPlatformError("Mini program platform capability is missing.",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),o="function"==typeof n.getImageInfo?Ns(n):void 0;return{request:nr(n),socket:or(n,r),upload:ir(n),runtime:cr(n,t),storage:ar(n,r),imageProcessor:o}},lr=[s.RUNTIME_PLATFORMS.WEB,s.RUNTIME_PLATFORMS.ELECTRON_RENDERER,s.RUNTIME_PLATFORMS.REACT_NATIVE],ur=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},hr=e=>lr.includes(e),pr=(e,t)=>e!==s.RUNTIME_PLATFORMS.UNIAPP?hr(e):!At(t)&&!gr(t)&&vt(t),mr=e=>ur(e,"getImageInfo")&&ur(e,"getFileSystemManager"),gr=e=>!At(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),fr=(e,t)=>{if(hr(e)&&e!==s.RUNTIME_PLATFORMS.REACT_NATIVE)return Ss();if(Mt(e)&&mr(t))return Ns(t);if(e===s.RUNTIME_PLATFORMS.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(vt(e))return Ss();if(mr(e.uni))return Ns(e.uni);if(mr(e.wx))return Ns(e.wx)}},yr=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=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())}},Er=(e,t,r,n)=>{if(e===s.RUNTIME_PLATFORMS.UNIAPP&&gr(r)&&void 0!==r.uni&&ft(r.uni))return{...dr(r.uni,e,t),proto:jt()};if(((e,t)=>!pr(e,t)&&Mt(e))(e,r)&&ft(n))return{...dr(n,e,t),proto:jt()};const o=r.XMLHttpRequest,i=pr(e,r),a=i?$t({fetchImpl:r.fetch}):void 0,c=i?ss({webSocketCtor:r.WebSocket}):void 0,d=e===s.RUNTIME_PLATFORMS.REACT_NATIVE?ds({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?as({xhrFactory:"function"==typeof o?()=>new o:void 0,fetchImpl:r.fetch}):void 0,l=i&&e!==s.RUNTIME_PLATFORMS.REACT_NATIVE?(u={platform:e,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const s=()=>{e(!0)},r=()=>{e(!1)};return t.addEventListener("online",s),t.addEventListener("offline",r),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",s),t.removeEventListener("offline",r)}},onAppVisibilityChange(e){const t=u.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 u;return{request:a,upload:d,socket:c,runtime:l,proto:jt(),storage:yr(r),imageProcessor:i&&e!==s.RUNTIME_PLATFORMS.REACT_NATIVE?Ss():fr(e,n)}},Rr=(e,t)=>{if(void 0!==e)return e;throw s.createPlatformError("Platform adapter initialization failed.",{code:s.PLATFORM_ERROR_CODE.INIT_FAILED,stage:s.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{capability:t}})},Ir=t=>{const s=e.getRuntimeGlobal(t?.runtimeInput),r=_t(s,t?.prefer),n=r.platform,o=Er(n,r.hostPlatform,s,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(t?.overrides,o),a={...o,...i},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);Dt(c);return{platform:n,platformId:n,capability:c,request:Rr(a.request,"request"),upload:Rr(a.upload,"upload"),socket:Rr(a.socket,"socket"),runtime:Rr(a.runtime,"runtime"),proto:Rr(a.proto,"proto"),storage:Rr(a.storage,"storage"),imageProcessor:a.imageProcessor}},vr={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Sr{constructor(e={}){this.attemptCount=0,this.config={...vr,...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 t=this.getRetryDelay();return e.logger.debug(`Waiting ${t}ms before retry (attempt ${this.attemptCount})`),new Promise(e=>setTimeout(e,t))}}const Cr={interval:3e4,timeout:6e4},Tr="function"==typeof TextDecoder?new TextDecoder:null;class Ar{constructor(t={}){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=t=>{const s=this.extractMessageText(t);if(!s)return;const r=this.parseJson(s);if(!Ar.isRecord(r))return;"pong"===Ar.readString(r.type)&&(this.markAlive(),e.logger.debug("Pong received"))},this.config={...Cr,...t}}start(t,s,r){this.heartbeatTimer&&this.stop(),this.attachWebSocket(t),this.onTimeoutCallback=s||null,this.sendPing=r??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),e.logger.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),e.logger.debug("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===s.SOCKET_READY_STATE.OPEN)try{if(this.sendPing)this.sendPing();else{const t=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(t)).catch(t=>{e.logger.error("Failed to send ping:",t),this.resolveProbe(!1)})}this.resetTimeout(),e.logger.debug("Ping sent")}catch(t){e.logger.error("Failed to send ping:",t),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)?Tr?.decode(t)??ht(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(()=>{e.logger.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(t,r){try{if(t.readyState!==s.SOCKET_READY_STATE.OPEN)return!1;this.attachWebSocket(t);const e=r??this.config.timeout;return await new Promise(t=>{const s=setTimeout(()=>{this.removeProbeResolver(t),t(!1)},e);this.probeResolvers.push(e=>{clearTimeout(s),t(e)}),this.sendPingInternal()})}catch(n){return e.logger.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 Or=null;function br(){return Or||(Or=Wt()),Or}const _r="websdk2:device-info",Mr="webim",Nr="web",Dr=t=>{const s=Date.now(),r=t.deviceId,n=t.customOSPlatform,o=void 0!==n?t.customDeviceName:void 0,i=e.getRuntimeGlobal().localStorage,a=()=>{if(!i)return null;try{const t=i.getItem(_r);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(i)try{i.setItem(_r,JSON.stringify(e))}catch{}},d=e=>void 0===n?e:{deviceId:`custom${n}_${e.deviceUuid}`,deviceName:o??r,deviceUuid:e.deviceUuid};if(t.useFixedDeviceId){const e=a();if(e)return d(e);if(r===Mr){const e=`${Nr}_${s}`,t=d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return c(t),t}if(void 0!==n){const e=d({deviceId:`webim_${Nr}_${r}`,deviceName:r,deviceUuid:`${Nr}_${s}`});return c(e),e}const t={deviceId:`webim_${Nr}_${r}`,deviceName:`webim_${Nr}_${r}`,deviceUuid:`webim_${Nr}_${r}`};return c(t),t}if(r===Mr){const e=`random_${Nr}_${s}`;return d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==n){return d({deviceId:`webim_${Nr}_${r}`,deviceName:r,deviceUuid:`random_${Nr}_${s}`})}return{deviceId:`webim_${Nr}_${r}`,deviceName:`webim_${Nr}_${r}`,deviceUuid:`webim_${Nr}_${r}`}},wr=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Ur=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 r.Long(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Lr=e=>{const t=[];for(const[s,r]of Object.entries(e))if(void 0!==r)if("boolean"!=typeof r)if("number"!=typeof r)if("string"!=typeof r)try{t.push({key:s,type:$e,stringValue:JSON.stringify(r)})}catch{t.push({key:s,type:Qe,stringValue:Object.prototype.toString.call(r)})}else t.push({key:s,type:Qe,stringValue:r});else Number.isInteger(r)?t.push({key:s,type:Ve,varintValue:r}):t.push({key:s,type:je,doubleValue:r});else t.push({key:s,type:Ke,varintValue:r?1:0});return t},Pr=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 r="number"==typeof s.type?s.type:Qe;if(r!==Ke)if(r!==Ve&&r!==ze&&r!==He)if(r!==We)if(r!==je){if(r!==$e)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},kr=new Set(["mute"]),xr={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},Fr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Br=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Gr=(e,t)=>{const s=e?.map(e=>Fr(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},qr=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=Br(t);if(!r)return;const n=r.muteExpire??r.mute_expire??r.expire??r.expired??r.expireAt??r.expiredAt,o=Number(n);return Number.isFinite(o)&&o>0?o:void 0},Kr=e=>{const t=Br(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=xr[r];if(!e)continue;let t=n;if(kr.has(r))t=!0===n||"true"===n;else if("max_users"===r){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},Vr=e=>{const t=Br(e);if(!t)return{attributes:{},keyList:[]};const s=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},r=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Array.isArray(s.successKeys)?s.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(n.map(e=>[e,r[e]]).filter(e=>"string"==typeof e[1])),keyList:n,from:Fr(t.operator)??Fr(t.username)}},zr=(e,t)=>({eventName:e,payload:t}),Hr=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=Fr(e.from?.name),r=(n=e.to,Fr(n?.[0]?.name));var n;switch(e.operation){case 1:return zr(E,t);case 10:return zr(v,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:r??s});case 17:return zr(R,{...t,memberIds:Gr(e.members,s),ext:e.ext??e.eventExt});case 18:return zr(I,{...t,memberIds:Gr(e.members,s)});case 20:return zr(M,{...t,oldOwnerId:s,newOwnerId:r});case 21:return zr(b,{...t,adminId:r??s});case 22:return zr(_,{...t,adminId:r??s});case 23:{const s=(e=>{const t=Br(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const r={};for(const[n,o]of Object.entries(s)){const e=Number(o);n&&Number.isFinite(e)&&(r[n]=e)}return Object.keys(r).length>0?r:null})(e.ext??e.eventExt),n=s?Object.keys(s):Gr(e.members,r),o=46388736e5;return zr(S,{...t,userIds:n,muteMembers:s??Object.fromEntries(n.map(e=>[e,o])),muteExpire:qr(e.reason,e.eventExt)??o})}case 24:return zr(C,{...t,userIds:Gr(e.members,r)});case 25:return zr(N,{...t,announcement:e.reason??""});case 26:return zr(N,{...t,announcement:""});case 29:return zr(T,{...t,userIds:Gr(e.members,r)});case 30:return zr(A,{...t,userIds:Gr(e.members,r)});case 31:return zr(O,{...t,isMuted:!0});case 32:return zr(O,{...t,isMuted:!1});case 14:return zr(D,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Kr(e.eventExt)});case 43:{const r=Vr(e.eventExt);return zr(w,{...t,attributes:r.attributes,from:r.from??s})}case 44:{const r=Vr(e.eventExt);return zr(U,{...t,keyList:r.keyList,from:r.from??s})}default:return null}},Wr=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),jr={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Qr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},$r=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Yr=(e,t)=>{const s=e?.map(e=>Qr(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Jr=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=$r(t);if(!r)return;const n=r.muteExpire??r.mute_expire??r.expire??r.expired??r.expireAt??r.expiredAt,o=Number(n);return Number.isFinite(o)&&o>0?o:void 0},Xr=e=>{const t=$r(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=jr[r];if(!e)continue;let t=n;if(Wr.has(r))t=!0===n||"true"===n;else if("max_users"===r){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},Zr=(e,t)=>{const s=$r(t)??$r(e);return i.normalizeGroupSharedFile(s??void 0)??void 0},en=(e,t)=>{const s=$r(t)??$r(e);return Qr(s?.fileId)??Qr(s?.file_id)??Qr(e)??""},tn=(e,t)=>({eventName:e,payload:t}),sn=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=Qr(e.from?.name),r=(n=e.to,Qr(n?.[0]?.name));var n;switch(e.operation){case 4:return tn(o.GroupEventName.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return tn(o.GroupEventName.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return tn(o.GroupEventName.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:r,reason:e.reason});case 7:return tn(o.GroupEventName.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return tn(o.GroupEventName.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return tn(o.GroupEventName.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return tn(o.GroupEventName.USER_REMOVED,t);case 1:return tn(o.GroupEventName.GROUP_DESTROYED,t);case 19:return tn(o.GroupEventName.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=$r(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const r={};for(const[n,o]of Object.entries(s)){const e=Qr(n),t=Number(o);e&&Number.isFinite(t)&&t>0&&(r[e]=t)}return Object.keys(r).length>0?r:null})(e.ext),n=s?Object.keys(s):Yr(e.members,r);return tn(o.GroupEventName.MUTE_LIST_ADDED,{...t,userIds:n,muteExpire:n.map(e=>s?.[e]).find(e=>void 0!==e)??Jr(e.reason,e.eventExt)})}case 24:return tn(o.GroupEventName.MUTE_LIST_REMOVED,{...t,userIds:Yr(e.members,r)});case 29:return tn(o.GroupEventName.ALLOW_LIST_ADDED,{...t,userIds:Yr(e.members,r)});case 30:return tn(o.GroupEventName.ALLOW_LIST_REMOVED,{...t,userIds:Yr(e.members,r)});case 31:return tn(o.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return tn(o.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return tn(o.GroupEventName.ADMIN_ADDED,{...t,administratorId:r??s});case 22:return tn(o.GroupEventName.ADMIN_REMOVED,{...t,administratorId:r??s});case 20:return tn(o.GroupEventName.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:r});case 17:{const r=Yr(e.members,s);return tn(o.GroupEventName.MEMBERS_JOINED,{...t,memberIds:r})}case 18:{const r=Yr(e.members,s);return tn(o.GroupEventName.MEMBERS_EXITED,{...t,memberIds:r})}case 25:return tn(o.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return tn(o.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return tn(o.GroupEventName.SHARED_FILE_ADDED,{...t,sharedFile:Zr(e.reason,e.eventExt)});case 28:return tn(o.GroupEventName.SHARED_FILE_DELETED,{...t,fileId:en(e.reason,e.eventExt)});case 14:return tn(o.GroupEventName.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:Xr(e.eventExt)});case 41:return tn(o.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return tn(o.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const r=(e=>{const t=$r(e);if(!t)return{attribute:{}};const s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},r=Object.fromEntries(Object.entries(s).filter(e=>"string"==typeof e[1]));return{userId:Qr(t.username),attribute:r}})(e.eventExt);return tn(o.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:r.userId,attribute:r.attribute,from:s,source:e.source??"direct"})}default:return null}},rn=new WeakMap,nn=(e,t)=>{rn.set(e,t)},on=e=>rn.get(e)??null,an=(e,t)=>{const s=on(e);s&&nn(t,s)},cn=new WeakMap,dn=e=>cn.get(e),ln="singleChat",un="groupChat",hn=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},pn=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}},mn=e=>{if(!Array.isArray(e))return;const t=e.map(e=>hn(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},gn=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),fn=(...e)=>{for(const t of e){const e=hn(t);if(e)return e}},yn=(e,t)=>Boolean(e&&t&&e===t),En=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),Rn=(e,t,s)=>{const r=mn(e);if(r&&r.length>0)return r;const n=(t??[]).map(e=>hn(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const o=hn(s?.name);return o?[o]:[]},In=e=>{const t=pn(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}}},vn=(t,s)=>{const r=fn(t.to?.[0]?.clientResource);if(1!==t.to?.length||hn(t.to[0]?.name)!==s.userId||!En(s.userId,r,s))return null;const n=(o=t.from,hn(o?.name)??"");var o;if(!n)return e.logger.warn("Discarded MultiDevice contact event without target user",{operation:t.operation}),null;const i=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice contact operation",{operation:t}),"UNKNOWN"}})(t.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:n,rosterVersion:t.rosterVersion,ext:t.ext,deviceId:r,timestamp:t.timestamp,raw:t.raw}},Sn=(t,s)=>{if(!t.groupId)return e.logger.warn("Discarded MultiDevice group event without groupId",{operation:t.operation}),null;const r=fn(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!En(hn(t.from?.name),r,s))return null;const n=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice group operation",{operation:t}),"UNKNOWN"}})(t.operation);if("UNKNOWN"===n)return null;const o=Rn(t.members,t.to,t.from);return{category:"group",operation:n,groupId:t.groupId,userIds:o.length>0?o:void 0,operatorId:hn(t.from?.name),groupName:t.groupName,deviceId:r,timestamp:t.timestamp,raw:t.raw}},Cn=(t,s)=>{if(!t.threadId)return e.logger.warn("Discarded MultiDevice thread event without threadId",{operation:t.operation}),null;const r=fn(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!En(hn(t.from?.name),r,s))return null;const n=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice thread operation",{operation:t}),"UNKNOWN"}})(t.operation);if("UNKNOWN"===n)return null;const o=Rn(t.members,t.to,t.from);return{category:"thread",operation:n,threadId:t.threadId,parentId:t.parentId,userIds:o.length>0?o:void 0,operatorId:hn(t.from?.name),threadName:t.threadName,deviceId:r,timestamp:t.timestamp,raw:t.raw}},Tn=(t,s)=>{if("pin"===t.operation||"pin_delete"===t.operation)return null;const r=fn(t.res,t.raw?.resource,t.raw?.clientResource);if(yn(r,s.clientResource))return e.logger.debug("Discarded same-device MultiDevice conversation echo",{operation:t.operation,conversationId:t.id}),null;const n="chat"===(o=t.type)||"singleChat"===o?ln:un;var o;const i=hn(t.id)??(n===ln?hn(t.from):void 0);if(!i)return e.logger.warn("Discarded MultiDevice conversation event without conversationId",{operation:t.operation}),null;const a=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice conversation operation",{operation:t}),"UNKNOWN"}})(t.operation);return"UNKNOWN"===a?null:{category:"conversation",operation:a,conversationId:i,conversationType:n,mark:"mark"===t.operation||"mark_delete"===t.operation?In(t.ext):void 0,operatorId:hn(t.from),deviceId:r,timestamp:pn(t.ts),raw:t.raw}},An=(t,s)=>{const r=fn(t.resource,t.raw?.resource,t.raw?.clientResource);if(yn(r,s.clientResource))return e.logger.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:t.to}),null;const n=hn(t.to);if(!n)return e.logger.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const o=hn(t.lastMsgId),i=mn(t.msgIdList)??(o?[o]:void 0),a=pn(t.deleteTime);if(!i&&void 0===a)return e.logger.warn("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:n}),null;const c=(t=>t&&"deleteRoaming"!==t&&"MESSAGE_REMOVED"!==t?(e.logger.warn("Discarded unknown MultiDevice message-removed operation",{operation:t}),"UNKNOWN"):"MESSAGE_REMOVED")(t.messageRoamingType);return"UNKNOWN"===c?null:{category:"messageRemoved",operation:c,conversationId:n,conversationType:"groupchat"===t.chatType||"groupChat"===t.chatType?un:ln,messageIds:i,beforeTimestamp:a,deviceId:r,raw:t.raw}},On=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var bn=4096,_n=65547,Mn=15,Nn=2113929216,Dn=65536,wn=65536,Un=10485760,Ln={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Pn={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function kn(e){if(!(e>0))return wn;if(e<=wn)return wn;if(e>1073741823)return e;for(var t=wn;t<e;)t*=2;return t}var xn={byU16:0,byU32:1},Fn=0,Bn=1,Gn=2,qn=0,Kn=1;function Vn(e,t){return e[t]|e[t+1]<<8}function zn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Hn(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var Wn="fast";function jn(e){return 2654435761*(e>>>0)>>>20&4095}function Qn(e){return 2654435761*(e>>>0)>>>19&8191}function $n(e,t,s){if("fast"===Wn){var r=zn(e,t);return s===xn.byU16?Qn(r):jn(r)}throw new Error("Unsupported hash strategy: "+Wn)}function Yn(e,t,s,r,n){s[t]=e-n}function Jn(e,t,s,r,n){Yn(t,$n(e,t,r),s,0,n)}function Xn(e,t,s,r){return t[e]+r}function Zn(e,t,s,r,n){return Xn($n(e,t,r),s,0,n)}function eo(e,t,s,r){for(var n=t;t<r-3;){if(zn(e,t)!==zn(e,s)){for(;t<r&&e[t]===e[s];)t++,s++;return t-n}t+=4,s+=4}for(;t<r&&e[t]===e[s];)t++,s++;return t-n}function to(e,t,s,r,n,o,i,a,c,d){var l,u,h,p=e.hashTable,m=r,g=m-e.dictSize,f=e.dictionary,y=e.dictionaryStart,E=y+e.dictSize,R=e.dictSize>0?E-r:0,I=r,v=r+n,S=v-12,C=v-5,T=0,A=o>0?o:s.length,O=0;if(n>Nn)return 0;switch(c){case Fn:default:l=r,u=r;break;case Bn:l=r-e.currentOffset,u=r-e.dictSize;break;case Gn:l=r-e.currentOffset,u=r}if(a===xn.byU16&&n>=_n)return 0;if(n<13)return no(t,s,I,v,T,A,i);Jn(t,m,p,a,l),h=$n(t,++m,a);e:for(;;){var b,_,M=m,N=1,D=64;do{var w=h;if(m=M,M+=N,N=D++>>>6,M>S)return no(t,s,I,v,T,A,i);b=Xn(w,p,0,l),c===Gn&&(b<r?(O=R,u=y):(O=0,u=r)),h=$n(t,M,a),Yn(m,w,p,0,l)}while(d===Kn&&b<g||a!==xn.byU16&&b+65535<m||!so(t,f,m,b,O,c,r));for(;m>I&&b+O>u;){var U=b+O-1;if(t[m-1]!==(c===Gn&&b<r?f[U-y+e.dictionaryStart]:t[U]))break;m--,b--}var L=m-I;if(_=T++,i&&T+L+8+Math.floor(L/255)>A)return 0;if(L>=Mn){var P=L-Mn;for(s[_]=240;P>=255;)s[T++]=255,P-=255;s[T++]=P}else s[_]=L<<4;if(L>=16&&s.set&&t.subarray)s.set(t.subarray(I,I+L),T),T+=L;else for(var k=0;k<L;k++)s[T++]=t[I+k];t:for(;;){var x;if(Hn(s,T,m-b),T+=2,c===Gn&&b<r){var F=m+(E-(b+O));if(F>C&&(F=C),(m+=4+(x=ro(t,f,m+4,b+O+4-y+e.dictionaryStart,F,E-y)))===F&&F<C){var B=eo(t,m,r,C);x+=B,m+=B}}else m+=4+(x=eo(t,m+4,b+4,C));if(i&&T+6+(x>>>8)>A)return 0;if(x>=15){for(s[_]+=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[_]+=x;if(I=m,m>S)break e;if(Jn(t,m-2,p,a,l),b=Zn(t,m,p,a,l),c===Gn&&(b<r?(O=R,u=y):(O=0,u=r)),Jn(t,m,p,a,l),!((d!==Kn||b>=g)&&b+65535>=m&&so(t,f,m,b,O,c,r)))break t;s[_=T++]=0}h=$n(t,++m,a)}return no(t,s,I,v,T,A,i)}function so(e,t,s,r,n,o,i){var a,c=zn(e,s);o===Gn&&r+n<i?a=zn(t,r+n):a=zn(e,r+n);return c===a}function ro(e,t,s,r,n,o,i){for(var a=s;r<o&&s<n&&t[r]===e[s];)r++,s++;return s-a}function no(e,t,s,r,n,o,i){var a=r-s;if(i&&n+a+1+Math.floor((a+255-Mn)/255)>o)return 0;if(a>=Mn){for(t[n++]=240,a-=Mn;a>=255;)t[n++]=255,a-=255;t[n++]=a}else t[n++]=a<<4;var c=s,d=r,l=d-c;if(l>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),n),n+=l;else for(var u=c;u<d;u++)t[n++]=e[u];return n}function oo(e,t,s,r){var n,o=0;if(r&&t.ip>=s)return-1;do{if(o+=n=e[t.ip++],t.ip>s)return-1;if(o>2147483647)return-1}while(255===n);return o}function io(e,t,s,r,n,o,i,a,c,d,l,u,h){if(null==e)return-1;if(o<0)return-1;var p=s,m=s+r,g=n,f=n+o,y=l-h,E=u+h,R=h<65536;if(0===o)return 1===r&&0===e[p]?0:-1;if(0===r)return-1;for(;;){var I,v,S,C;if(p>=m)return-(p-s)-1;if((v=(I=e[p++])>>>4)===Mn){var T=oo(e,b={ip:p},m-Mn,!0);if(p=b.ip,-1===T)return-(p-s)-1;if(g+(v+=T)<g)return-(p-s)-1;if(p+v<p)return-(p-s)-1}if(S=g+v,i&&(S>f-12||p+v>m-8)||!i&&S>f-8){if(!i&&S!==f)return-(p-s)-1;if(i&&(p+v!==m||S>f))return-(p-s)-1;if(v>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+v),g);else for(var A=0;A<v;A++)t[g+A]=e[p+A];p+=v,g+=v;break}if(v>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+v),g);else for(A=0;A<v;A++)t[g+A]=e[p+A];if(g=S,(p+=v)+2>m)return-(p-s)-1;var O=Vn(e,p);if(p+=2,C=S-O,R&&C+h<l)return-(p-s)-1;if(0===O)return-(p-s)-1;if(15===(v=15&I)){var b;T=oo(e,b={ip:p},m-5+1,!1);if(p=b.ip,-1===T)return-(p-s)-1;if(g+(v+=T)<g)return-(p-s)-1}if(v+=4,d===Gn&&C<l){if(g+v>f-5)return-(p-s)-1;if(v<=l-C){var _=E-(l-C);for(A=0;A<v;A++)t[g+A]=t[_+A];g+=v}else{var M=l-C;for(_=E-M,A=0;A<M;A++)t[g+A]=t[_+A];var N=v-M;if(N>(g+=M)-l)for(var D=l,w=g+N;g<w;)t[g++]=t[D++];else{for(A=0;A<N;A++)t[g+A]=t[l+A];g+=N}}}else{if(C<y)return-(p-s)-1;if(S=g+v,g-C<8)for(t[g]=t[C],t[g+1]=t[C+1],t[g+2]=t[C+2],t[g+3]=t[C+3],g+=4,C+=4;g<S;)t[g++]=t[C++];else for(;g<S;)t[g++]=t[C++]}}return i?g-n:p-s}function ao(){return{hashTable:new Uint32Array(bn),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function co(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function lo(e,t,s,r,n,o,i,a){r=r||0;var c=e.dictionaryStart+e.dictSize,d=r;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,r=0;r<e.hashTable.length;r++)e.hashTable[r]<t?e.hashTable[r]=0:e.hashTable[r]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=s-e.dictSize}}(e);var l,u=r+n;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?Kn:qn;return e.dictionary&&c===r?(l=to(e,t,s,r,n,i||0,a||!1,xn.byU32,Bn,h),e.dictSize+=n,e.currentOffset+=n,l):(l=to(e,t,s,r,n,i||0,a||!1,xn.byU32,Gn,h),e.dictionary=t,e.dictionaryStart=r,e.dictSize=n,e.currentOffset+=n,l)}function uo(e,t,s,r){var n=e.dictionaryStart+e.dictSize;r>65536&&(r=65536),r>e.dictSize&&(r=e.dictSize);var o=n-r;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(o,o+r),s);else for(var i=0;i<r;i++)t[s+i]=e.dictionary[o+i];return e.dictionary=t,e.dictionaryStart=s,e.dictSize=r,r}function ho(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function po(e,t,s,r){return e.prefixSize=r,e.prefixEnd=s+r,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function mo(e,t,s,r,n,o,i){var a;if(e.prefixEnd===o){if((a=io(t,s,r,n,o,i,!0,0,0,Gn,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=io(t,s,r,n,o,i,!0,0,0,Gn,o,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=o+a}return a}function go(e){var t=(e=e||{}).minWorkArea||wn,s=e.maxWorkArea||Un,r=e.shrinkThreshold||t;t<wn&&(t=wn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=Dn+t,this.maxBufferSize=Dn+s,this.shrinkThreshold=Dn+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ln.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=ao()}function fo(e){var t=(e=e||{}).minWorkArea||wn,s=e.maxWorkArea||Un,r=e.shrinkThreshold||t;t<wn&&(t=wn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=Dn+t,this.maxBufferSize=Dn+s,this.shrinkThreshold=Dn+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ln.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}go.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<Dn?this.offset:Dn,n=this.offset>Dn?this.offset-Dn:0;t.set(this.ringBuffer.subarray(n,n+r),0),uo(this.stream,t,0,r),s=r}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},go.prototype.compress=function(e,t){var s=e.length;if(s<=0)return Pn.PARAM_ERROR;if(s>this.maxBufferSize-Dn)return Pn.PARAM_ERROR;if(s>this.ringBufferSize-Dn){var r=kn(s),n=Dn+r;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Pn.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(uo(this.stream,this.ringBuffer,0,Dn),this.offset=Dn);var o=this.offset;this.ringBuffer.set(e,o);var i=lo(this.stream,this.ringBuffer,t,o,s,0,t.length,!0);return i<=0?Pn.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),i)},go.prototype.reset=function(){this.offset=0,co(this.stream)},go.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},go.prototype._tryAutoShrink=function(){this.shrinkMode!==Ln.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ln.AUTO_IMMEDIATE||this.shrinkMode===Ln.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},go.prototype.getWorkArea=function(){return this.ringBufferSize-Dn},go.prototype.getRingBufferSize=function(){return this.ringBufferSize},go.prototype.getBaseBufferSize=function(){return this.minBufferSize},go.prototype.getMaxBufferSize=function(){return this.maxBufferSize},go.prototype.getCurrentOffset=function(){return this.offset},go.prototype.getShrinkMode=function(){return this.shrinkMode},go.prototype.setShrinkMode=function(e){this.shrinkMode=e},go.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},go.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Dn,s=this.maxBufferSize-Dn;if(e<t||e>s)return Pn.PARAM_ERROR;this.shrinkThreshold=Dn+e},fo.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<Dn?this.offset:Dn,n=this.offset>Dn?this.offset-Dn:0;t.set(this.ringBuffer.subarray(n,n+r),0),s=r,po(this.streamDecode,0,0,r)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},fo.prototype.decompress=function(e,t,s){var r=e.length;if(r<=0||s<=0)return Pn.PARAM_ERROR;if(s>this.maxBufferSize-Dn)return Pn.PARAM_ERROR;if(s>this.ringBufferSize-Dn){var n=kn(s),o=Dn+n;if(o>this.maxBufferSize&&(o=this.maxBufferSize),!this._resizeBuffer(o))return Pn.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var i=this.offset-Dn;i>0&&this.ringBuffer.set(this.ringBuffer.subarray(i,i+Dn),0),po(this.streamDecode,this.ringBuffer,0,Dn),this.offset=Dn}var a=mo(this.streamDecode,e,this.ringBuffer,0,r,this.offset,s);return a<=0?Pn.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},fo.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},fo.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},fo.prototype._tryAutoShrink=function(){this.shrinkMode!==Ln.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ln.AUTO_IMMEDIATE||this.shrinkMode===Ln.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},fo.prototype.getWorkArea=function(){return this.ringBufferSize-Dn},fo.prototype.getRingBufferSize=function(){return this.ringBufferSize},fo.prototype.getBaseBufferSize=function(){return this.minBufferSize},fo.prototype.getMaxBufferSize=function(){return this.maxBufferSize},fo.prototype.getCurrentOffset=function(){return this.offset},fo.prototype.getShrinkMode=function(){return this.shrinkMode},fo.prototype.setShrinkMode=function(e){this.shrinkMode=e},fo.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},fo.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Dn,s=this.maxBufferSize-Dn;if(e<t||e>s)return Pn.PARAM_ERROR;this.shrinkThreshold=Dn+e};const yo={LZ4_MAX_INPUT_SIZE:Nn,BLOCK_MAX_SIZE:65536,DICT_SIZE:Dn,DEFAULT_WORK_AREA:wn,DEFAULT_MAX_WORK:Un,SHRINK_MODE:Ln,LZ4_ERROR:Pn,alignToPowerOf2:kn,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".');Wn=e},getHashStrategy:function(){return Wn},compress:function(e,t,s,r,n){if(null==e)return 0;if(null==t)return 0;if(s=s||0,r=void 0===r?e.length:r,n=n||0,s<0||n<0)return 0;if(r<0)return 0;if(s+r>e.length)return 0;if(r>Nn)return 0;if(0===r)return t.length>n?(t[n]=0,1):0;var o=r<_n?xn.byU16:xn.byU32;return to({hashTable:new Uint32Array(o===xn.byU16?8192:bn),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,0,!1,o,Fn,qn)},compressLimited:function(e,t,s,r,n,o){if(null==e)return 0;if(null==t)return 0;if(s=s||0,r=void 0===r?e.length:r,n=n||0,s<0||n<0)return 0;if(r<0||o<0)return 0;if(s+r>e.length)return 0;if(r>Nn)return 0;if(o<1)return 0;if(0===r)return t[n]=0,1;var i=r<_n?xn.byU16:xn.byU32;return to({hashTable:new Uint32Array(i===xn.byU16?8192:bn),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,o,!0,i,Fn,qn)},compressBound:function(e){return e<0||e>Nn?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,s,r,n,o){return null==e||null==t?-1:(n=n||0,(s=s||0)<0||n<0||r<0||o<0||s+r>e.length||n+o>t.length?-1:io(e,t,s,r,n,o,!0,0,0,Fn,n,null,0))},decompressFast:function(e,t,s,r,n){return io(e,t,s=s||0,0,r=r||0,n,!1,0,0,Bn,r-65536,0,65536)},createStream:ao,resetStream:co,loadDict:function(e,t,s,r){if(e.initCheck&&co(e),r<4)return e.dictionary=null,e.dictSize=0,0;r>65536&&(s=s+r-65536,r=65536);var n=s-e.currentOffset;e.dictionary=t,e.dictionaryStart=s,e.dictSize=r,e.currentOffset+=r;for(var o=s,i=s+r;o<=i-4;)Jn(t,o,e.hashTable,xn.byU32,n),o+=3;return r},compressContinue:lo,saveDict:uo,createStreamDecode:ho,setStreamDecode:po,decompressSafeContinue:mo,RingBufferEncoder:go,RingBufferDecoder:fo,_hashU16:Qn,_hashU32:jn,_TABLE_TYPE:xn},Eo=268435455,Ro=new Uint32Array(256);let Io=!1;function vo(e){!function(){if(!Io){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;Ro[e]=t>>>0}Io=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const r=e[s]??0;t=t>>>8^(Ro[255&(t^255&r)]??0)}return(4294967295^t)>>>0}var So=(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))(So||{});const Co=268435455;class To{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:yo.DEFAULT_WORK_AREA,maxWorkArea:yo.DEFAULT_MAX_WORK,shrinkMode:yo.SHRINK_MODE.MANUAL};this.encoder=new yo.RingBufferEncoder(e),this.decoder=new yo.RingBufferDecoder(e)}compress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length>Co)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=yo.compressBound(t.length),r=new Uint8Array(s),n=this.encoder.compress(t,r);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const o=r.subarray(0,n),i=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>Eo)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=vo(t),c=new Uint8Array(i.length+4+n);let d=0;c.set(i,d),d+=i.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(o,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},r=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let s=0,r=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,s|=(127&n)<<r,!(128&n))return s>>>0;if(r+=7,r>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,s);if(r>Co)throw new Error(`Original size exceeds maximum allowed: ${r}`);if(t.length<s.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+s.offset,4).getUint32(0,!1);s.offset+=4;const o=t.subarray(s.offset),i=new Uint8Array(r),a=this.decoder.decompress(o,i,r);if(a<0||a!==r)throw new Error(`LZ4 decompression failed: expected ${r}, got ${a}`);const c=vo(i);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return i}reset(){this.encoder.reset(),this.decoder.reset()}}const Ao=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Oo=(e,t)=>r.encodeWithReflection(e,t).finish();class bo{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Dr({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:[Ee],compressType:[Re],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 t=br(),s=t.lookupType("easemob.pb.Provision"),r=t.lookupType("easemob.pb.MSync"),n={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Re],encryptType:[Ee],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}:{}},o=Oo(s,n),i={version:0,guid:wr({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:B,deviceId:0,encryptType:[Ee],payload:o,traceId:e.createTraceId()};return Oo(r,i)}encodeHeartbeat(){const t=br(),s=t.lookupType("easemob.pb.CommUnreadUL"),r=t.lookupType("easemob.pb.MSync"),n=Oo(s,{}),o={version:0,encryptType:[Ee],command:x,payload:n,traceId:e.createTraceId()};return Oo(r,o)}encodeStatisticRebuild(){const t=br(),s=t.lookupType("easemob.pb.StatisticsBody"),r=t.lookupType("easemob.pb.Meta"),n=t.lookupType("easemob.pb.CommSyncUL"),o=t.lookupType("easemob.pb.MSync"),i=Oo(s,{operation:0}),a=r.decode(new Uint8Array);a.id=Date.now(),a.ns=le,a.payload=i;const c=n.decode(new Uint8Array);c.meta=a;const d=Oo(n,c);return Oo(o,{version:0,encryptType:[Ee],command:k,payload:d,traceId:e.createTraceId()})}decodeProvision(e){const t=br().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},r="number"==typeof s.errorCode?s.errorCode:Se,n="string"==typeof s.reason?s.reason:void 0,o="string"==typeof t.resource?t.resource:void 0,i="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:r===ve,statusCode:r,reason:n,resource:o,authToken:i,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=br().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=br().lookupType("easemob.pb.CommSyncDL").decode(e),s=Array.isArray(t.metas)?t.metas:[],r=[];for(const n of s){const e=this.decodeStatisticMeta(n);e&&r.push(e)}return r}decodeMsync(e){const t=br().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(t){const s=br(),r=s.lookupType("easemob.pb.CommSyncDL"),n=s.lookupType("easemob.pb.MessageBody"),o=r.decode(t);e.logger.debug("decodeSync commSyncDl",{hasMetas:Array.isArray(o.metas)});const i=Array.isArray(o.metas)?o.metas:[],a=this.decodeAck(o);a?.ok&&(a.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const c=Ur(o.metaId),d=Ur(o.nextKey),l=o.queue??void 0,u="boolean"==typeof o.isLast?o.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:a,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u,replacedMessage:e}}for(const e of i){const t=this.decodeChatMeta(e,n);t&&h.push(t);const s=this.decodeChatActionMeta(e,n);s&&p.push(s);const r=this.decodeNotifyMeta(e);r.length>0&&p.push(...r)}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,r=s.payload;let n=null;if(r instanceof Uint8Array?n=r:r instanceof ArrayBuffer?n=new Uint8Array(r):ArrayBuffer.isView(r)&&(n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!n)return null;if(("number"==typeof s.ns?s.ns:void 0)!==ue)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const r=e;return this.decodeMessage(s,r)}catch{return null}}decodeChatActionMeta(t,s){if(!t||"object"!=typeof t)return null;const r=t,n=r.payload;let o=null;if(n instanceof Uint8Array?o=n:n instanceof ArrayBuffer?o=new Uint8Array(n):ArrayBuffer.isView(n)&&(o=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!o)return null;if(("number"==typeof r.ns?r.ns:void 0)!==ue)return null;try{const t=s.decode(o);if(!t||"object"!=typeof t)return null;const n=t,i="number"==typeof n.type?n.type:q;if(i!==H&&i!==j&&i!==Q&&i!==$&&i!==W)return null;const a=this.readJid(r.to),c=Number(Ur(r.timestamp))||Date.now(),d=this.resolveActionConversationType(a.domain,n.meta,n),{senderId:l,receiverId:u}=this.resolveIncomingMessageParties(r,n,d),h=this.resolveActionConversationId(l,u,d);if(i===Q)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===H){e.logger.debug("Received READ_ACK MessageBody",n);const t=(Array.isArray(n.ackMessageIds)?n.ackMessageIds:[]).map(e=>Ur(e)).filter(e=>Boolean(e)),s=Ur(n.ackMessageId);if(0===t.length&&s&&t.push(s),0===t.length||!h)return null;const r=Pr(Array.isArray(n.ext)?n.ext.filter(Ao):void 0),o=Ao(r.group_ack_count)?r.group_ack_count:{},i=t.flatMap(e=>{const t=o[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:t,conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:c,..."groupChat"===d?{receiptDetails:i}:{}}}}if(i===W){const e=Ur(n.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(i===j){const e=Ur(n.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=Ur(n.editMessageId),m=(Array.isArray(n.contents)?n.contents:[])[0],g=m?this.decodeContent(m):null;if(!p||!h||!g)return null;const f=this.resolveModifiedInfo(n.meta);return{type:"message_updated",data:{messageId:p,conversationId:h,conversationType:d,timestamp:c,message:{type:g.type,body:g.body,ext:Pr(n.ext),...f?{modifiedInfo:f}:{}}}}}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!==me&&s!==pe&&s!==he&&s!==le)return[];const r=t.payload;let n=null;return r instanceof Uint8Array?n=r:r instanceof ArrayBuffer?n=new Uint8Array(r):ArrayBuffer.isView(r)&&(n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),n?s===pe?this.decodeRosterMeta(t,n):s===he?this.decodeMucMeta(t,n):s===le?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(t,s){try{const r=br(),n=r.lookupType("easemob.pb.StatisticsBody").decode(s);if("string"!=typeof n.location||0===n.location.length)return[];const o=JSON.parse(n.location);if(!Ao(o)||!Array.isArray(o.group_ack))return[];const i=this.readMetaTimestamp(t)??Date.now(),a=new Map;for(const e of o.group_ack){if(!Ao(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[s,r]of Object.entries(e)){if("groupId"===s)continue;const e="number"==typeof r?r:"string"==typeof r&&r.trim().length>0?Number(r):Number.NaN;!s||!Number.isInteger(e)||e<0||a.set(s,{conversationId:t,count:e})}}return e.logger.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:i,receiptDetails:[{messageId:e,count:s}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==le)return null;const s=t.payload;let r=null;if(s instanceof Uint8Array?r=s:s instanceof ArrayBuffer?r=new Uint8Array(s):ArrayBuffer.isView(s)&&(r=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!r)return null;try{const e=br(),t=e.lookupType("easemob.pb.StatisticsBody").decode(r);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=br(),r=s.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof r.operation?r.operation:-1,o=this.readRosterJid(r.from),i=this.readRosterJidList(r.to),a="string"==typeof r.reason?r.reason:"",c="string"==typeof r.rosterVer&&r.rosterVer.trim().length>0?r.rosterVer:void 0,d=o.name??"",l=i[0]?.name??"";if(!d&&!l)return[];const u=vn({operation:n,from:o,to:i,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:r},this.msyncCodecContext());if(u)return[this.createMultiDeviceNotify(u)];const h=this.mapRosterOperationToEvent(n,{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=br(),r=s.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof r.operation?r.operation:-1,o=!0===r.isChatroom,i=!0===r.isThread,a=this.readJid(r.from),c=Array.isArray(r.to)?r.to.map(e=>this.readJid(e)):[],d=r.eventInfo&&"object"==typeof r.eventInfo?r.eventInfo:void 0,l=Array.isArray(r.members)?r.members.filter(e=>"string"==typeof e):[],u=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(i){const t=Cn({operation:n,threadId:this.readJid(r.mucId).name??"",threadName:"string"==typeof r.mucName?r.mucName:void 0,parentId:this.readJid(r.mucParentId).name??void 0,from:a,to:c,members:l,timestamp:this.readMetaTimestamp(e),raw:r},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const s=37===n&&c.some(e=>e.name===this.context.userId),o=this.readJid(r.mucId).name??"",i=this.readJid(r.mucParentId).name??"";return s&&o&&i?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:o,name:"string"==typeof r.mucName?r.mucName:void 0,muc_parent_id:i,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!o){const t=Sn({operation:n,groupId:this.readJid(r.mucId).name??"",groupName:"string"==typeof r.mucName?r.mucName:void 0,from:a,to:c,reason:"string"==typeof r.reason?r.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:l,timestamp:this.readMetaTimestamp(e),raw:r},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=o?Hr({operation:n,chatRoomId:this.readJid(r.mucId).name??"",chatRoomName:"string"==typeof r.mucName?r.mucName:void 0,from:a,to:c,reason:"string"==typeof r.reason?r.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof r.ext?r.ext:void 0,members:l}):sn({operation:n,groupId:this.readJid(r.mucId).name??"",groupName:"string"==typeof r.mucName?r.mucName:void 0,from:a,to:c,reason:"string"==typeof r.reason?r.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof r.ext?r.ext:void 0,members:l,source:u});return h?[{type:o?"chatroom":"group",eventName:o?"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&&cn.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(t){try{let s="";for(let e=0;e<t.length;e+=1){const r=t[e];if(void 0===r)return[];s+=`%${r.toString(16)}`}const r=decodeURIComponent(s),n=JSON.parse(r);e.logger.debug("Decoded MSync notify payload",{payload:n});const o="string"==typeof n.type?n.type:"";if(!o)return[];if("thread"===o){return[{type:o,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:Ao(n.data)?n.data:n}}]}if("conv"===o){const e=Ao(n.data)?n.data:n,t=[],s="string"==typeof e.op?e.op:"";if("pin"===s||"pin_delete"===s)return[{type:o,eventName:"onPinnedMessageChanged",data:e}];const r=Tn({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 r&&t.push(this.createMultiDeviceNotify(r)),t}if("roaming_delete"===o){const e=Ao(n.data)?n.data:n,t=An({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"===o){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const s=[];for(const r of e){if(!gn(r))continue;const e=fn(r.operator_resource,r.resource,r.clientResource);if(yn(e,t.clientResource))continue;const n=hn(r.group)??hn(r.user);if(!n||!gn(r.data))continue;const o=hn(r.group)?un:ln,i=r.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:o,remindType:hn(i.type),silentMode:i,deviceId:e,raw:r})}return s})(Ao(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:o,data:n.data??n}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,s=Number(Ur(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:On(e.category),data:e}}decodeNotice(e){const t=br().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=br().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(t){const s=br(),r=s.lookupType("easemob.pb.CommSyncUL"),n=s.lookupType("easemob.pb.MSync"),o=Oo(r,{queue:t}),i={version:0,encryptType:[Ee],command:k,payload:o,traceId:e.createTraceId()};return Oo(n,i)}encodeLastSession(t,s){const r=br(),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i=Oo(n,{queue:t,key:s}),a={version:0,encryptType:[Ee],command:k,payload:i,traceId:e.createTraceId()};return Oo(o,a)}encodeChatMessage(t,s){const r=br(),n=r.lookupType("easemob.pb.MessageBody"),o=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),a=this.buildContent(t),c=this.resolveMessageProfileVersionFields(t),d=this.buildMessageMeta(t),l=this.resolveOutboundMessageTarget(t.conversationId,t.conversationType),u={type:this.resolveChatType(t),from:{name:this.context.userId},to:{name:l.name},contents:[a],ext:Lr(t.ext??{}),...d?{meta:d}:{},...c,...t.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},h=Oo(n,u),p="singleChat"===t.conversationType?this.context.domain:"conference.easemob.com",m=this.resolveDirectedUsers(t),g=this.resolveMetaExt(t),f={id:s,to:wr({appKey:this.context.appKey,name:l.name,domain:p,clientResource:l.clientResource}),ns:ue,payload:h,routetype:this.resolveRouteType(t),directedUsers:m,ext:g,...void 0!==t.webhookEnv?{env:t.webhookEnv}:{}},y=Oo(o,{meta:f}),E={version:0,encryptType:[Ee],command:k,payload:y,traceId:e.createTraceId()};return Oo(i,E)}encodeActionMessage(t,s){const r=br(),n=r.lookupType("easemob.pb.MessageBody"),o=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),a=r.lookupEnum("easemob.pb.MessageBody.EditScope"),c=this.resolveOutboundMessageTarget(t.conversationId,t.conversationType),d=t.body&&t.messageType?[this.buildContent({msgServerId:t.messageId??"",msgLocalId:s,from:this.context.userId,to:t.conversationId,sender:{userId:this.context.userId},conversationId:t.conversationId,conversationType:t.conversationType,type:t.messageType,sendStatus:"sending",ext:t.ext??{},timestamp:Date.now(),body:t.body})]:[],l={type:this.resolveActionMessageType(t),from:{name:this.context.userId},to:{name:c.name},contents:d,ext:Lr(t.ext??{})};"recall"!==t.kind&&"deliveryAck"!==t.kind||(l.ackMessageId=t.messageId),"sendMessageReadReceipts"===t.kind&&(l.ackMessageIds=t.messageIds,"groupChat"===t.conversationType&&(l.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===t.kind&&(l.sendToPeer=t.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===t.kind&&(l.sendToPeer=t.sendToPeer??!1,l.clearAllUnreadMessageCount=t.clearAllUnreadMessageCount??!0),"update"===t.kind&&(l.editMessageId=t.messageId,l.editScope=t.ext&&Object.keys(t.ext).length>0?a.values.BODY_AND_EXT:a.values.BODY);const u=Oo(n,l);if("clearAllConversationUnreadMessageCount"===t.kind){const t=n.decode(u),r=n.fields.clearAllUnreadMessageCount;e.logger.debug("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:s,messageType:l.type,fieldId:r?.id,requestedValue:l.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(t,"clearAllUnreadMessageCount"),decodedValue:t.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const h={id:s,to:wr({appKey:this.context.appKey,name:c.name,domain:"singleChat"===t.conversationType?this.context.domain:"conference.easemob.com",clientResource:c.clientResource}),ns:ue,payload:u,routetype:ge,directedUsers:[],ext:[]},p=Oo(o,{meta:h}),m={version:0,encryptType:[Ee],command:k,payload:p,traceId:e.createTraceId()};return Oo(i,m)}encodeChatRoomOperation(t,s){const r=br(),n=r.lookupType("easemob.pb.MUCBody"),o=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),a={mucId:wr({appKey:this.context.appKey,name:t.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===t.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===t.operation&&(void 0!==t.ext&&(a.ext=t.ext),void 0!==t.leaveOtherRooms&&(a.leaveOtherRooms=t.leaveOtherRooms));const c=Oo(n,a),d={id:s,from:wr({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:he,payload:c},l=Oo(o,{meta:d}),u={version:0,encryptType:[Ee],command:k,payload:l,traceId:e.createTraceId()};return Oo(i,u)}decodeServerMessageMeta(e){const t=br(),s=t.lookupType("easemob.pb.Meta"),r=t.lookupType("easemob.pb.MessageBody");try{const t=s.decode(e);return this.decodeChatMeta(t,r)}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?ut(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=r.Long.fromString("1099511628211",!0);let s=r.Long.fromString("1469598103934665603",!0);for(let n=0;n<e.length;n+=1)s=s.xor(r.Long.fromInt(e.charCodeAt(n),!0)).multiply(t).toUnsigned();return s.isZero()?"1":s.toString()})(e)}decodeChatRoomJoinInfo(t){const s=br().lookupType("easemob.pb.MUCBody");for(const n of t){if(!Ao(n)||n.ns!==he)continue;const t=n.payload,o=t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):void 0;if(o)try{const e=s.decode(o);if(!Ao(e)||!Ao(e.status))continue;const t=e.status.chatroomInfo;if("string"!=typeof t||""===t)continue;const r=JSON.parse(t);if(!Ao(r))continue;const n=r[this.context.userId];if(!Ao(n))continue;const i=n;return{..."boolean"==typeof i.is_all_mute?{isAllMembersMuted:i.is_all_mute}:{},..."number"==typeof i.create_timestamp?{createTimestamp:i.create_timestamp}:{},..."boolean"==typeof i.is_in_white_list?{isInAllowlist:i.is_in_white_list}:{},..."number"==typeof i.member_count?{memberCount:i.member_count}:{},muteExpireTimestamp:"number"==typeof i.mute_duration&&0!==i.mute_duration?i.mute_duration:-1}}catch(r){e.logger.error("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=Ur(e.metaId);if(!t||"0"===t)return;const s=e.status??{},r="number"==typeof s.errorCode?s.errorCode:Se,n="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:Ur(e.serverId),ok:r===ve,statusCode:r,reason:n}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:K;if(!this.isPublicMessageType(s))return null;const r=(Array.isArray(t.contents)?t.contents:[])[0];if(!r)return null;const n=this.resolveConversationType(s),{senderUserId:o,senderId:i,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=i===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:i:a,l=this.decodeContent(r);if(!l)return null;const u=Pr(t.ext),h=Pr(e.ext),p=Number(Ur(e.timestamp))||Date.now(),m=Ur(e.id),g=this.resolveBroadcast(h),f=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),E=this.resolveContentReplaced(y),R=this.resolveReactions(y),I=this.resolveModifiedInfo(y),v=this.resolveChatThreadMessageContext(y),S=this.resolveChatThreadOverview(y),C=this.resolveProfileVersionTime(t.userInfoUpdateTime),T=this.resolveProfileVersionTime(t.namecardUpdateTime),A={msgServerId:m,msgLocalId:"",from:i,to:a,sender:{userId:o},conversationId:d,conversationType:n,type:l.type,sendStatus:"sent",ext:u,timestamp:p,body:l.body,direct:c,isOnline:this.resolveMessageIsOnline(s,h)};nn(A,{userInfoUpdateTime:C,namecardUpdateTime:T});const O=this.decodeStreamMeta(t.stream,r);O&&(A.type="text",A.body={content:O.fullText},A.stream=O),void 0!==g&&(A.isBroadcast=g),void 0!==f&&(A.priority=f),void 0!==E&&(A.isContentReplaced=E),R&&(A.reactions=R),I&&(A.modifiedInfo=I),v&&(A.isChatThread=!0,A.chatThread=v);const b=this.resolvePeerRead(y,n,c);void 0!==b&&(A.isPeerRead=b);const _=this.resolveGroupReadCount(y,n);void 0!==_&&(A.groupReadCount=_),S&&(A.chatThreadOverview=S);const M=t.msgConfig;return M?.allowGroupAck&&(A.needReadReceipt=!0),A}resolveMessageProfileVersionFields(e){const t=on(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 a.normalizeProfileVersionSeconds(Ur(e))}isPublicMessageType(e){return e===K||e===V||e===z}resolveMessageIsOnline(e,t){if(e===z)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,r=Number(Ur(s.streamSeq));if(!Number.isFinite(r))return;const n="number"==typeof s.streamStatus?s.streamStatus:ae,o="number"==typeof s.streamError?s.streamError:0,i="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:r,status:this.mapStreamStatus(n,o),errorType:o,finishReason:i,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?L.ERROR:e===oe?L.START:e===ie?L.START_COMPLETED:e===ce?L.COMPLETED:e===de?L.FULL:L.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(s){if("text"===s.type){const e=s.body;return{type:Y,text:e.content}}if("cmd"===s.type){const e=s.body;return{type:se,action:e.action}}if("custom"===s.type){const e=s.body;return{type:re,customEvent:e.event,customExts:Lr(e.params??{})}}if("location"===s.type){const e=s.body;return{type:Z,latitude:e.latitude,longitude:e.longitude,address:e.address,buildingName:e.buildingName}}if("image"===s.type){const t=s.body,r=t.isGif||t.isOriginalImage?"original":"large";return{type:J,displayName:t.filename,remotePath:t.originalImageUrl??"",imageType:e.toProtocolImageType(r),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"===s.type){const e=s.body;return{type:X,displayName:e.filename,remotePath:e.url,secretKey:e.secret,fileLength:e.fileLength,duration:e.duration,size:e.width&&e.height?{width:e.width,height:e.height}:void 0,thumbnailRemotePath:e.thumbnailUrl,thumbnailSecretKey:e.secret,thumbnailDisplayName:e.filename}}if("voice"===s.type){const e=s.body;return{type:ee,displayName:e.filename,remotePath:e.url,secretKey:e.secret,fileLength:e.fileLength,duration:e.duration,thumbnailDisplayName:e.filename}}if("combine"===s.type){const e=s.body;return{type:Y,subType:0,text:t.getCombineCompatibleTextSidecar(s)??"版本过低",displayName:e.filename,remotePath:e.url,secretKey:e.secret,fileLength:e.fileLength,title:e.title,summary:e.summary,combineLevel:e.combineLevel}}const r=s.body;return{type:te,displayName:r.filename,remotePath:r.url,secretKey:r.secret,fileLength:r.fileLength,thumbnailDisplayName:r.filename}}decodeContent(t){const s="number"==typeof t.type?t.type:Y,r="string"==typeof t.remotePath&&t.remotePath.length>0||"string"==typeof t.title&&t.title.length>0||"string"==typeof t.summary&&t.summary.length>0||"number"==typeof t.combineLevel&&t.combineLevel>0,n=Object.prototype.hasOwnProperty.call(t,"subType")&&0===t.subType;if(s===ne||s===Y&&(n||r)){return{type:"combine",body:{title:"string"==typeof t.title?t.title:"",summary:"string"==typeof t.summary?t.summary:"",filename:"string"==typeof t.displayName?t.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof t.remotePath?t.remotePath:void 0,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,combineLevel:"number"==typeof t.combineLevel?t.combineLevel:0}}}if(s===Y)return{type:"text",body:{content:"string"==typeof t.text?t.text:""}};if(s===se)return{type:"cmd",body:{action:"string"==typeof t.action?t.action:""}};if(s===re){const e=Pr(t.customExts);return{type:"custom",body:{event:"string"==typeof t.customEvent?t.customEvent:"",params:e}}}if(s===Z)return{type:"location",body:{latitude:"number"==typeof t.latitude?t.latitude:0,longitude:"number"==typeof t.longitude?t.longitude:0,address:"string"==typeof t.address?t.address:void 0,buildingName:"string"==typeof t.buildingName?t.buildingName:void 0}};if(s===J){const s=t.size??{},r="number"==typeof s.width?s.width:0,n="number"==typeof s.height?s.height:0,o=e.fromProtocolImageType(t.imageType)===e.IMAGE_TYPE_ORIGINAL,i="string"==typeof t.remotePath?t.remotePath:"",a=e.deriveImageUrls(i,{deriveVariants:!this.useCustomAttachmentUpload}),c="string"==typeof t.thumbnailRemotePath&&t.thumbnailRemotePath.length>0?t.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof t.displayName?t.displayName:"image",filetype:"application/octet-stream",width:r,height:n,isGif:1===t.subType,isOriginalImage:o,originalImageUrl:a.originalImageUrl,bigImageUrl:a.bigImageUrl,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,thumbnailUrl:c??a.thumbnailUrl}}}if(s===X){const e=t.size??{},s="number"==typeof e.width?e.width:void 0,r="number"==typeof e.height?e.height:void 0,n="string"==typeof t.thumbnailRemotePath?t.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof t.duration?t.duration:0,width:s,height:r,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,thumbnailUrl:n}}}if(s===ee){return{type:"voice",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof t.duration?t.duration:0,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0}}}if(s===te){return{type:"file",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0}}}return null}resolveChatType(e){switch(e.conversationType){case"groupChat":return V;case"chatRoom":return z;default:return K}}resolveActionConversationType(e,t,s){const r=this.resolveConversationTypeFromMeta(t);if(r)return r;const n=s?.msgConfig&&"object"==typeof s.msgConfig?s.msgConfig:null;return!0===n?.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,r=("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"===r||"singleChat"===r)return"singleChat";if("chat:group"===r||"groupChat"===r)return"groupChat";if("chat:room"===r||"chatRoom"===r)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 r=e.slice(s.length);return r?{name:this.context.userId,clientResource:r}:{name:e}}resolveIncomingMessageParties(e,t,s){const r=this.readJid(e.from),n=this.readJid(e.to),o=this.readJid(t.from),i=this.readJid(t.to),a=o.name??r.name??"",c=i.name??n.name??"";if(!("singleChat"===s&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:r.clientResource&&r.clientResource!==this.context.clientResource?`${a}/${r.clientResource}`:a,receiverId:n.clientResource?`${c}/${n.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return Q;case"sendMessageReadReceipts":return H;case"deliveryAck":return W;case"recall":return j;case"update":return $;default:return K}}resolveConversationType(e){return e===V?"groupChat":e===z?"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?Lr({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?ye:this.resolveDeliverOnlineOnly(e)?fe:ge}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),r=this.parseMetaPayload(t);return s&&r?{...r,...s}:s??r??e??t}resolvePeerRead(e,t,s){if("singleChat"!==t||"SEND"!==s)return;const r=this.parseMetaPayload(e);return"boolean"==typeof r?.isRead?r.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const s=this.parseMetaPayload(e),r=s?.group_read_ack;return"number"==typeof r&&Number.isInteger(r)&&r>=0?r:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),s=t?.edit_msg;if(!Ao(s))return;const r="string"==typeof s.operator?s.operator:"",n=this.toFiniteNumber(s.count),o=this.toFiniteNumber(s.edit_time);return r&&void 0!==n&&void 0!==o?{operatorId:r,operationCount:n,operationTime:o}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),s=t?.thread;if(!Ao(s)||0===Object.keys(s).length)return;const r=this.readString(s.msg_parent_id??s.messageId),n=this.readString(s.muc_parent_id??s.parentId);if(!r||!n)return;const o=this.readString(s.thread_name??s.chatThreadName);return{messageId:r,parentId:n,...o?{chatThreadName:o}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),s=t?.thread_overview??t?.threadOverview;if(!Ao(s)||0===Object.keys(s).length)return;const r=this.readString(s.id??s.thread_id??s.chatThreadId),n=this.readString(s.muc_parent_id??s.parentId);if(!r||!n)return;const o=this.readString(s.name),i=this.resolveChatThreadOverviewLastMessage(s.last_message??s.lastMessage,r);return{chatThreadId:r,parentId:n,...o?{name:o}:{},...void 0!==i?{lastMessage:i}:{},...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(!Ao(e)||0===Object.keys(e).length)return null;const s=this.readString(e.msgId??e.msg_id??e.id);if(!s)return null;const r=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),o=this.readString(n?.from)??this.readString(e.from)??"",i=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=Ao(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=o===this.context.userId?"SEND":"RECEIVE";return{msgServerId:s,msgLocalId:"",from:o,to:i,sender:{userId:o},conversationId:h,conversationType:"groupChat",type:l,sendStatus:"sent",ext:Ao(n?.ext)?n.ext:{},timestamp:r,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(Ao(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(t,s,r){if(!s){return{content:this.readString(r.msg??r.content??r.text)??""}}switch(t){case"text":default:return{content:this.readString(s.msg??s.content??s.text)??""};case"image":{const t=this.readString(s.url)??"",r=e.deriveImageUrls(t,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(s.filename)??"image",filetype:this.readString(s.filetype)??"application/octet-stream",width:this.toFiniteNumber(s.width)??0,height:this.toFiniteNumber(s.height)??0,isGif:!0===s.isGif,isOriginalImage:!1,originalImageUrl:r.originalImageUrl,bigImageUrl:r.bigImageUrl,thumbnailUrl:this.readString(s.thumb)??r.thumbnailUrl,secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)}}case"voice":return{url:this.readString(s.url)??"",filename:this.readString(s.filename)??"voice",filetype:this.readString(s.filetype)??"application/octet-stream",duration:this.toFiniteNumber(s.duration??s.length)??0,secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)};case"video":return{url:this.readString(s.url)??"",filename:this.readString(s.filename)??"video",filetype:this.readString(s.filetype)??"application/octet-stream",duration:this.toFiniteNumber(s.duration??s.length)??0,width:this.toFiniteNumber(s.width),height:this.toFiniteNumber(s.height),thumbnailUrl:this.readString(s.thumb),secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)};case"file":return{url:this.readString(s.url)??"",filename:this.readString(s.filename)??"file",filetype:this.readString(s.filetype)??"application/octet-stream",secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)};case"location":return{latitude:this.toFiniteNumber(s.lat??s.latitude)??0,longitude:this.toFiniteNumber(s.lng??s.longitude)??0,address:this.readString(s.addr??s.address),buildingName:this.readString(s.buildingName)};case"cmd":return{action:this.readString(s.action)??""};case"custom":return{event:this.readString(s.event??s.customEvent)??"",params:Ao(s.params??s.customExts)?s.params??s.customExts:{}};case"combine":return{title:this.readString(s.title)??"",summary:this.readString(s.summary)??"",filename:this.readString(s.filename)??"combine",filetype:"application/octet-stream",url:this.readString(s.url),secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength),combineLevel:this.toFiniteNumber(s.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(ht(t));return Ao(e)?e:null}catch{return null}}if(Ao(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return Ao(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(Ao).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?[]:[Ie]}configureCompression(e,t){if(!e||!e.includes(Ie))return void this.disableCompression();this.compressor||(this.compressor=new To);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===So.UPLINK_ONLY||s===So.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===So.DOWNLINK_ONLY||s===So.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?So.UPLINK_ONLY:1===e?So.DOWNLINK_ONLY:2===e?So.BIDIRECTIONAL:So.NONE}disableCompression(){this.compressor&&(this.compressor.mode=So.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}class _o{constructor(s,r){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=new Set,this.offlineMessageQueueReports=new Map,this.offlineMessageQueueCounts=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:e.HEARTBEAT_INTERVAL,autoReconnectNumMax:10,connectTimeout:e.CONNECT_TIMEOUT,...s},this.eventHub=r,this.msyncCodec=new bo({appKey:s.appKey,useCustomAttachmentUpload:s.useCustomAttachmentUpload,userId:s.userId,token:s.token,useReplacedMessageContents:s.useReplacedMessageContents,useFixedDeviceId:s.useFixedDeviceId,deviceId:s.deviceId,customDeviceName:s.customDeviceName,customOSPlatform:s.customOSPlatform,uiKitVersion:s.uiKitVersion,loginExtensionInfo:s.loginExtensionInfo,serviceId:s.serviceId}),this.serverUrls=this.normalizeServerUrls(s),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:t.ConnectionStatus.DISCONNECTED,serverUrl:this.config.serverUrl,userId:s.userId,token:s.token,reconnectAttempts:0},this.connectionRetry=new Sr({maxAttempts:this.config.autoReconnectNumMax,initialDelay:e.RECONNECT_INITIAL_DELAY,maxDelay:e.RECONNECT_MAX_DELAY,backoffMultiplier:e.RECONNECT_BACKOFF_MULTIPLIER}),this.heartbeatManager=new Ar({interval:this.config.heartBeatWait,timeout:e.HEARTBEAT_TIMEOUT}),this.connectionEventNormalizer=new pt,this.socketAdapter=this.resolveSocketAdapter(s),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[t.InternalEventName.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 r=Date.now();if(s<=r)throw new e.ConnectionError("Token is expired",{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=t,this.connection.token=t,this.msyncCodec.updateToken(t),this.setupTokenLifecycle(t,s,r),e.logger.warn("Connection token renewed",{userId:this.config.userId,expireAt:s}),{token:t,expireAt:s}}handleOnline(){e.logger.warn("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0;const s=this.offlineRecoverPending?t.ConnectionEventReason.OFFLINE_RECOVER:t.ConnectionEventReason.ONLINE;this.offlineRecoverPending=!1,this.resumeReconnect(s)}handleOffline(){e.logger.warn("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.stopHeartbeat(),this.closeWebSocket(t.ConnectionEventReason.OFFLINE,!0),e.logger.warn("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void e.logger.warn("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const s=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==s)return;this.closeWebSocket(t.ConnectionEventReason.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(t.ConnectionEventReason.HEARTBEAT_FAILED)}}catch(r){if(e.logger.warn("Foreground heartbeat check failed",r),this.reconnectInProgress||this.websocket!==s)return;this.closeWebSocket(t.ConnectionEventReason.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(t.ConnectionEventReason.HEARTBEAT_FAILED)}}resumeReconnect(s){this.isLoggedIn&&(this.reconnectInProgress?e.logger.warn("Reconnect recovery skipped",{guard:"reconnect-in-progress",reason:s,...this.getReconnectDiagnostic()}):this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),e.logger.warn("Reconnect recovery requested",{reason:s,...this.getReconnectDiagnostic()}),this.triggerReconnect(s)))}handleSendTimeout(s){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||s.reason===t.ConnectionEventReason.SEND_TIMEOUT&&e.logger.warn("Message send timeout received without reconnect",s))}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(t){if(!(t instanceof e.ConnectionError))return!1;const s=t.details;if(!s||"object"!=typeof s)return!1;return!1===s.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(ht(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 t=this.connectionRetry.getRetryDelay();e.logger.warn("Reconnect retry scheduled",{delayMs:Math.round(t),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise(e=>{this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,e()},t)})}buildConnectionEventPayload(t,s){const r=this.connection.error instanceof e.ConnectionError?this.connection.error:void 0;return{state:t,reason:s,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,s){if(e===t.ConnectionStatus.DISCONNECTED&&!this.hasEverConnected)return;if(e===t.ConnectionStatus.RECONNECT_FAILED&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t.ConnectionStatus.DISCONNECTED||e===t.ConnectionStatus.RECONNECT_FAILED))return;const r=this.buildConnectionEventPayload(e,s),n=this.connectionEventNormalizer.normalize(e,r);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(s,r,n,o=!1){const i=this.connection.status!==s;(i||o)&&(i&&(this.connection.status=s,this.connection.lastConnectedAt=s===t.ConnectionStatus.CONNECTED?Date.now():void 0),n&&this.dispatchConnectionEvent(s,r),e.logger.debug("Connection status updated",{status:s,reason:r,attempt:this.reconnectAttempts,forceEmit:o}))}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 r=Math.max(t-s,0),n=s+Math.floor(.8*r);this.tokenLifecycle={token:e,issuedAt:s,expireAt:t,willExpireAt:n,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(n-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(t){if(t&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const s=JSON.parse(t);if(!s||"object"!=typeof s)return void e.logger.warn("Provision auth token has invalid payload");const r=Number(s.expires_in);if(!Number.isFinite(r))return void e.logger.warn("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(s){e.logger.warn("Failed to parse provision auth token expiration",s)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,e.logger.warn("Token will expire"),this.eventHub.dispatch(t.ConnectionEventName.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 s=this.tokenLifecycle;s.expiredEmitted||(s.expiredEmitted=!0,e.logger.warn("Token expired"),this.eventHub.dispatch(t.ConnectionEventName.TOKEN_EXPIRED,void 0))}isTokenExpiredConnectionError(t){return t instanceof e.ConnectionError&&t.code===e.ERROR_CODES.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(s){e.logger.warn("Connection closing because token expired",{source:s}),this.connection.error=new e.ConnectionError("Token expired",{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:s,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(t.ConnectionEventReason.TOKEN_EXPIRED,!0,!0),this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.TOKEN_EXPIRED,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(t.ConnectionEventReason.HEARTBEAT_FAILED)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,e.HEARTBEAT_TIMEOUT)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(){if(!this.reconnectInProgress)if(this.connection.status!==t.ConnectionStatus.CONNECTED&&this.connection.status!==t.ConnectionStatus.CONNECTING){this.isLoginPhase=!0,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(t.ConnectionEventReason.LOGIN,!0),this.isLoggedIn=!0}catch(s){throw this.isLoggedIn=!1,s}finally{this.isLoginPhase=!1}}else e.logger.warn("Connection already established or connecting")}async connectWithRetry(s,r){if(e.logger.warn("Reconnect flow requested",{reason:s,throwOnFailure:r,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void e.logger.warn("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:s,...this.getReconnectDiagnostic()});if(this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket)return;if(this.reconnectPaused)return void e.logger.warn("Reconnect flow skipped",{guard:"reconnect-paused",reason:s,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let n=null,o=null;const i=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),e.logger.warn("Reconnect flow started",{reason:s,throwOnFailure:r,maxAttempts:i,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<i;){this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const r=this.isLoginPhase?t.ConnectionStatus.CONNECTING:t.ConnectionStatus.RECONNECTING;e.logger.warn("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:i,reason:s,nextStatus:r,...this.getReconnectDiagnostic()}),this.updateStatus(r,s,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(s)}catch(a){if(n=a,e.logger.warn("Connection attempt failed",{attempt:this.reconnectAttempts,reason:s,error:n}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(n))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(n)){o=n;break}}if(this.connectionRetry.getAttemptCount()>=i)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){e.logger.warn("Reconnect retry loop interrupted",{reason:s,attempt:this.reconnectAttempts,maxAttempts:i,...this.getReconnectDiagnostic()});break}await this.waitForReconnectDelay()}if(o){if(this.connection.error=o,r)throw this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.ERROR,!1),o;return this.reconnectPaused=!0,void this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.ERROR,!0)}if(r)throw this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.ERROR,!1),n??new e.ConnectionError("Connection failed",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,e.logger.warn("Reconnect attempts exhausted",{reason:s,attempt:this.reconnectAttempts,maxAttempts:i,lastError:n,...this.getReconnectDiagnostic()}),this.updateStatus(t.ConnectionStatus.RECONNECT_FAILED,t.ConnectionEventReason.LIMIT,!0)}finally{this.reconnectInProgress=!1,e.logger.warn("Reconnect flow finished",{reason:s,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(t.ConnectionEventReason.RECONNECT,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(s){this.updateStatus(t.ConnectionStatus.CONNECTED,s,!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),e.logger.warn("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}async triggerReconnect(s){e.logger.warn("Reconnect trigger received",{reason:s,...this.getReconnectDiagnostic()}),this.isLoggedIn?this.reconnectInProgress?e.logger.warn("Reconnect trigger skipped",{guard:"reconnect-in-progress",reason:s,...this.getReconnectDiagnostic()}):this.reconnectPaused?e.logger.warn("Reconnect trigger skipped",{guard:"reconnect-paused",reason:s,...this.getReconnectDiagnostic()}):(this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket&&this.closeWebSocket(s,!0,!0),await this.connectWithRetry(s,!1)):e.logger.warn("Reconnect trigger skipped",{guard:"not-logged-in",reason:s,...this.getReconnectDiagnostic()})}handleDisconnection(s){e.logger.warn("Connection disconnection handled",{reason:s,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t.ConnectionStatus.DISCONNECTED,s,!0),s!==t.ConnectionEventReason.TOKEN_EXPIRED&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(s))}closeWebSocket(e,s,r=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),r&&this.updateStatus(t.ConnectionStatus.DISCONNECTED,e,s)):r&&this.updateStatus(t.ConnectionStatus.DISCONNECTED,e,s)}createWebSocketConnection(){return new Promise((s,r)=>{const n=this.pickNextServerUrl();e.logger.debug("WebSocket connecting",{url:n}),this.clearSocketListeners();let o=!1;const i=setTimeout(()=>{o=!0,e.logger.warn("WebSocket connection attempt timed out",{url:n,connectTimeout:this.config.connectTimeout,...this.getReconnectDiagnostic()}),r(new e.ConnectionError("Connection timeout",{code:e.ERROR_CODES.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},this.config.connectTimeout);this.socketAdapter.connect({url:n,timeoutMs:this.config.connectTimeout}).then(a=>{if(clearTimeout(i),o||this.reconnectPaused)return e.logger.warn("WebSocket connection result discarded",{url:n,cancelled:o,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void a.close();this.websocket=a,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(a,this.socketGeneration),this.startProvision().then(()=>{if(this.resetProvisionHandlers(),o||this.reconnectPaused)return e.logger.warn("Provision result discarded",{url:n,cancelled:o,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void this.closeWebSocket(t.ConnectionEventReason.ERROR,!1,!1);s()}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(t.ConnectionEventReason.ERROR,!1,!1),r(e instanceof Error?e:new Error(String(e)))})}).catch(s=>{if(clearTimeout(i),o)return;const n=s instanceof e.ConnectionError?s:new e.ConnectionError("Failed to create WebSocket",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:s instanceof Error?s.message:String(s)}});this.handleConnectionError(n,t.ConnectionEventReason.ERROR),r(n)})}).catch(s=>{if(s instanceof e.ConnectionError)throw s;const r=new e.ConnectionError("Failed to create WebSocket",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:s instanceof Error?s.message:String(s)}});throw this.handleConnectionError(r,t.ConnectionEventReason.ERROR),r})}handleWebSocketClose(s){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(e.logger.warn("WebSocket closed",{code:s.code,reason:s.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(t.ConnectionEventReason.CLOSE))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new e.ConnectionError("Provision interrupted",{code:e.ERROR_CODES.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(t,s){if(e.logger.error("Connection error:",t),this.connection.error=t,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(s)}handleTerminalConnectionError(s,r){if(e.logger.warn("Terminal connection error received",{code:s.code,message:s.message,details:s.details}),this.connection.error=s,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(t.ConnectionStatus.DISCONNECTED,r,!0,!0)}async handleWebSocketMessage(s,r){try{if(r!==this.socketGeneration)return;e.logger.debug("WebSocket message received",{dataType:typeof s});const o=await this.msyncCodec.normalizeIncoming(s);if(r!==this.socketGeneration)return;if(e.logger.debug("handleWebSocketMessage data",{length:o.length}),!o.length)return;const i=this.msyncCodec.decompressIncoming(o);if(!i){const s=null!==this.provisionReject;return e.logger.error("Failed to decompress mSync payload, closing connection",{stage:s?"provision":"connected"}),void(s?(this.rejectPendingProvision(new e.ConnectionError("Failed to decompress Provision payload",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(t.ConnectionEventReason.ERROR,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(i))return void e.logger.debug("Ignore server normal close payload",{length:i.length});let a=null;try{a=this.msyncCodec.decodeMsync(i)}catch(n){const t=n instanceof Error?n:new Error("Failed to decode mSync payload");if(t instanceof RangeError)return void e.logger.warn("Discard invalid mSync payload",{length:i.length,message:t.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 e.logger.warn("Invalid mSync payload signature",{length:i.length,prefixHex:Array.from(i.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),t}switch(this.heartbeatManager.markAlive(),e.logger.debug("handleWebSocketMessage decoded",{command:a.command}),a.command){case B:this.handleProvisionMessage(a.payload);break;case G:this.handleLogoutMessage(a.payload);break;case F:this.handleNoticeMessage(a.payload);break;case x:this.handleUnreadMessage(a.payload);break;case k:this.handleSyncMessage(a.payload)}}catch(n){const s=n instanceof Error?n:new Error("Failed to handle mSync payload");e.logger.error("Failed to handle mSync payload",s),this.handleConnectionError(s,t.ConnectionEventReason.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 e.ConnectionError("Provision timeout",{code:e.ERROR_CODES.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},e.PROVISION_TIMEOUT);try{const t=this.msyncCodec.encodeProvision();e.logger.debug("startProvision provision",{length:t.length}),this.sendMsyncPayload(t)}catch{this.provisionReject?.(new e.ConnectionError("Provision send failed",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(t){const s=this.msyncCodec.decodeProvision(t);if(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),s.ok)this.msyncCodec.updateResource(s.resource),this.setupTokenLifecycleFromProvision(s.authToken),this.provisionResolve?.();else{e.logger.warn("Provision rejected",{statusCode:s.statusCode,reason:s.reason});const t=dt(s.statusCode,s.reason),r=t.code===e.ERROR_CODES.UNKNOWN?e.ERROR_CODES.CONNECTION_PROVISION_REJECTED:t.code;this.provisionReject?.(new e.ConnectionError("Provision rejected",{code:r,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,r=!!t&&this.isSelfQueue(t),n=!!t&&this.isQueueInList(t);t&&s&&(r||n||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(t){const{queues:s}=this.msyncCodec.decodeUnread(t),r=s.filter(e=>this.getQueueId(e));if(r.length){r.length!==s.length&&e.logger.warn("Unread queues without usable identity were ignored",{ignoredCount:s.length-r.length}),this.startOfflineMessageSync(r);for(const e of r)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(s){const r=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(s));if(r)return void this.handleTerminalConnectionError(r,t.ConnectionEventReason.ERROR);if(!this.messageReceiver)return;const n=this.messageReceiver.handleSyncPayload(s);if(e.logger.debug("handleSyncMessage result",{result:n}),!n)return;(void 0!==n.queue||void 0!==n.nextKey||void 0!==n.isLast)&&this.handleSyncQueueState(n)}handleSyncQueueState(t){e.logger.debug("[QueueSync] handleSyncQueueState",{isLast:t.isLast,nextKey:t.nextKey,queueName:t.queue?this.getQueueName(t.queue):null,queueId:t.queue?this.getQueueId(t.queue):null,queuesLength:this.queues.length});const s=this.resolveSyncQueueState(t);if(!s)return t.queue&&t.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):t.queue&&t.nextKey?void this.sendLastSession(t.queue,t.nextKey):void 0;const{queue:r,queueId:n}=s;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(n)){const e=this.offlineMessageQueueCounts.get(n)??0;this.offlineMessageQueueCounts.set(n,e+t.messages.length),this.offlineMessageTotalCount+=t.messages.length}const o=t.nextKey;if(t.isLast)return this.finishOfflineMessageQueue(n),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(o){if(o!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=o,this.currentQueueId=n,this.currentQueue=r,void this.sendLastSession(r,o);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(t){const s=t.queue&&"object"==typeof t.queue?t.queue:void 0,r=s?this.getQueueName(s):null,n=s?this.getQueueId(s):null,o=void 0!==s&&null!==n&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,s)));if(s&&n&&o)return{queue:s,queueId:n};const i=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=i??a??this.queues[0],d=c?this.getQueueName(c):null,l=c?this.getQueueId(c):null;return c&&l?(e.logger.warn("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:r,responseQueueId:n,fallbackQueueName:d,fallbackQueueId:l,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:t.isLast,hasNextKey:Boolean(t.nextKey)}),{queue:c,queueId:l}):null}handleLogoutMessage(t){const s=this.msyncCodec.decodeLogout(t);e.logger.warn("Logout message received",s)}resolveStatisticDisconnectError(t){for(const s of t)switch(s.operation){case 1:return new e.ConnectionError("User has been removed",{code:e.ERROR_CODES.USER_REMOVED,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 2:return new e.ConnectionError("The user is already logged on another device",{code:e.ERROR_CODES.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1,...s.reason?{loginInfoCustomExt:s.reason}:{}}});case 3:return new e.ConnectionError("The user was kicked by changing password",{code:e.ERROR_CODES.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 4:return new e.ConnectionError("The user was kicked by other device",{code:e.ERROR_CODES.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(t.ConnectionEventReason.CLOSE,!0,!0),this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.CLOSE,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),e.logger.warn("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){if(e.socketAdapter)return e.socketAdapter;const t=ss({webSocketCtor:"function"==typeof WebSocket?WebSocket:void 0});if(t)return t;throw s.createPlatformError("Socket capability is missing for current platform",{code:"PLATFORM_MISSING_CAPABILITY",stage:"socket",retryable:!1,details:{capability:"socket"}})}attachSocketListeners(s,r){this.clearSocketListeners(),this.socketDisposers=[s.onMessage(e=>{this.websocket===s&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(e,r)))}),s.onError(()=>{if(this.websocket!==s)return;e.logger.warn("WebSocket error",{stage:"ws"});const r=new e.ConnectionError("WebSocket connection error",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(r,t.ConnectionEventReason.ERROR)}),s.onClose(e=>{this.websocket===s&&this.handleWebSocketClose(e)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(t){if(this.websocket&&this.websocket.readyState===s.SOCKET_READY_STATE.OPEN)try{const s=this.msyncCodec.prepareOutgoing(t);e.logger.debug("WebSocket send payload",{length:s.length}),Promise.resolve(this.websocket.send(s)).catch(t=>{e.logger.error("Failed to send mSync payload",t),this.websocket?.close()})}catch(r){e.logger.error("Failed to send mSync payload",r),this.websocket?.close()}}sendBackqueue(t){this.currentQueue=t,this.currentQueueId=this.getQueueId(t),this.nextKey=null;const s=this.msyncCodec.encodeBackQueue(t);e.logger.debug("sendBackqueue payload",{length:s.length}),this.sendMsyncPayload(s)}sendLastSession(t,s){e.logger.debug("sendLastSession queue",{queueName:this.getQueueName(t),nextKey:s});const r=this.msyncCodec.encodeLastSession(t,s);this.sendMsyncPayload(r)}sendNextQueue(){e.logger.debug("sendNextQueue queues",{size:this.queues.length});const t=this.queues[0];t&&this.sendBackqueue(t)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(s){const r=new Set;for(const e of s){const t=this.getQueueId(e);t&&r.add(t)}if(0!==r.size){for(const e of r)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.startDataReportOperation({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of r){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(t.ConnectionEventName.OFFLINE_MESSAGE_SYNC_START,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const s=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:s}),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(t.ConnectionEventName.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),r=this.msyncCodec.getContext();return t===r.userId&&s===r.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"),r=this.getQueueResource(e);if(s)return`domain:${s}|resource:${r??""}`;if(r)return`resource:${r}`;const n=this.getQueueField(e,"appKey");return n?`appKey:${n}`: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),r=this.getQueueId(t);return null!==s&&s===r}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 Mo=new Uint8Array([99,109]),No=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Do=e=>Array.isArray(e)&&e.every(No),wo=e=>"string"==typeof e?e:void 0,Uo=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Lo=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},Po=(t,s)=>{const r=t[s],n=t[s+1],o=t[s+2],i=t[s+3];if("number"!=typeof r||"number"!=typeof n||"number"!=typeof o||"number"!=typeof i)throw new e.MessageReceiveError("Combine payload length header is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});return r<<24|n<<16|o<<8|i},ko=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},xo=(e,t)=>{const s=br().lookupType(e).decode(t);if(!No(s))throw new Error(`${e} decoded result is invalid`);return s},Fo=e=>No(e)&&"string"==typeof e.name?e.name:"",Bo=(t,s,r)=>{const n=(Do(t.contents)?t.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const o=(t=>{const s=Uo(t.type)??Y,r=Boolean(wo(t.remotePath))||Boolean(wo(t.title))||Boolean(wo(t.summary))||(Uo(t.combineLevel)??0)>0,n=s===Y&&0===t.subType&&r;if(s===ne||n){const e=Uo(t.combineLevel)??0;return{type:"combine",body:{title:wo(t.title)??"",summary:wo(t.summary)??"",filename:wo(t.displayName)??"combine",filetype:"application/octet-stream",url:wo(t.remotePath),secret:wo(t.secretKey),fileLength:Uo(t.fileLength),combineLevel:e},combineLevel:e}}if(s===Y)return{type:"text",body:{content:wo(t.text)??""}};if(s===se)return{type:"cmd",body:{action:wo(t.action)??""}};if(s===re){const e=Pr(Do(t.customExts)?t.customExts:void 0);return{type:"custom",body:{event:wo(t.customEvent)??"",params:e}}}if(s===Z)return{type:"location",body:{latitude:Uo(t.latitude)??0,longitude:Uo(t.longitude)??0,address:wo(t.address),buildingName:wo(t.buildingName)}};if(s===J){const s=No(t.size)?t.size:{},r=wo(t.remotePath)??"",n=e.deriveImageUrls(r),o=wo(t.thumbnailRemotePath),i=e.fromProtocolImageType(t.imageType)===e.IMAGE_TYPE_ORIGINAL;return{type:"image",body:{localUrl:"",filename:wo(t.displayName)??"image",filetype:"application/octet-stream",width:Uo(s.width)??0,height:Uo(s.height)??0,isGif:1===t.subType,isOriginalImage:i,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:wo(t.secretKey),fileLength:Uo(t.fileLength),thumbnailUrl:o??n.thumbnailUrl}}}if(s===X){const e=No(t.size)?t.size:{};return{type:"video",body:{url:wo(t.remotePath)??"",filename:wo(t.displayName)??"video",filetype:"application/octet-stream",duration:Uo(t.duration)??0,width:Uo(e.width),height:Uo(e.height),secret:wo(t.secretKey),fileLength:Uo(t.fileLength),thumbnailUrl:wo(t.thumbnailRemotePath)}}}if(s===ee)return{type:"voice",body:{url:wo(t.remotePath)??"",filename:wo(t.displayName)??"voice",filetype:"application/octet-stream",duration:Uo(t.duration)??0,secret:wo(t.secretKey),fileLength:Uo(t.fileLength)}};if(s===te)return{type:"file",body:{url:wo(t.remotePath)??"",filename:wo(t.displayName)??"file",filetype:"application/octet-stream",secret:wo(t.secretKey),fileLength:Uo(t.fileLength)}};return null})(n);if(!o)throw new Error("MessageBody content type is unsupported");const i=Fo(t.from)||Fo(r?.from)||`unknown-${s}`,a=Fo(t.to)||Fo(r?.to)||`unknown-${s}`,c=(d=t.type)===V?"groupChat":d===z?"chatRoom":"singleChat";var d;const l=a||i,u=Number(Ur(r?.timestamp))||Date.now(),h=Pr(Do(t.ext)?t.ext:void 0),p={msgServerId:Ur(r?.id),msgLocalId:"",type:o.type,sender:{userId:i},conversationId:l,conversationType:c,timestamp:u,body:o.body,ext:h};return"number"==typeof o.combineLevel&&(p.body.combineLevel=o.combineLevel),p},Go=(e,t)=>{const s=[];try{const n=xo("easemob.pb.Meta",e),o=(r=n.payload)instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):void 0;if(o&&o.length>0){const e=xo("easemob.pb.MessageBody",o);return Bo(e,t,n)}s.push("Meta payload is empty")}catch(n){s.push(n instanceof Error?n.message:String(n))}var r;try{const s=xo("easemob.pb.MessageBody",e);return Bo(s,t)}catch(n){s.push(n instanceof Error?n.message:String(n))}try{const s=xo("easemob.pb.MessageBody.Content",e);return Bo({type:K,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[s],ext:[]},t)}catch(n){s.push(n instanceof Error?n.message:String(n))}throw new Error(s.join("; "))},qo=(t,s)=>{const r=ht(t);try{const t=JSON.parse(r);if(!No(t))throw new e.MessageReceiveError("Combine payload item is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{index:s}});return t}catch(n){if(n instanceof e.MessageReceiveError)throw n;try{return Go(t,s)}catch(o){throw new e.MessageReceiveError("Combine payload item parse failed",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{index:s,cause:n instanceof Error?n.message:String(n),protobufCause:o instanceof Error?o.message:String(o)}})}}},Ko=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Vo{constructor(t,s,r,n){this.websocket=null,this.pendingMessages=new Map,this.ackTimeout=e.MESSAGE_TIMEOUT,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=s,this.eventHub=r,this.msyncCodec=t,this.attachmentUploader=n??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(t,r){const n=this.msyncCodec.toProtocolId(t.msgLocalId);if(P(t))throw new e.MessageSendError("Stream message send is not supported",{code:e.ERROR_CODES.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==s.SOCKET_READY_STATE.OPEN){const s=this.msyncCodec.toProtocolId(t.msgLocalId);throw new e.MessageSendError("WebSocket is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:s,retryable:!0}})}let o={...t,sendStatus:"sending"};an(t,o),e.logger.debug("Message send queued",{msgLocalId:t.msgLocalId,protocolId:n,type:t.type,conversationType:t.conversationType,conversationId:t.conversationId});try{const e="combine"===o.type?this.prepareCombineMessage(o):o,t={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,r):e,sendStatus:"sending"};an(o,t),o=t,r?.onSending?.(t);const s=await this.doSendMessage(t);return r?.onSuccess?.(s),s}catch(i){const e={...o,sendStatus:"failed"};throw an(o,e),r?.onFailed?.(e,i instanceof Error?i:new Error(String(i))),i}}async sendAction(t,s){const r=this.msyncCodec.toProtocolId(`${t.kind}:${t.messageId??t.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===t.kind&&e.logger.debug("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:r,conversationId:t.conversationId,conversationType:t.conversationType,sendToPeer:t.sendToPeer,clearAllUnreadMessageCount:t.clearAllUnreadMessageCount});const n=this.msyncCodec.encodeActionMessage(t,r);"clearAllConversationUnreadMessageCount"===t.kind&&e.logger.debug("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:r,payloadBytes:n.byteLength});const o="recall"===t.kind?"MSYNC_RECALLMESSAGE":"update"===t.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${t.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(r,n,s,this.createPendingDataReport({category:"message",operationName:o,operationType:"MESSAGE",requestName:o,msgId:t.messageId,messageType:Ko(t.conversationType)}))}async sendChatRoomOperation(e,t){const s=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),r=this.msyncCodec.encodeChatRoomOperation(e,s),n="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(s,r,t,this.createPendingDataReport({category:"chatroom",operationName:n,operationType:"CHATROOM",requestName:n,msgId:e.chatRoomId}))}async doSendMessage(t){const r=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:t.msgLocalId,messageType:Ko(t.conversationType)});return new Promise((n,o)=>{const i=this.msyncCodec.toProtocolId(t.msgLocalId),a=setTimeout(()=>{this.pendingMessages.delete(i),this.finishPendingDataReport(r,{code:e.ERROR_CODES.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),o(new e.MessageSendError("Message ACK timeout",{code:e.ERROR_CODES.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(i,{kind:"message",message:t,protocolId:i,timeoutId:a,resolve:e=>{clearTimeout(a),n(e)},reject:e=>{clearTimeout(a),o(e)},report:r});try{if(!this.websocket||this.websocket.readyState!==s.SOCKET_READY_STATE.OPEN)throw new e.MessageSendError("WebSocket is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}});const n=this.msyncCodec.encodeChatMessage(t,i),c=this.msyncCodec.prepareOutgoing(n);Promise.resolve(this.websocket.send(c)).catch(s=>{const n=s instanceof Error?s.message:String(s);this.pendingMessages.delete(i),clearTimeout(a),this.finishPendingDataReport(r,{code:-1,success:!1,description:n}),e.logger.warn("Message send socket failure",{msgLocalId:t.msgLocalId,protocolId:i,websocketReadyState:this.websocket?.readyState??null,cause:n}),o(new e.MessageSendError(`WebSocket send failed: ${n}`,{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0,cause:n}}))}),e.logger.debug("Message sent",{msgLocalId:t.msgLocalId,protocolId:i})}catch(c){if(this.pendingMessages.delete(i),clearTimeout(a),this.finishPendingDataReport(r,{code:c instanceof e.MessageSendError?c.code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,success:!1,description:c instanceof Error?c.message:String(c)}),c instanceof e.MessageSendError)throw c;throw new e.MessageSendError("Message encode failed",{code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,details:{msgLocalId:t.msgLocalId,protocolId:i,retryable:!0}})}})}async sendProtocolPayload(t,r,n,o){return new Promise((i,a)=>{const c=setTimeout(()=>{this.pendingMessages.delete(t),this.finishPendingDataReport(o,{code:e.ERROR_CODES.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),a(new e.MessageSendError("Message ACK timeout",{code:e.ERROR_CODES.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:o});try{if(!this.websocket||this.websocket.readyState!==s.SOCKET_READY_STATE.OPEN)throw new e.MessageSendError("WebSocket is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0}});const n=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(n)).catch(s=>{const r=s instanceof Error?s.message:String(s);this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(o,{code:-1,success:!1,description:r}),a(new e.MessageSendError(`WebSocket action send failed: ${r}`,{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0,cause:r}}))})}catch(d){if(this.pendingMessages.delete(t),clearTimeout(c),this.finishPendingDataReport(o,{code:d instanceof e.MessageSendError?d.code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof e.MessageSendError)throw d;a(new e.MessageSendError("Message encode failed",{code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,details:{protocolId:t,retryable:!1}}))}})}prepareCombineMessage(s){const r=s.body,n=r.messageList??[];t.validateCombineMessageList(n);const o=t.calculateCombineLevel(n);t.ensureCombineLevel(o);const i=(t=>{try{const s=t.map((t,s)=>{const r=JSON.stringify(t);if(!r)throw new e.MessageSendError("Combine payload item encode failed",{code:e.ERROR_CODES.COMBINE_ENCODE_FAILED,details:{index:s}});return ut(r)}),r=Mo.length+s.reduce((e,t)=>e+4+t.length,0)+1,n=new Uint8Array(r);let o=0;n.set(Mo,o),o+=Mo.length;for(const e of s){const t=Lo(e.length);n.set(t,o),o+=t.length,n.set(e,o),o+=e.length}const i=ko(n.subarray(0,n.length-1));return n[n.length-1]=i,n}catch(s){if(s instanceof e.MessageSendError)throw s;throw new e.MessageSendError("Combine payload encode failed",{code:e.ERROR_CODES.COMBINE_ENCODE_FAILED,details:{cause:s instanceof Error?s.message:String(s)}})}})(n),a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i);const c=new File([a],r.filename||"combine",{type:r.filetype||"application/octet-stream"}),d=t.createLocalFileUrl(c);if(!d&&!this.attachmentUploader)throw new e.MessageSendError("Combine payload local url generation failed",{code:e.ERROR_CODES.COMBINE_ENCODE_FAILED});t.attachmentFileStore.set(s.msgLocalId,c);const l={...s,body:{...r,combineLevel:o,fileLength:i.byteLength,filename:r.filename||"combine",filetype:r.filetype||"application/octet-stream",url:d??r.url}};return an(s,l),t.copyCombineCompatibleTextSidecar(s,l),l}handleAck(s,r,n,o){const i=this.pendingMessages.get(s);if(!i)return void e.logger.debug("Received ACK without a tracked pending message",{protocolId:s});if("action"===i.kind)return this.pendingMessages.delete(s),this.finishPendingDataReport(i.report,{code:200,success:!0}),void i.resolve({protocolId:s,serverId:r??"",statusCode:0,chatRoomInfo:o});const a={...i.message,...this.resolveReplacedMessage(i.message,n),sendStatus:"sent",msgServerId:r||n?.msgServerId||i.message.msgServerId};an(i.message,a),this.pendingMessages.delete(s),this.finishPendingDataReport(i.report,{code:200,success:!0}),"image"!==a.type&&"video"!==a.type&&"voice"!==a.type&&"file"!==a.type&&"combine"!==a.type||t.attachmentFileStore.delete(a.msgLocalId),e.logger.debug("Message ACK matched",{protocolId:s,msgLocalId:a.msgLocalId,msgServerId:a.msgServerId??null,type:a.type,conversationType:a.conversationType,conversationId:a.conversationId}),this.eventHub.dispatch(t.InternalEventName.MESSAGE_SENT,a),i.resolve(a)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(t,s){const r=this.pendingMessages.get(t);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(t),this.finishPendingDataReport(r.report,{code:s instanceof e.MessageSendError?s.code:-1,success:!1,description:s.message}),void r.reject(s);const n={...r.message,sendStatus:"failed"};an(r.message,n),this.pendingMessages.delete(t),this.finishPendingDataReport(r.report,{code:s instanceof e.MessageSendError?s.code:-1,success:!1,description:s.message}),e.logger.warn("Message send failed after ACK/error",{protocolId:t,msgLocalId:n.msgLocalId,type:n.type,conversationType:n.conversationType,conversationId:n.conversationId,error:s.message}),r.reject(s)}handleAckFailure(e,t,s,r){const n=this.pendingMessages.get(e);if(n)return"action"===n.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t,success:!1,description:s??r.message}),void n.reject(n.createAckError?.(t,s)??r)):void this.handleSendError(e,r)}setWebSocket(e){this.websocket=e}destroy(){for(const[t,s]of this.pendingMessages)clearTimeout(s.timeoutId),this.finishPendingDataReport(s.report,{code:-1,success:!1,description:"Message sender destroyed"}),s.reject(new e.MessageSendError("Message sender destroyed",{code:e.ERROR_CODES.MESSAGE_SENDER_DESTROYED,details:"message"===s.kind?{msgLocalId:s.message.msgLocalId,protocolId:t,retryable:!1}:{protocolId:t,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(t){if(("message"===t.category?this.messageReportCount:this.chatRoomReportCount)>=e.DATA_REPORT_CORRELATION_LIMIT){return void(("message"===t.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(e.logger.warn("DataReport correlation limit reached",{category:t.category}),"message"===t.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const s=e.startDataReportOperation({operationName:t.operationName,operationType:t.operationType,msgId:t.msgId,messageType:t.messageType});if(s)return"message"===t.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:t.category,operation:s,request:s.startRequest({requestName:t.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(t,s){t&&!t.released&&(t.released=!0,t.request.finish(s),t.operation.finish(s),"message"===t.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<e.DATA_REPORT_CORRELATION_LIMIT&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<e.DATA_REPORT_CORRELATION_LIMIT&&(this.chatRoomReportSaturated=!1)))}}class zo{constructor(e){this.sessions=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: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),r=t.stream.seq;return s.chunksBySeq.has(r)?{duplicate:!0,session:s}:(s.chunksBySeq.set(r,t),s.lastActivityTs=Date.now(),t.stream.status!==L.START&&t.stream.status!==L.START_COMPLETED||null!==s.startSeq||(s.startSeq=r),{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 r=[];for(;t.chunksBySeq.has(s);){const e=t.chunksBySeq.get(s);if(!e)break;r.push(e),s+=1}return r}markDispatched(e,t,s){const r=this.sessions.get(e);if(!r)return;const n=t.stream.seq;r.lastDispatchedSeq=Math.max(r.lastDispatchedSeq,n),r.fullText=s,r.chunksBySeq.delete(n)}markCompleted(e,t,s){const r=this.getOrCreate(e);r.completed=!0,r.completedReason=t,r.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,r]of this.sessions)r.lastActivityTs<t&&(t=r.lastActivityTs,e=s);e&&this.sessions.delete(e)}}class Ho{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new zo}handle(t){const s=this.resolveMessageId(t);if(!s)return void e.logger.warn("stream message id missing, skip dispatch");if(this.completedIds.has(s))return void e.logger.debug("stream message already completed, ignore",{msgId:s});if(t.stream.status===L.FULL)return void this.handleFullChunk(s,t);const r=this.cache.get(s);if(r?.completed)return void e.logger.debug("stream session completed, ignore chunk",{msgId:s,seq:t.stream.seq});const{duplicate:n}=this.cache.addChunk(s,t);n?e.logger.debug("stream duplicate chunk ignored",{msgId:s,seq:t.stream.seq}):t.stream.errorType>0?this.dispatchServerError(s,t):this.dispatchSequentialChunks(s)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(t){const s=this.cache.getSequentialChunks(t);if(0!==s.length)for(const e of s){const s=this.cache.get(t);if(!s)return;const r=s.fullText,n=e.stream.deltaText,i=`${r}${n}`,a=e.stream.errorType>0?L.ERROR:e.stream.status,c=this.buildDispatchMessage(e,{status:a,fullText:i,deltaText:n});if(this.eventHub.dispatch(o.ChatEventName.STREAM_MESSAGE,c),this.cache.markDispatched(t,e,i),a===L.START_COMPLETED||a===L.COMPLETED||a===L.ERROR){const e=a===L.ERROR?"timeout_error":"normal";return this.cache.markCompleted(t,e,i),this.cache.clear(t),void this.markCompleted(t)}}else e.logger.debug("stream chunks pending for missing seq",{msgId:t})}handleFullChunk(e,t){const s=this.cache.get(e),r=s?.fullText??"",n=this.resolveFullText(t,r),i=this.resolveDeltaText(r,n,t.stream.deltaText),a=!s||-1===s.lastDispatchedSeq&&0===s.chunksBySeq.size,c=t.stream.errorType>0?L.ERROR:a?L.START_COMPLETED:L.COMPLETED,d=this.buildDispatchMessage(t,{status:c,fullText:n,deltaText:i});this.eventHub.dispatch(o.ChatEventName.STREAM_MESSAGE,d);const l=c===L.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,l,n),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const s=this.cache.get(e),r=s?.fullText??"",n=this.resolveFullText(t,r),i=this.resolveDeltaText(r,n,t.stream.deltaText),a=this.buildDispatchMessage(t,{status:L.ERROR,fullText:n,deltaText:i});this.eventHub.dispatch(o.ChatEventName.STREAM_MESSAGE,a),this.cache.markCompleted(e,"timeout_error",n),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 r=e.body.content;return r&&r.length>=t.length?r:`${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 Wo{constructor(e=100){this.seenIds=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 jo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Qo{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new Ho(s),this.messageContexts=new Map,this.recentMessageIds=new Wo(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(t){try{e.logger.debug("handleSyncPayload payload",{length:t.length});const s=this.msyncCodec.decodeSync(t);e.logger.debug("handleSyncPayload result",{ack:Boolean(s.ack),messageCount:s.messages.length});const{ack:r,messages:n}=s;s.notifies&&s.notifies.length>0&&this.handleNotifies(s.notifies),r&&(e.logger.debug("Decoded sync ACK",{ok:r.ok,protocolId:r.protocolId,serverId:r.serverId??null,statusCode:r.statusCode??null,reason:r.reason??null,hasReplacedMessage:Boolean(s.replacedMessage)}),this.handleAck(r,s.replacedMessage));for(const e of n)this.dispatchMessage(e);return s}catch(s){e.logger.error("Failed to decode sync payload",s)}return null}handleAck(t,s){if(t.ok)return e.logger.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));e.logger.warn("ACK rejected",{protocolId:t.protocolId,statusCode:t.statusCode,reason:t.reason,hasReplacedMessage:Boolean(s)});const r=((t,s)=>{const r=dt(t,s),n=r.code===e.ERROR_CODES.UNKNOWN?e.ERROR_CODES.MESSAGE_SEND_FAILED:r.code;return{code:n,message:lt[n]??(s?`Message send failed: ${s}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(t.statusCode,t.reason),n=new e.MessageSendError(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,n)}dispatchMessage(t){if(P(t))return void this.streamMessageHandler.handle(t);this.rememberMessageContext(t),this.sendDeliveryAckIfNeeded(t);const s=this.resolveMessageContextId(t);this.recentMessageIds.checkAndRecord(s)?e.logger.debug("Duplicate message ignored",{messageId:s}):(this.eventHub.dispatch(o.ChatEventName.MESSAGE,t),e.logger.debug("Message received",{msgServerId:t.msgServerId}))}sendDeliveryAckIfNeeded(t){if(!this.enableDeliveryReceipt)return;if("singleChat"!==t.conversationType)return;const s=this.msyncCodec.getContext().userId;s&&t.from!==s&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:t.from,conversationType:"singleChat",messageId:t.msgServerId??t.msgLocalId}).catch(t=>{e.logger.warn("Failed to send delivery ack",t)})}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(o.ChatEventName.MESSAGE_READ_RECEIPTS,t)}handleUserInfoNotify(e){const s="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(!s)return;const r=e.data;if(!r||"object"!=typeof r)return;const n=r,o="string"==typeof n.username?n.username:"string"==typeof n.userId?n.userId:"user_metadata_updated"===s?this.msyncCodec.getContext().userId:"",i=n.metadata&&"object"==typeof n.metadata&&!Array.isArray(n.metadata)?n.metadata:null,a="number"==typeof n.lastModified?n.lastModified:"string"==typeof n.lastModified?Number(n.lastModified):Number.NaN;if(!o||!i||!Number.isFinite(a))return;const c={notifyType:s,userId:o,metadata:i,lastModified:a};this.eventHub.dispatch(t.InternalEventName.USER_INFO_NOTIFY,c)}handleContactNotify(t){if(e.logger.debug("[RosterSync] handleContactNotify",{eventName:t.eventName,type:t.type}),"string"!=typeof t.eventName)return;if(t.eventName!==o.ContactEventName.INVITED&&t.eventName!==o.ContactEventName.DELETED&&t.eventName!==o.ContactEventName.ADDED&&t.eventName!==o.ContactEventName.REFUSE&&t.eventName!==o.ContactEventName.AGREED)return;const s=t.data;if(!s||"object"!=typeof s)return;const r=s;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(t.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t,r=Array.isArray(s.values)?s.values:[];if(0===r.length)return;const n=[];for(const o of r){if(!o||"object"!=typeof o)continue;const e=o,t=this.normalizePresenceStatus(e.status),s="string"==typeof e.uid?e.uid:"";s&&n.push({userId:s,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==n.length&&this.eventHub.dispatch(o.PresenceEventName.STATUS_CHANGE,n)}handleGroupNotify(e){const s=e.data;if(!s||"object"!=typeof s)return;const r=s;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(t.InternalEventName.GROUP_NOTIFY,r)}handleChatRoomNotify(e){const s=e.data;if(!s||"object"!=typeof s)return;const r=s;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(t.InternalEventName.CHATROOM_NOTIFY,r)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const s of t){if(!jo(s)||"string"!=typeof s.messageId)continue;const e=this.resolveReactionConversationContext(s);e&&this.eventHub.dispatch(o.ChatEventName.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(!jo(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 r="string"==typeof t.ext?t.ext:"",n="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",a="string"==typeof t.id?t.id:"";r&&i&&a&&this.eventHub.dispatch(o.ChatEventName.PINNED_MESSAGE_CHANGED,{messageId:r,conversationId:"chat"===n?i:a,conversationType:"chat"===n?"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(!jo(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(!jo(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 r=s[0];if(!r)return null;const n=this.resolveMessageReceiptContext(r,t.conversationId,t.conversationType);if("groupChat"===n.conversationType){const e=new Set(s),r=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!jo(t))return[];const s=t.messageId,r=t.count;return"string"==typeof s&&e.has(s)&&"number"==typeof r&&Number.isInteger(r)&&r>=0?[{messageId:s,count:r}]:[]}):[];return{messageIds:s,conversationId:n.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:r}}return{messageIds:s,conversationId:n.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!jo(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(o.ChatEventName.MESSAGE_DELIVERED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!jo(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(o.ChatEventName.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(!jo(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!jo(t.message)||"string"!=typeof t.message.type||!jo(t.message.body)||!jo(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...jo(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(o.ChatEventName.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:r,...n}=t;return{...n,content:s}}handleChatThreadNotify(e){const s=e.data;if(!s||"object"!=typeof s)return;const r=s;"onChatThreadChange"===r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(t.InternalEventName.CHAT_THREAD_NOTIFY,r)}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 r=this.messageContexts.get(e);return r||("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:"",r="string"==typeof e.channel_type?e.channel_type:"";if(!t||!s)return null;if("groupChat"===r||"groupchat"===r||"group"===r)return{conversationId:s,conversationType:"groupChat",from:t,to:s};if(""!==r&&"chat"!==r&&"singleChat"!==r)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)jo(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)!jo(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 $o=e=>e instanceof Error?e.message:String(e);class Yo{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?$t({fetchImpl:fetch}):void 0))(e)}async downloadAndParse(s){const r=s.url.trim();if(!r)throw new e.ValidationError("Combine message url is required",{code:e.ERROR_CODES.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const n="number"==typeof s.maxItems?s.maxItems:t.MAX_COMBINE_MESSAGE_COUNT;t.ensureCombineItemLimit(1,n);const o=this.requestAdapter;if(!o)throw new e.MessageReceiveError("Request adapter is required for combine message download",{code:e.ERROR_CODES.COMBINE_DOWNLOAD_FAILED});const i=e.appendAttachUrlParams(r,s.secret);try{const r=await o.request({url:i,method:"GET",responseType:"arraybuffer",timeoutMs:s.timeoutMs??15e3,headers:{[e.REQUEST_ID_HEADER]:e.createTraceId()}});if(401===r.status||403===r.status)throw new e.AuthenticationError(401===r.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===r.status?e.ERROR_CODES.AUTH_UNAUTHORIZED:e.ERROR_CODES.AUTH_FORBIDDEN,details:{url:i,httpStatus:r.status}});if(r.status>=400)throw new e.MessageReceiveError("Combine payload download failed",{code:e.ERROR_CODES.COMBINE_DOWNLOAD_FAILED,details:{status:r.status,url:i}});const a=(t=>{if(t.length<Mo.length+1)throw new e.MessageReceiveError("Combine payload is too short",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const s=t.subarray(0,Mo.length);if(s[0]!==Mo[0]||s[1]!==Mo[1])throw new e.MessageReceiveError("Combine payload header is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const r=t.subarray(0,t.length-1),n=ko(r),o=t[t.length-1]??0;if(o!==n)throw new e.MessageReceiveError("Combine payload checksum failed",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{expectedChecksum:n,actualChecksum:o}});const i=[];let a=Mo.length;const c=t.length-1;for(;a<c;){if(a+4>c)throw new e.MessageReceiveError("Combine payload length header is incomplete",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const s=Po(t,a);if(a+=4,s<=0||a+s>c)throw new e.MessageReceiveError("Combine payload item length is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{itemLength:s}});const r=t.subarray(a,a+s);a+=s;const n=qo(r,i.length);i.push(n)}if(a!==c)throw new e.MessageReceiveError("Combine payload has unexpected trailing bytes",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{offset:a,expected:c}});return i})((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 ut(t);throw new e.MessageReceiveError("Combine payload response type is invalid",{code:e.ERROR_CODES.COMBINE_DOWNLOAD_FAILED})})(r.data));return t.ensureCombineItemLimit(a.length,n),t.validateCombineMessageList(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 e.ValidationError||a instanceof e.AuthenticationError||a instanceof e.MessageReceiveError)throw a;throw new e.MessageReceiveError("Combine payload download or parse failed",{code:e.ERROR_CODES.COMBINE_DOWNLOAD_FAILED,details:{cause:$o(a),url:i}})}}}const Jo=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"}},Xo=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 Zo{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?$t({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 e.ValidationError("message does not contain downloadable attachment",{code:e.ERROR_CODES.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:r,secret:n}=(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 e.ValidationError("attachment url is required",{code:e.ERROR_CODES.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});if(!this.requestAdapter)throw new e.NetworkError("request adapter is required for attachment download");const o=await this.requestAdapter.request({url:e.appendAttachUrlParams(r,n),method:"GET",responseType:"arraybuffer",timeoutMs:s,headers:{[e.REQUEST_ID_HEADER]:e.createTraceId()}});if(401===o.status)throw new e.AuthenticationError("attachment download unauthorized",{code:e.ERROR_CODES.AUTH_UNAUTHORIZED,details:{url:r,httpStatus:o.status}});if(403===o.status)throw new e.AuthenticationError("attachment download forbidden",{code:e.ERROR_CODES.AUTH_FORBIDDEN,details:{url:r,httpStatus:o.status}});if(404===o.status){const t=("string"==typeof o.data?o.data:"").includes("expired");throw new e.SDKError(t?"attachment file is expired":"attachment not found",t?e.ERROR_CODES.ATTACHMENT_EXPIRED:e.ERROR_CODES.ATTACHMENT_NOT_FOUND)}if(429===o.status)throw new e.SDKError("attachment download rate limited",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED);if(o.status>=400)throw new e.SDKError("attachment download failed",e.ERROR_CODES.FILE_DOWNLOAD_FAILED,{details:{status:o.status,url:r}});return{filename:Jo(t),mimeType:Xo(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 ei=(t,s,r)=>({Authorization:`Bearer ${t}`,Accept:s,[e.REQUEST_ID_HEADER]:e.createTraceId(),...r??{}}),ti=async t=>{const s=ei(t.token,"application/json",t.headers),r=Date.now(),n="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:n,method:t.method,url:t.url});let i=0;if(e.logger.debug("Upload request start",{operation:t.operation,method:t.method}),t.requestAdapter)try{const n=await t.requestAdapter.request({url:t.url,method:t.method,headers:s,responseType:"json",timeoutMs:e.UPLOAD_TIMEOUT});i=n.status;const c=Date.now()-r;if(n.status<200||n.status>=300)throw e.logger.warn("Upload response error",{operation:t.operation,method:t.method,status:n.status,duration:c}),new e.UploadError("Upload request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:n.status}});e.logger.debug("Upload response success",{operation:t.operation,method:t.method,status:n.status,duration:c});const d="string"==typeof(a=n.data)?JSON.parse(a):a;return o?.finish({code:n.status,success:!0}),d}catch(l){if(o?.finish({code:0!==i?i:l instanceof e.UploadError?l.code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,success:!1,description:l instanceof Error?l.message:String(l)}),l instanceof e.UploadError)throw l;throw e.logger.warn("Upload request failed",{operation:t.operation,method:t.method}),new e.UploadError("Upload request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}var a;const c=new AbortController,d=setTimeout(()=>c.abort(),e.UPLOAD_TIMEOUT);try{const n=await fetch(t.url,{method:t.method,headers:s,signal:c.signal});i=n.status;const a=Date.now()-r;if(!n.ok)throw e.logger.warn("Upload response error",{operation:t.operation,method:t.method,status:n.status,duration:a}),new e.UploadError("Upload request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:n.status}});return e.logger.debug("Upload response success",{operation:t.operation,method:t.method,status:n.status,duration:a}),o?.finish({code:n.status,success:!0}),await n.json()}catch(l){if(o?.finish({code:0!==i?i:l instanceof e.UploadError?l.code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,success:!1,description:l instanceof Error?l.message:String(l)}),l instanceof e.UploadError)throw l;if(l instanceof Error&&"AbortError"===l.name)throw e.logger.warn("Upload request timeout",{operation:t.operation,method:t.method,timeout:e.UPLOAD_TIMEOUT}),new e.UploadError("Upload timeout",{code:e.ERROR_CODES.UPLOAD_TIMEOUT,details:{url:t.url,timeout:e.UPLOAD_TIMEOUT}});throw e.logger.warn("Upload request failed",{operation:t.operation,method:t.method}),new e.UploadError("Upload request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}finally{clearTimeout(d)}},si=(t,s,r,n,o,i)=>new Promise((a,c)=>{const d=new XMLHttpRequest,l=Date.now(),u=i?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:t});e.logger.debug("Upload part start",{operation:"upload.multipart.part",partNumber:r}),d.upload&&o&&d.upload.addEventListener("progress",e=>{o(e.loaded)},!1),d.addEventListener("abort",()=>{u?.finish({code:e.ERROR_CODES.UPLOAD_ABORTED,success:!1,description:"Upload aborted"}),e.logger.warn("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),c(new e.UploadError("Upload aborted",{code:e.ERROR_CODES.UPLOAD_ABORTED,details:{url:t,partNumber:r}}))},!1),d.addEventListener("error",()=>{u?.finish({code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,success:!1,description:"Upload part failed"}),e.logger.warn("Upload part failed",{operation:"upload.multipart.part",partNumber:r}),c(new e.UploadError("Upload part failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t,partNumber:r}}))},!1),d.addEventListener("timeout",()=>{u?.finish({code:e.ERROR_CODES.UPLOAD_TIMEOUT,success:!1,description:"Upload timeout"}),e.logger.warn("Upload part timeout",{operation:"upload.multipart.part",partNumber:r,timeout:e.UPLOAD_TIMEOUT}),c(new e.UploadError("Upload timeout",{code:e.ERROR_CODES.UPLOAD_TIMEOUT,details:{url:t,partNumber:r}}))},!1),d.addEventListener("load",()=>{const s=Date.now()-l;if(200!==d.status)return u?.finish({code:d.status,success:!1,description:"Upload part failed"}),e.logger.warn("Upload part error",{operation:"upload.multipart.part",partNumber:r,status:d.status,duration:s}),void c(new e.UploadError("Upload part failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t,partNumber:r,status:d.status}}));e.logger.debug("Upload part success",{operation:"upload.multipart.part",partNumber:r,duration:s}),u?.finish({code:d.status,success:!0}),a()},!1);const h=new FormData;h.append("part_file",n),h.append("part_number",r),d.timeout=e.UPLOAD_TIMEOUT,d.open("PUT",t),Object.entries(ei(s,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{d.setRequestHeader(e,t)}),d.send(h)}),ri=async t=>{if(t.fileSize<=e.MULTIPART_THRESHOLD)throw new e.UploadError("Multipart not required",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:s,file:r,conversationId:n,conversationType:o,fileName:i,fileType:a,fileSize:c,messageType:d,imageType:l,md5:u,width:h,height:p}=t,{orgName:m,appName:g}=e.parseAppKey(s.appKey),f=`${s.restBaseUrl}/${m}/${g}/sdk/chatfiles/part-upload`;let y;try{y=await ti({url:f,method:"POST",token:s.token,operation:"upload.multipart.init",requestAdapter:s.requestAdapter,dataReportOperation:t.dataReportOperation})}catch(M){throw new e.UploadError("Multipart init failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:M,url:f}})}const E=(t=>{const s=t.entities?.[0],r="number"==typeof s?.file_upper_limit?s.file_upper_limit:0,n="number"==typeof s?.part_lower_limit?s.part_lower_limit:e.DEFAULT_PART_SIZE,o="string"==typeof s?.uuid?s.uuid:"";if(!o)throw new e.UploadError("Multipart init failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{response:t}});return{fileMaxSize:r,partMinSize:n,uuid:o}})(y);if(E.fileMaxSize&&c>E.fileMaxSize)throw new e.UploadError("File size exceeds limit",{code:e.ERROR_CODES.UPLOAD_SIZE_EXCEEDED,details:{fileSize:c,maxSize:E.fileMaxSize}});const R=E.partMinSize||e.DEFAULT_PART_SIZE,I=Math.ceil(c/R),v=Array.from({length:I},()=>0),S=`${s.restBaseUrl}/${m}/${g}/sdk/chatfiles/part-upload/${E.uuid}`,C=[],T=(e,s)=>{v[e]=s;const r=v.reduce((e,t)=>e+t,0),n=c?r/c*100:void 0;t.callbacks?.onFileUploadProgress?.({loaded:r,total:c,percent:n})};for(let N=0;N<I;N+=1){const n=N*R,o=Math.min(c,n+R),i=r.slice(n,o),a=String(N+1),d=si(S,s.token,a,i,e=>T(N,e),t.dataReportOperation).finally(()=>{const e=C.indexOf(d);e>=0&&C.splice(e,1)});C.push(d),C.length>=e.MAX_POOL&&await Promise.race(C)}await Promise.all(C);const A=e.toUploadChatType(o),O=e.appendUrlQueryParams(`${s.restBaseUrl}/${m}/${g}/sdk/chatfiles/part-upload/${E.uuid}`,{"restrict-access":"true","chat-type":A,"chat-target":n,"thumbnail-width":t.thumbnailWidth,"thumbnail-height":t.thumbnailHeight,md5:u??"",..."image"===d?{imageType:e.toUploadImageType(l),width:h,height:p}:{}}),b=await ti({url:O,method:"POST",token:s.token,operation:"upload.multipart.complete",requestAdapter:s.requestAdapter,dataReportOperation:t.dataReportOperation}),_=e.buildUploadResult({response:b,restBaseUrl:s.restBaseUrl,orgName:m,appName:g,fileType:a,fileName:i,fallbackSize:c,messageType:d,imageType:l,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(_),_},ni=t=>new Promise((s,r)=>{const{config:n,file:o,conversationId:i,conversationType:a,messageType:c,imageType:d,md5:l,width:u,height:h,fileName:p,fileType:m,fileSize:g}=t,{orgName:f,appName:y}=e.parseAppKey(n.appKey),E=e.toUploadChatType(a),R=e.appendUrlQueryParams(`${n.restBaseUrl}/${f}/${y}/chatfiles`,{"chat-type":E,"chat-target":i,md5:l??"",..."image"===c?{imageType:e.toUploadImageType(d),width:u,height:h}:{}}),I=Date.now(),v=t.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:R});e.logger.debug("Upload request start",{operation:"upload.simple",method:"POST",fileSize:g,messageType:c});const S=new XMLHttpRequest;S.upload&&t.callbacks?.onFileUploadProgress&&S.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),S.addEventListener("abort",()=>{v?.finish({code:e.ERROR_CODES.UPLOAD_ABORTED,success:!1,description:"Upload canceled"}),e.logger.warn("Upload request aborted",{operation:"upload.simple"}),t.callbacks?.onFileUploadCanceled?.(),r(new e.UploadError("Upload canceled",{code:e.ERROR_CODES.UPLOAD_ABORTED,details:{url:R}}))},!1),S.addEventListener("error",()=>{v?.finish({code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,success:!1,description:"Upload failed"}),e.logger.warn("Upload request failed",{operation:"upload.simple"}),r(new e.UploadError("Upload failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:R}}))},!1),S.addEventListener("timeout",()=>{v?.finish({code:e.ERROR_CODES.UPLOAD_TIMEOUT,success:!1,description:"Upload timeout"}),e.logger.warn("Upload request timeout",{operation:"upload.simple",timeout:e.UPLOAD_TIMEOUT}),r(new e.UploadError("Upload timeout",{code:e.ERROR_CODES.UPLOAD_TIMEOUT,details:{url:R,timeout:e.UPLOAD_TIMEOUT}}))},!1),S.addEventListener("load",()=>{try{const r=Date.now()-I,o=JSON.parse(S.responseText);if(S.status>=400)throw v?.finish({code:S.status,success:!1,description:"Upload failed"}),e.logger.warn("Upload response error",{operation:"upload.simple",status:S.status,duration:r}),new e.UploadError("Upload failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{status:S.status,response:o}});e.logger.debug("Upload response success",{operation:"upload.simple",status:S.status,duration:r});const i=e.buildUploadResult({response:o,restBaseUrl:n.restBaseUrl,orgName:f,appName:y,fileType:m,fileName:p,fallbackSize:g,messageType:c,imageType:d,useCustomAttachmentUpload:n.useCustomAttachmentUpload});t.callbacks?.onFileUploadComplete?.(i),v?.finish({code:S.status||200,success:!0}),s(i)}catch(o){v?.finish({code:o instanceof e.UploadError?o.code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,success:!1,description:o instanceof Error?o.message:String(o)}),r(o instanceof Error?o:new Error(String(o)))}},!1),S.timeout=e.UPLOAD_TIMEOUT,S.open("POST",R),S.setRequestHeader("restrict-access","true"),S.setRequestHeader("Accept","*/*"),S.setRequestHeader("Authorization",`Bearer ${n.token}`),S.setRequestHeader(e.REQUEST_ID_HEADER,e.createTraceId());const C=new FormData;C.append("file",o,p),void 0!==t.thumbnailWidth&&C.append("thumbnail-width",String(t.thumbnailWidth)),void 0!==t.thumbnailHeight&&C.append("thumbnail-height",String(t.thumbnailHeight)),S.send(C)}),oi=Ss(),ii=e=>Object.prototype.toString.call(e),ai=e=>{const t=e&&"object"==typeof e?e:null,s="string"==typeof t?.path?t.path:void 0,r="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,o="string"==typeof t?.type?t.type:void 0,i="number"==typeof t?.size?t.size:void 0;return{kind:ii(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 r&&r.length>0,uriPrefix:r?r.slice(0,48):void 0,name:n,type:o,size:i}},ci=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}),di=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,li=e=>"object"==typeof e&&null!==e,ui=(e,t)=>{const r=li(t)?t:void 0,n=r?.code===s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY&&r.stage===s.PLATFORM_ERROR_STAGE.RUNTIME;return"miniapp-path"===e&&(e=>{if(!li(e))return!1;const t=li(e.details)?e.details:void 0;return e.code===s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY&&e.stage===s.PLATFORM_ERROR_STAGE.RUNTIME&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&n};class hi{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(r,n){if(!di(r.type))return r;const o=r.body;if(this.hasUploadedRemoteResource(r.type,o))return r;const i=this.resolveUploadUrl(r.type,o),a=t.attachmentFileStore.get(r.msgLocalId),c=Boolean(a);if(e.logger.warn("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:r.msgLocalId,messageType:r.type,conversationType:r.conversationType,hasFile:c,uploadUrl:i,cachedFile:ai(a),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}}),!e.shouldUploadByUrl(i,c))return r;if(!a)throw new e.UploadError("Attachment file is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:r.msgLocalId,url:i}});if(!this.config?.restBaseUrl)throw new e.UploadError("REST base url is required for upload",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let d,l,u;try{d=await this.prepareAttachmentUpload(r,o,a),d.precheck?.hit||(u=e.startDataReportOperation({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:r.msgLocalId,messageType:r.type})),l=d.precheck?.hit?this.buildPrecheckedUploadResult(r,d,n):await this.uploadAttachment(r,d,n,u),u?.finish({code:0,success:!0})}catch(h){const t=s.mapUploadAdapterError(h);throw u?.finish({code:t.code,success:!1,description:t.message}),t.code===e.ERROR_CODES.UPLOAD_ABORTED&&n?.onFileUploadCanceled?.(),n?.onFileUploadError?.(t),t}return this.buildPreparedMessage(r,d,l)}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(t,s){if("image"===t){const t=s;return"string"==typeof t.originalImageUrl&&e.isRemoteUrl(t.originalImageUrl)}return"url"in s&&"string"==typeof s.url&&e.isRemoteUrl(s.url)}async prepareAttachmentUpload(t,s,r){const n=e.normalizeAttachmentFile(r,s);if(e.logger.warn("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:t.type,fileInfo:ci(n)}),"image"!==t.type){return{body:s,fileInfo:n,md5FileInfo:n,precheck:await this.maybePrecheck(t,n,n,void 0)}}const o=s,i=await this.resolveImageCandidate(o,n),a={...o,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===e.IMAGE_TYPE_ORIGINAL},c=await this.maybePrecheck(t,i.fileInfo,n,i.imagePolicy.resolvedImageType);return{body:a,fileInfo:i.fileInfo,md5FileInfo:n,imageType:i.imagePolicy.resolvedImageType,precheck:c,originalWidth:o.width,originalHeight:o.height}}async resolveImageCandidate(t,s){const r=e.resolveImageSendPolicy(t);if(e.logger.warn("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:t.isGif,source:ci(s)}),r.resolvedImageType===e.IMAGE_TYPE_ORIGINAL){let n=t.width,o=t.height;if(!n||!o){const t=this.resolveImageProcessor(s.source.sourceType);e.logger.warn("Image original info resolving",{operation:"upload.image.info",processorSourceType:s.source.sourceType,source:ci(s)});const r=await t.getImageInfo(s.source);n=r.width,o=r.height}return{imagePolicy:r,sourceKind:"origin",fileInfo:s,width:n,height:o}}try{const t=this.resolveImageProcessor(s.source.sourceType);e.logger.warn("Image big generation start",{operation:"upload.image.big.start",processorSourceType:s.source.sourceType,source:ci(s)});const n=await t.generateBigImage(s.source,{maxShortEdge:720,quality:.85});return{imagePolicy:r,sourceKind:"big",fileInfo:{source:n.source,fileName:n.fileName??s.fileName,fileType:n.fileType??s.fileType,fileSize:n.fileSize??s.fileSize,webFile:n.webFile},width:n.width,height:n.height}}catch(n){return e.logger.warn("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:n instanceof Error?n.message:String(n),source:ci(s)}),{imagePolicy:{resolvedImageType:e.IMAGE_TYPE_ORIGINAL,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:s,width:t.width??0,height:t.height??0}}}async maybePrecheck(t,s,r,n){if(!di(t.type))return;if(!0!==this.config?.enableMd5Check)return void e.logger.debug("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:t.type,imageType:n,fileSize:s.fileSize});const o=e.buildAttachmentPrecheckDecision({messageType:t.type,fileSize:s.fileSize,imageType:n});if(!o.shouldPrecheck)return void e.logger.debug("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:t.type,imageType:n,fileSize:s.fileSize,thresholdBytes:o.thresholdBytes});let i;try{i=await this.computeMd5(r)}catch(c){if(ui(r.source.sourceType,c))return void e.logger.warn("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:t.type,imageType:n,thresholdType:o.thresholdType,source:ci(r),error:c instanceof Error?c.message:String(c)});throw c}const a=await this.requestPrecheck(t,o.thresholdType,i,n);return e.logger.debug(a.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:a.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:t.type,imageType:n,exists:a.exists,existsType:a.existsType,uuid:a.uuid,hasShareSecret:"string"==typeof a.shareSecret&&a.shareSecret.length>0}),{...a,md5:i}}async computeMd5(t){const s=this.resolveImageProcessor(t.source.sourceType);return e.logger.warn("Attachment md5 compute start",{operation:"upload.md5.start",source:ci(t)}),s.computeMd5(t.source)}resolveImageProcessor(t){if(this.config?.imageProcessor)return e.logger.warn("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:t,processor:"platform"}),this.config.imageProcessor;if("web-file"===t)return e.logger.warn("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:t,processor:"web-fallback"}),oi;throw e.logger.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:t}),s.createPlatformError("Image processor capability is missing for current platform",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{capability:"imageProcessor",sourceType:t}})}async requestPrecheck(t,s,r,n){if(!this.config)throw new e.UploadError("Upload config is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:o,appName:i}=e.parseAppKey(this.config.appKey),a=e.appendUrlQueryParams(`${this.config.restBaseUrl}/${o}/${i}/chatfiles/exists`,{md5:r,..."image"===t.type?{imageType:e.toUploadImageType(n)}:{}}),c=await this.requestJson({url:a,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(o=>{e.logger.warn("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:t.type,imageType:n,thresholdType:s,md5:r,error:o instanceof Error?o.message:String(o)})});return c?e.parseAttachmentPrecheckResult(c):{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 r=await t.request({url:s.url,method:s.method,headers:s.headers,responseType:"json",timeoutMs:e.UPLOAD_TIMEOUT});if(r.status>=400)throw new e.UploadError("Upload precheck request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:r.status,operation:s.operation}});return r.data}async requestByFetch(t){if("function"!=typeof fetch)throw s.createPlatformError("Request capability is missing for current platform",{code:s.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:s.PLATFORM_ERROR_STAGE.REQUEST,retryable:!1,details:{operation:t.operation}});const r=new AbortController,n=setTimeout(()=>r.abort(),e.UPLOAD_TIMEOUT);try{const s=await fetch(t.url,{method:t.method,headers:t.headers,signal:r.signal});if(!s.ok)throw new e.UploadError("Upload precheck request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:s.status,operation:t.operation}});return await s.json()}finally{clearTimeout(n)}}buildPrecheckedUploadResult(t,s,r){if(!this.config||!s.precheck)throw new e.UploadError("Precheck result is required",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED});if(!s.precheck.uuid)throw new e.UploadError("Precheck hit missing uuid",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{precheck:s.precheck}});if(!di(t.type))throw new e.UploadError("Attachment message type is invalid",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const{orgName:n,appName:o}=e.parseAppKey(this.config.appKey),i="image"===t.type?s.precheck.existsType??s.imageType:void 0,a="image"===t.type&&i===e.IMAGE_TYPE_ORIGINAL?s.md5FileInfo:s.fileInfo,c="image"===t.type&&i===e.IMAGE_TYPE_ORIGINAL?s.originalWidth:"image"===t.type?s.body.width:void 0,d="image"===t.type&&i===e.IMAGE_TYPE_ORIGINAL?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=e.buildUploadResult({response:l,restBaseUrl:this.config.restBaseUrl,orgName:n,appName:o,fileType:a.fileType,fileName:a.fileName,fallbackSize:a.fileSize,messageType:t.type,imageType:i,width:c,height:d,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(t,s,r,n){if(!this.config)throw new e.UploadError("Upload config is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING});if(!di(t.type))throw new e.UploadError("Attachment message type is invalid",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const o=t.type,i=await this.resolveUploadMetadata(o,s);if(this.config.uploadAdapter)return e.logger.warn("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:o,source:ci(s.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,t,s,i,r);if(!s.fileInfo.webFile)throw new e.UploadError("Upload adapter is required for non-web file source",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:s.fileInfo.source.sourceType}});const a={message:t,file:s.fileInfo.webFile,conversationId:t.conversationId,conversationType:t.conversationType,messageType:o,imageType:s.imageType,md5:i.md5,width:i.width,height:i.height,fileName:s.fileInfo.fileName,fileType:s.fileInfo.fileType,fileSize:s.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(o,s.body),thumbnailHeight:this.resolveThumbnailHeight(o,s.body),callbacks:r,config:this.config,dataReportOperation:n},c=!1!==this.config?.enableMultipartUpload,d=c&&s.fileInfo.fileSize>e.MULTIPART_THRESHOLD;if(e.logger.warn("Attachment web upload selected",{operation:"upload.web.selected",messageType:o,source:ci(s.fileInfo),multipartEnabled:c,uploadMode:d?"multipart":"simple"}),d)try{return await ri(a)}catch(l){const t=l instanceof e.UploadError?l.details:void 0;if(t&&"object"==typeof t&&"init"===t.stage)return ni(a);throw l}return ni(a)}async uploadByAdapter(t,s,r,n,o){if(!this.config)throw new e.UploadError("Upload config is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:a}=e.parseAppKey(this.config.appKey),c=e.toUploadChatType(s.conversationType);if(!di(s.type))throw new e.UploadError("Attachment message type is invalid",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:s.type}});const d=s.type,l=e.appendUrlQueryParams(`${this.config.restBaseUrl}/${i}/${a}/chatfiles`,{"chat-type":c,"chat-target":s.conversationId,md5:n.md5,..."image"===d?{imageType:e.toUploadImageType(r.imageType),width:n.width,height:n.height}:{}}),u={},h={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[e.REQUEST_ID_HEADER]:e.createTraceId()},p=this.resolveThumbnailWidth(d,r.body),m=this.resolveThumbnailHeight(d,r.body);void 0!==p&&(u["thumbnail-width"]=String(p)),void 0!==m&&(u["thumbnail-height"]=String(m)),e.logger.warn("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:d,source:ci(r.fileInfo),uploadUrl:l,fields:u});const g=await t.upload({url:l,headers:h,source:r.fileInfo.source,fields:u,onProgress:e=>{o?.onFileUploadProgress?.(e)}});if(g.status>=400){const t=g.body??"",s=413===g.status?e.ERROR_CODES.FILE_TOO_LARGE:"string"==typeof t&&t.includes("content improper")?e.ERROR_CODES.FILE_CONTENT_IMPROPER:e.ERROR_CODES.UPLOAD_REQUEST_FAILED;throw new e.UploadError("Upload failed",{code:s,details:{status:g.status,response:g.body}})}let f;try{f=JSON.parse(g.body)}catch(E){throw new e.UploadError("Upload response parse failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{response:g.body,cause:E instanceof Error?E.message:String(E)}})}const y=e.buildUploadResult({response:f,restBaseUrl:this.config.restBaseUrl,orgName:i,appName:a,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:d,imageType:r.imageType,width:n.width,height:n.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return o?.onFileUploadComplete?.(y),y}buildPreparedMessage(e,s,r){if("image"===e.type){const n=s.body,o={...e,body:{...n,isOriginalImage:r.isOriginalImage??n.isOriginalImage,originalImageUrl:r.originalImageUrl??n.originalImageUrl,bigImageUrl:r.bigImageUrl??n.bigImageUrl,secret:r.secret??n.secret,fileLength:r.fileLength??n.fileLength??s.fileInfo.fileSize,filetype:r.filetype??n.filetype,filename:r.filename??n.filename,thumbnailUrl:r.thumbnailUrl??n.thumbnailUrl,width:r.width??n.width,height:r.height??n.height}};return an(e,o),t.copyCombineCompatibleTextSidecar(e,o),o}if("video"===e.type){const t=s.body,n={...e,body:{...t,url:r.url,secret:r.secret??t.secret,fileLength:r.fileLength??t.fileLength??s.fileInfo.fileSize,filetype:r.filetype??t.filetype,filename:r.filename??t.filename,thumbnailUrl:r.thumbnailUrl??t.thumbnailUrl}};return an(e,n),n}if("voice"===e.type){const t=s.body,n={...e,body:{...t,url:r.url,secret:r.secret??t.secret,fileLength:r.fileLength??t.fileLength??s.fileInfo.fileSize,filetype:r.filetype??t.filetype,filename:r.filename??t.filename}};return an(e,n),n}if("combine"===e.type){const t=s.body,n={...e,body:{...t,url:r.url,secret:r.secret??t.secret,fileLength:r.fileLength??t.fileLength??s.fileInfo.fileSize,filetype:r.filetype??t.filetype,filename:r.filename??t.filename}};return an(e,n),n}const n=s.body,o={...e,body:{...n,url:r.url,secret:r.secret??n.secret,fileLength:r.fileLength??n.fileLength??s.fileInfo.fileSize,filetype:r.filetype??n.filetype,filename:r.filename??n.filename}};return an(e,o),o}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(t,s){let r=s.precheck?.md5??"";if(!s.precheck)try{r=await this.computeMd5(s.md5FileInfo)}catch(o){if(!ui(s.md5FileInfo.source.sourceType,o))throw o;e.logger.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:t,source:ci(s.md5FileInfo),error:o instanceof Error?o.message:String(o)})}const n=s.body;return{md5:r,width:"image"===t&&"number"==typeof n.width&&n.width>0?n.width:void 0,height:"image"===t&&"number"==typeof n.height&&n.height>0?n.height:void 0}}}class pi{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 mi="__internal:core";class gi{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 _o({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),r=e.restBaseUrl?new hi({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 Vo(s,null,this.eventHub,r),this.messageReceiver=new Qo(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Yo(e.platformAdapter?.request),this.attachmentDownloader=new Zo(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(mi,{[t.ConnectionEventName.CONNECTED]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[t.ConnectionEventName.DISCONNECTED]:e=>{this.messageSender.setWebSocket(null)},[t.ConnectionEventName.RECONNECT_FAILED]:e=>{this.messageSender.setWebSocket(null)},[t.InternalEventName.MESSAGE_SENT]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new pi(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(mi),t.attachmentFileStore.clear()}}const fi=e=>{if(e.length>=1048576){const t=[],s=32768;for(let r=0;r<e.length;r+=s)t.push(String.fromCharCode(...e.subarray(r,r+s)));return btoa(t.join(""))}let t="";for(let s=0;s<e.length;s+=1){const r=e[s];void 0!==r&&(t+=String.fromCharCode(r))}return btoa(t)},yi=e=>{const t=new Uint8Array(n.lightExports.util.base64.length(e));return n.lightExports.util.base64.decode(e,t,0),t};class Ei{getCrypto(){return e.getRuntimeGlobal().crypto}constructor(t,r){if(this.enabled=(()=>{const t=e.getRuntimeGlobal();if([t.wx,t.qq,t.tt,t.swan,t.my,t.dd,t.jd,t.ks,t.uni].some(e=>void 0!==e))return!1;const r=_t(t);if("web"!==r.framework&&"worker"!==r.framework&&r.platform!==s.RUNTIME_PLATFORMS.ELECTRON_RENDERER)return!1;const n=t.crypto;return void 0!==n&&void 0!==n.subtle&&"function"==typeof n.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const e=`${t}:${r}`;this.keyPromise=this.deriveKey(e)}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,r=this.getCrypto().getRandomValues(new Uint8Array(12)),n=s.encode(e),o=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:r},t,n),i={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:fi(r),ct:fi(new Uint8Array(o))};return JSON.stringify(i)}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=yi(t.iv),r=yi(t.ct),n=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:s},e,r);return(new TextDecoder).decode(n)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),s=this.getCrypto(),r=await s.subtle.digest("SHA-256",t);return s.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const Ri="conversationMap",Ii="userInfoMap",vi="groupNamecardMap",Si="contactRelationMap",Ci="contactVersion",Ti="contactMeta",Ai="sessionListMap",Oi="sessionListCheckpoint",bi="joinedGroupPreview",_i="metadata",Mi=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Ni{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 Di=()=>{const t="undefined"!=typeof window?window.localStorage:void 0;if(t&&"function"==typeof t.getItem)return t;const s=e.getRuntimeGlobal().localStorage;return s&&"function"==typeof s.getItem?s:null};class wi{constructor(e,t){this.storage=t??wi.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!wi.checkAvailable())return null;const e=Di();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=Di();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(t,s){if(!this.storage)return s;try{const e=await this.storage.getItem(t);if(!e)return s;let r=e;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const t=await this.cryptoAdapter.decrypt(e);if(null===t)return s;r=t}return d.safeJsonParse(r,s)}catch(r){return e.logger.warn("CacheStore read failed",r),s}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(t,s,r){if(!this.storage)return;const n=d.safeJsonStringify(s);if(null!==n)try{const e=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(n):n;await this.storage.setItem(t,e)}catch(o){if(Ls(o))throw o;if(r)throw o;e.logger.warn("CacheStore write failed",o)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(t){if(this.storage)try{await this.storage.removeItem(t)}catch(s){e.logger.warn("CacheStore remove failed",s)}}}const Ui={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Li={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Pi{constructor(){this.items=new Map,this.versionState=Ui,this.meta=Li}load(e,t,s){this.items.clear();for(const r of e){const e=this.normalizeRecord(r);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 r=this.items.get(e);return!(!r||r.remark===t)&&(this.items.set(e,{...r,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])),r=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}}),n="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:r,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:n}}normalizeRecord(e){if(!d.isRecord(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 d.isRecord(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"}:Ui}normalizeMeta(e){return d.isRecord(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"}:Li}}const ki=(e,t,s)=>{if(t<=0)return{kept:e,removed:[]};const r=[],n=[];for(const o of e)s-o.lastUpdate>t?n.push(o):r.push(o);return{kept:r,removed:n}},xi=(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),r=new Set(s);return{kept:e.filter(e=>!r.has(e)),removed:s}},Fi=e=>{if(!Array.isArray(e))return[];const t=new Set,s=[],r=e;for(const n of r){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,r="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(r)||r<0||r>19)continue;const o=r;t.has(o)||(t.add(o),s.push(o))}return s};class Bi{constructor(){this.items=[]}load(e,t){const s=[];for(const r of e){const e=this.normalizeItem(r,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 r of e){const e=this.findIndex(r.conversationId,r.type);if(e<0)continue;const n=this.items[e];n&&(n.lastAccess!==t&&(this.items[e]={...n,lastAccess:t},s=!0))}return s}removeExpired(e,t){const s=ki(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=xi(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),r=t.slice(0,s),n=new Set(r);return this.items=this.items.filter(e=>!n.has(e)),r.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 r="single"===(n=s.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!r)return null;const o=this.normalizeMessage(s.lastMessage);return{conversationId:s.conversationId,type:r,lastMessage:o,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:Fi(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(!d.isRecord(e))return null;const t="string"==typeof e.msgId?e.msgId:"",s="string"==typeof e.type?e.type:"",r="number"==typeof e.timestamp?e.timestamp:0,n=d.isRecord(e.body)?e.body:{},o="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,i="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:s,body:n,timestamp:r,userInfoUpdateTime:o,namecardUpdateTime:i}:null}}const Gi=(e,t)=>`${e}:${t}`;class qi{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const s of e){const e=this.normalizeItem(s,t);e&&this.items.set(Gi(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,r){const n=Gi(e,t),o=this.items.get(n);return o?(r&&this.items.set(n,{...o,lastAccess:s}),o):null}getByGroupId(e,t,s){const r=[];for(const n of this.items.values())n.groupId===e&&(r.push(n),s&&this.items.set(Gi(n.groupId,n.userId),{...n,lastAccess:t}));return r}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const r=Gi(e.groupId,e.userId),n=this.items.get(r);this.items.set(r,{...e,lastAccess:n?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(Gi(t.groupId,t.userId))}removeExpired(e,t,s=new Set){const r=Array.from(this.items.values()),n=r.filter(e=>!s.has(e.userId)),o=ki(n,e,t),i=new Set(o.removed.map(e=>Gi(e.groupId,e.userId)));this.items.clear();for(const a of r)i.has(Gi(a.groupId,a.userId))||this.items.set(Gi(a.groupId,a.userId),a);return o.removed.length>0}evictByLru(e,t=new Set){const s=Array.from(this.items.values()),r=s.filter(e=>!t.has(e.userId)),n=xi(r,Math.min(e,r.length)),o=new Set(n.removed.map(e=>Gi(e.groupId,e.userId)));this.items.clear();for(const i of s)o.has(Gi(i.groupId,i.userId))||this.items.set(Gi(i.groupId,i.userId),i);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!d.isRecord(e))return null;const s="string"==typeof e.groupId?e.groupId:"",r="string"==typeof e.userId?e.userId:"";if(!s||!r)return null;return{groupId:s,userId:r,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 Ki=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Vi=e=>{const t={...e};return delete t.type,t},zi=e=>{if(!d.isRecord(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!d.isRecord(e.body))return null;const s=((e,t)=>{if(d.isRecord(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 r=Ki(e.conversationType),n=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),o=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),i=(e=>{if(d.isRecord(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:Vi(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...r?{conversationType:r}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...n?{sendStatus:n}:{},...o?{direct:o}:{},...i?{modifiedInfo:i}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Hi=e=>{if(!Array.isArray(e))return[];const t=new Set,s=[],r=e;for(const n of r){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,r="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(r)||r<0||r>19)continue;const o=r;t.has(o)||(t.add(o),s.push(o))}return s},Wi=(e,t)=>{const s="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,r="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(s!==r)return r-s;const n=e.lastMessageAt??e.updatedAt,o=t.lastMessageAt??t.updatedAt;return n!==o?o-n:e.conversationId.localeCompare(t.conversationId)};class ji{constructor(){this.items=[]}load(e,t){const s=[];for(const r of e){const e=this.normalizeItem(r,t);e&&s.push(e)}this.items=s.sort(Wi)}getAll(){return this.items}setAll(e){const t=Date.now(),s=[];for(const r of e){const e=this.normalizeItem(r,t);e&&s.push(e)}this.items=s.sort(Wi)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!d.isRecord(e))return null;const s=e,r="string"==typeof s.conversationId?s.conversationId:"";if(!r)return null;const n=Ki(s.conversationType);if(!n)return null;const o="string"==typeof s.conversationName&&s.conversationName.length>0?s.conversationName:r,i="string"==typeof s.conversationAvatar?s.conversationAvatar:void 0;return{conversationId:r,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:zi(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:Hi(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:o,conversationAvatar:i,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class Qi{constructor(){this.items=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 r=[];for(const n of e){const e=this.items.get(n);e&&(r.push(e),s&&this.items.set(n,{...e,lastAccess:t}))}return r}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const r=this.items.get(e.userId),n=r?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,s=new Set){const r=Array.from(this.items.values()),n=r.filter(e=>!s.has(e.userId)),o=ki(n,e,t),i=new Set(o.removed.map(e=>e.userId));this.items.clear();for(const a of r)i.has(a.userId)||this.items.set(a.userId,a);return o.removed.length>0}evictByLru(e,t=new Set){const s=Array.from(this.items.values()),r=s.filter(e=>!t.has(e.userId)),n=xi(r,Math.min(e,r.length)),o=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const i of s)o.has(i.userId)||this.items.set(i.userId,i);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const s=Array.from(this.items.values()),r=Math.max(s.length-e,0);return this.evictByLru(r,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!d.isRecord(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 $i=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Yi=e=>e.lastMessageAt??e.updatedAt,Ji=e=>[...e].sort((e,t)=>{const s=$i(t)-$i(e);if(0!==s)return s;const r=Yi(t)-Yi(e);return 0!==r?r:e.conversationId.localeCompare(t.conversationId)}),Xi=e=>`${e.conversationType}:${e.conversationId}`,Zi=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,ea=(e,t)=>((e,t)=>Yi(t)>Yi(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Zi(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,ta=e=>{const t=new Map,s=new Set;for(const o of e.snapshot)s.add(Xi(o));for(const o of e.existing)t.set(Xi(o),o);const r=e.snapshot.map(e=>{const s=t.get(Xi(e));return s?ea(e,s):e}),n=e.existing.filter(t=>!s.has(Xi(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Ji([...r,...n])},sa=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],ra=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),na=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 oa{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,s=Date.now()){const r=this.records.get(e)??null;if(!r||!t)return r;const n={...r,lastAccess:s};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const s of e){const e=s.lastModified??t,r=this.records.get(s.profile.userId),n=r?.lastAccess??t;this.records.set(s.profile.userId,{profile:s.profile,lastModified:e,lastAccess:n,source:s.source})}}applyPatch(e,t,s=Date.now()){const r=this.records.get(e.userId),n={userId:e.userId,...t??{},...r?.profile??{}};if(r&&e.lastModified<r.lastModified)return{applied:!1,reason:"stale",record:r};const o={...n,...e.attributes,userId:e.userId};if(r&&e.lastModified===r.lastModified&&(i=r.profile,a=o,sa.every(e=>i[e]===a[e])))return{applied:!1,reason:"duplicate",record:r};var i,a;const c={profile:o,lastModified:e.lastModified,lastAccess:r?.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 ia=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class aa{constructor(e){this.conversationDeletionTimestamps=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=new Map,this.pendingDirtyRevisions=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 Ei(e.appKey,e.userId);this.store=new wi(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Mi(s,Ri),this.userInfoKey=Mi(s,Ii),this.groupNamecardKey=Mi(s,vi),this.sessionListKey=Mi(s,Ai),this.sessionListCheckpointKey=Mi(s,Oi),this.joinedGroupPreviewKey=Mi(s,bi),this.contactRelationKey=Mi(s,Si),this.contactVersionKey=Mi(s,Ci),this.contactMetaKey=Mi(s,Ti),this.metadataKey=Mi(s,_i),this.metadataStore=new Ni(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Bi,this.userInfoCache=new Qi,this.groupNamecardCache=new qi,this.sessionListCache=new ji,this.joinedGroupPreviewCache=new i.JoinedGroupPreviewCache,this.contactCache=new Pi,this.userInfoRuntimeStore=new oa,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 i.JoinedGroupPreviewCache;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 r=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==r&&r<=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,r=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(s=!0,0===n.unreadCount?n:(r=!0,{...n,unreadCount:0,lastUpdate:t})));let o=!1;const i=this.sessionListCache.getAll().map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:(s=!0,0===r.unreadCount&&r.readAt===t?r:(o=!0,{...r,unreadCount:0,readAt:t,updatedAt:t})));return r||o?(r&&this.conversationCache.setAll(n),o&&this.sessionListCache.setAll(i),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(),r=s.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),o=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),i=!this.isConversationListEqual(s,r),a=!this.isSessionListEqual(n,o);return i||a?(i&&this.conversationCache.setAll(r),a&&this.sessionListCache.setAll(o),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(),r=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}),n=this.sessionListCache.getAll(),o=n.map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:{...s,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),i=!this.isConversationListEqual(s,r),a=!this.isSessionListEqual(n,o);return i||a?(i&&this.conversationCache.setAll(r),a&&this.sessionListCache.setAll(o),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 r=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=s.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),o=r.length!==t.length,i=n.length!==s.length;return o||i?(o&&this.conversationCache.setAll(r),i&&this.sessionListCache.setAll(n),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(),r=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),o=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const o=r(e.marks);return this.areConversationMarksEqual(o,e.marks)?e:{...e,marks:o,lastUpdate:s}}),i=this.sessionListCache.getAll(),a=i.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const o=r(e.marks);return this.areConversationMarksEqual(o,e.marks)?e:{...e,marks:o,updatedAt:s}}),c=!this.isConversationListEqual(n,o),d=!this.isSessionListEqual(i,a);return c||d?(c&&this.conversationCache.setAll(o),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 r=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??r})),o=ta({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:s?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(o,r)),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 r=!1;for(;!r;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),s=this.getDomainRevision("sessionList"),s===n&&(r=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=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?ra(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([na(t)])}getUserInfoSummaries(e,t){const s=Date.now(),r=this.userInfoCache.getByIds(e,s,t);return t&&this.scheduleFlush(["userInfo"]),r}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,s){const r=this.groupNamecardCache.get(e,t,Date.now(),s);return s&&r&&this.scheduleFlush(["groupNamecard"]),r}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 r=this.loadContactSnapshot("sync");return{snapshot:r,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(r)}}refreshSessionListDisplayFromUserInfos(e){const t=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(),r=this.loadContactSnapshot("cache").items,n=new Map(r.map(e=>[e.userId,e])),o=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),i=this.sessionListCache.getAll().map(e=>{let r=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,o)){const t=n.get(e.conversationId),i=this.resolveSessionDisplayUserInfo(e.conversationId,o),a=this.buildSingleSessionDisplayFields(e.conversationId,t,i,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(r={...r,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:s})}const i=r.lastMessage;if(i&&!this.shouldSkipSessionUserDisplayRefresh(i.sender.userId,t,o)){const e=n.get(i.sender.userId),t=this.resolveSessionDisplayUserInfo(i.sender.userId,o),a=this.buildSessionMessageSender(i.sender.userId,i.sender,e,t);this.isSenderEqual(i.sender,a)||(r={...r,lastMessage:{...i,sender:a},updatedAt:s})}return r}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,i);return c&&(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const s=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 r=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=s.get(e.conversationId);if(!n)return e;const o=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&o)return e;const i=n.name?.trim(),a=i||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.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:r}:e}),o=this.sessionListCache.getAll(),i=!this.isSessionListEqual(o,n);return i&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:i}}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(),r="add"===e.action?this.contactCache.addByNotice(e.userId,s):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,s);(r||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const o=this.loadContactSnapshot("cache");return{snapshot:o,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(o)}}updateConversationsFromServer(e,t){const s=Date.now(),r=this.conversationCache.getAll(),n=this.mergeConversationLists(r,e,s,t?.syncStartedAt),o=!this.isConversationListEqual(r,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:o}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const s=Date.now(),r=this.conversationCache.getAll(),n=r.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),o=n>=0?r[n]:void 0,i=this.buildConversationFromMessage(e,o,s);if(!i)return{items:r,changed:!1};const a=[i,...r.filter((e,t)=>t!==n)];return this.isConversationListEqual(r,a)?{items:r,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(),r=s.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const o=(e=>{const t=Xi(e.nextRecord),s=e.existing.filter(e=>Xi(e)!==t);return Ji([e.nextRecord,...s])})({existing:s,nextRecord:this.buildSessionListRecordFromConversation(n,e,r,Date.now())});return this.isSessionListEqual(s,o)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(o),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 r=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(r,e);const n=await this.readValue(this.sessionListKey,null),o=n&&d.isRecord(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(o,e);const i=(n&&d.isRecord(n)&&d.isRecord(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(i);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),l=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,l,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&d.isRecord(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&d.isRecord(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=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(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(t){try{const n=6;for(let o=0;o<=n;o+=1)try{return await this.writeDirtyDomains(t),void(await this.metadataStore.touchLastFlush())}catch(s){if(!Ls(s))return this.restoreDirtyBatch(t),void e.logger.warn("Cache flush failed",s);const n=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(t,n),"none"===n)return void e.logger.warn("Cache flush failed: no cache entry can be evicted",s);try{await this.writeDomain(n)}catch(r){if(!Ls(r))return this.restoreDirtyBatch(t),void e.logger.warn("Cache quota cleanup persistence failed",r)}}e.logger.warn("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of ia)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 r={items:e,checkpoint:t};s?await this.store.writeStrictAsync(this.sessionListKey,r):await this.store.writeAsync(this.sessionListKey,r),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),s=new Map;for(const n of t)s.set(`${n.conversationType}:${n.conversationId}`,n);const r=Date.now();return(e=>{const t=e.incoming.filter(e=>$i(e)>0),s=new Map;for(const n of e.incoming)s.set(Xi(n),n);const r=t.length>0?e.existing.filter(e=>!s.has(Xi(e))&&0===$i(e)):e.existing.filter(e=>!s.has(Xi(e)));return Ji([...r,...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??r}})})}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(ta({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,r){const n=e.find(e=>e.conversationId===s&&e.type===r),o=t.find(e=>e.conversationId===s&&e.conversationType===r);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,o?.updatedAt??0,o?.lastMessageAt??0,o?.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 r=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),r}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,r){const n=new Map,o=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),o.set(e,d)}const i=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??s;i.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 r&&e.lastUpdate>r)});return[...i,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],n=t[s];if(!r||!n)return!1;if(this.buildConversationSignature(r)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,s=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",r=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,o=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${r}:${n}:${o}:${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 r=this.resolveConversationFromMessage(e);if(!r)return null;const n=e.msgServerId||e.msgLocalId,o=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,i="SEND"===e.direct?s:t?.lastAccess??s;return{conversationId:r.conversationId,type:r.type,lastMessage:this.buildMessageSnippet(e),unreadCount:o,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:i,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=on(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,r=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),o=n.get(e.conversationId),i=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],r,!1)[0],c=i??(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,n.get(h),p),g="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,f="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,o,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:g,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:f.conversationName,conversationAvatar:f.conversationAvatar,updatedAt:r}}resolveSessionListUnreadCount(e,t,s){const r=s?.unreadCount,n=t.msgServerId||t.msgLocalId;return s?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof r?Math.max(e.unreadCount,r+1):e.unreadCount:"number"==typeof r?Math.max(e.unreadCount,r):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,r,n){const o=t?.remark?.trim(),i=t?.userInfo.avatarUrl??s?.avatarUrl??n;if(o)return{conversationName:o,conversationAvatar:i};const a=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return a?{conversationName:a,conversationAvatar:i}:r?{conversationName:r,conversationAvatar:i}:{conversationName:e,conversationAvatar:i}}shouldSkipSessionUserDisplayRefresh(e,t,s){if(!t.has(e))return!0;const r=t.get(e),n=s.get(e);return"number"==typeof r&&"number"==typeof n?.lastUpdate&&n.lastUpdate>r}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const s=this.loadContactSnapshot("cache").items,r=new Map(s.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const s=e.lastMessage;if(!s)return e;const o=s.sender.userId,i=r.get(o),a=this.resolveSessionDisplayUserInfo(o,n),c="singleChat"===e.conversationType&&o===e.conversationId?this.buildSingleChatPeerMessageSender(o,s.sender,i,a):this.buildSessionMessageSender(o,s.sender,i,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 r=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return r?ra(r):null}buildSessionMessageSender(e,t,s,r){const n=s?.remark?.trim();return{userId:e,nickname:n||s?.userInfo.nickname?.trim()||r?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:s?.userInfo.avatarUrl??r?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,s,r){const n=this.buildSessionMessageSender(e,void 0,s,r);return{userId:e,nickname:t?.nickname?.trim()||n.nickname,avatarUrl:t?.avatarUrl||n.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 r=e[s],n=t[s];if(!r||!n)return!1;if(this.buildSessionListSignature(r)!==this.buildSessionListSignature(n))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",r=`${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,r,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 ca{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const s=[],r=[];for(const o of this.handlers.entries()){const[e]=o;e.startsWith("__internal")?s.push(o):r.push(o)}const n=this.dispatchToHandlers(e,t,s);n?n.then(()=>{this.dispatchToHandlers(e,t,r)}):this.dispatchToHandlers(e,t,r)}dispatchToHandlers(e,t,s){let r=null;for(const[,n]of s){const s=n[e];s&&(r=r?r.then(async()=>{await this.invokeHandler(e,t,s)}):this.invokeHandler(e,t,s))}return r}invokeHandler(t,s,r){try{const n=r(s);return this.isPromiseLike(n)?Promise.resolve(n).then(()=>{}).catch(s=>{e.logger.error(`Event handler error for ${t}`,s)}):null}catch(n){return e.logger.error(`Event handler error for ${t}`,n),null}}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const da={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function la(e,t){const s=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),r=Math.min(s,t.maxDelay);if(t.jitter){const e=.2*r,t=(2*Math.random()-1)*e;return Math.max(0,r+t)}return r}function ua(e){return new Promise(t=>setTimeout(t,e))}const ha=e=>{const t={...e};return delete t.type,t},pa=(e,t)=>{const s=e.lastMessage;if(!s)return null;const r=((e,t)=>{const s=t.getCurrentUserId?.()??"",r="singleChat"===e.type?e.conversationId:"";return{from:r,to:"singleChat"===e.type?s:e.conversationId,sender:{userId:r}}})(e,t);return{msgServerId:s.msgId,from:r.from,to:r.to,sender:r.sender,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof s.type&&s.type.length>0?s.type:"text",timestamp:s.timestamp,body:ha(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},ma=async(e,t)=>{const s=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!s)return new Map;const r=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===r.length)return new Map;const n=[];for(let a=0;a<r.length;a+=50)n.push(r.slice(a,a+50));const o=new Map;let i=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;i<n.length;){const e=i;i+=1;const t=n[e];if(t)try{const e=await s.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&o.set(t.groupId,t)}catch{}}})())),o},ga=async(e,t)=>{const s=await ma(e,t);return e.map(e=>((e,t,s)=>{const r=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),n=((e,t)=>{const s=e.getCacheManager();if(!s)return null;const r=s.getRuntimeUserInfo(t,!1);if(r)return r;const n=s.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),o="singleChat"===e.type?((e,t,s)=>{const r=t?.remark?.trim();if(r)return{conversationName:r,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl};const n=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}})(e.conversationId,r,n):"groupChat"===e.type?(i=e.conversationId,a=s.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:i}):(e=>({conversationName:e}))(e.conversationId);var i,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:pa(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:o.conversationName,conversationAvatar:o.conversationAvatar}})(e,t,s))};class fa{constructor(e=`session-list-${t.generateMsgLocalId()}`){this.status="idle",this.seenBatchKeys=new Set,this.itemsByConversation=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 e.SDKError("Session-list sync session cannot re-enter syncing state after completion",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(t){if(t.requestId!==this.requestId)throw new e.SDKError("Session-list sync requestId mismatch",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:t.requestId}});if(this.isTerminal())throw new e.SDKError("Session-list sync batch received after terminal state",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{requestId:t.requestId,status:this.status}});const s=(r=t.requestId,n=t.batchSequence,`${r}:${n}`);var r,n;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 ya=0,Ea=5,Ra=10,Ia=11,va=1,Sa=2,Ca=1,Ta=2,Aa=3,Oa=e=>e===va?"groupChat":e===Sa?"chatRoom":"singleChat",ba=()=>br().lookupType("easemob.pb.MessageBody"),_a=e=>{const t=ba().toObject(ba().decode(e),{longs:Number,bytes:Uint8Array}),s=Array.isArray(t.contents)?t.contents:[],r=(n=s[0])&&"object"==typeof n&&!Array.isArray(n)?n:{};var n;const o="number"==typeof r.type?r.type:Y,i="string"==typeof r.remotePath&&r.remotePath.length>0||"string"==typeof r.title&&r.title.length>0||"string"==typeof r.summary&&r.summary.length>0||"number"==typeof r.combineLevel&&r.combineLevel>0,a=Object.prototype.hasOwnProperty.call(r,"subType")&&0===r.subType;return o===ne||o===Y&&(a||i)?{type:"combine",title:"string"==typeof r.title?r.title:"",summary:"string"==typeof r.summary?r.summary:"",filename:"string"==typeof r.displayName?r.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof r.remotePath?r.remotePath:void 0,secret:"string"==typeof r.secretKey?r.secretKey:void 0,fileLength:"number"==typeof r.fileLength?r.fileLength:void 0,combineLevel:"number"==typeof r.combineLevel?r.combineLevel:0}:o===Y?{type:"text",content:"string"==typeof r.text?r.text:""}:1===o?{type:"image",filename:"string"==typeof r.displayName?r.displayName:"image",remotePath:"string"==typeof r.remotePath?r.remotePath:""}:2===o?{type:"video",filename:"string"==typeof r.displayName?r.displayName:"video",remotePath:"string"==typeof r.remotePath?r.remotePath:""}:3===o?{type:"location",latitude:"number"==typeof r.latitude?r.latitude:0,longitude:"number"==typeof r.longitude?r.longitude:0,address:"string"==typeof r.address?r.address:void 0}:4===o?{type:"voice",filename:"string"==typeof r.displayName?r.displayName:"voice",remotePath:"string"==typeof r.remotePath?r.remotePath:"",duration:"number"==typeof r.duration?r.duration:0}:5===o?{type:"file",filename:"string"==typeof r.displayName?r.displayName:"file",remotePath:"string"==typeof r.remotePath?r.remotePath:""}:6===o?{type:"cmd",action:"string"==typeof r.action?r.action:""}:7===o?{type:"custom",event:"string"==typeof r.customEvent?r.customEvent:""}:{}},Ma=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),r="string"==typeof s?.nickname?s.nickname:void 0,n="string"==typeof s?.remark?s.remark:void 0,o="string"==typeof s?.avatarurl?s.avatarurl:"string"==typeof s?.avatarUrl?s.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:o}:r?{conversationName:r,conversationAvatar:o}:{conversationName:t,conversationAvatar:o}},Na=e=>{const t={...e};return delete t.type,t},Da=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,wa=(e,t,s)=>{if(!e)return null;const r=(e=>{if(!e)return"";const t=e.lastIndexOf("_");return t>=0?e.slice(t+1):e})(e.from?.name),n={userId:r};return"singleChat"===s.conversationType&&r===s.conversationId&&s.singleChatPeerDisplay&&(s.singleChatPeerDisplay.conversationName!==r&&(n.nickname=s.singleChatPeerDisplay.conversationName),s.singleChatPeerDisplay.conversationAvatar&&(n.avatarUrl=s.singleChatPeerDisplay.conversationAvatar)),{msgServerId:e.id??"",from:r,to:Da({conversationId:s.conversationId,conversationType:s.conversationType,from:r,currentUserId:s.currentUserId}),sender:n,conversationId:s.conversationId,conversationType:s.conversationType,type:(o=t.type,"text"===o||"image"===o||"file"===o||"voice"===o||"video"===o||"location"===o||"custom"===o||"cmd"===o||"combine"===o?o:"text"),timestamp:e.timestamp??0,body:Na(t)};var o},Ua=e=>{if(!Array.isArray(e))return[];const t=new Set,s=[],r=e;for(const n of r){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,r="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(r)||r<0||r>19)continue;const o=r;t.has(o)||(t.add(o),s.push(o))}return s},La=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return _a(e)}catch{return{}}})(e.last_message?.payload),r=e.session_id??"",n=Oa(e.session_type),o=(e=>{const t=e.session_id??"",s=Oa(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Ma(e)})(e);return{conversationId:r,conversationType:n,unreadCount:e.unread_count??0,lastMessage:wa(e.last_message,s,{conversationId:r,conversationType:n,currentUserId:t,singleChatPeerDisplay:"singleChat"===n?o:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:Ua(e.marks),readAt:e.read_receipt,remindType:(i=e.remind_type,i===Ca?"ALL":i===Ta?"AT":i===Aa?"NONE":"DEFAULT"),conversationName:o.conversationName,conversationAvatar:o.conversationAvatar};var i}),Pa={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 ka=null,xa=!1;const Fa=()=>ka||(xa||(n.lightExports.util.Long=r.Long,n.lightExports.configure(),xa=!0),r.installReflectionRuntime(),ka=n.lightExports.Root.fromJSON(Pa),r.installReflectionCodecInNamespace(ka),ka),Ba=e=>Fa().lookupType(e),Ga=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}},qa=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Ga(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Ga(t.protocol_version)??Ga(t.protocolVersion)??0}},Ka=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}},Va=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Ga(t.id)?String(Ga(t.id)):void 0,from:Ka(t.from),timestamp:Ga(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 za{constructor(){this.requestType=Ba("easemob.sessionlist.GetSessionListRequest"),this.responseType=Ba("easemob.sessionlist.GetSessionListResponse"),this.errorType=Ba("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 r=this.tryDecodeRequest(e);return r||{type:ya}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=Ga(t.type);return s!==Ra?null:{type:s,header:qa(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Ga(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=Ga(t.type);return s!==Ia?null:{type:s,header:qa(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:Ga(t.session_type),last_message:Va(t.last_message),updated_at:Ga(t.updated_at),pinned_time:Ga(t.pinned_time),unread_count:Ga(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Ga(t.read_receipt),remind_type:Ga(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:Ga(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=Ga(t.type);return s!==Ea?null:{type:s,header:qa(t.header),code:Ga(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Ha=async t=>{const s=t.client.getCacheManager(),r=t.client.getRestContext(),n=t.client.getSessionListSyncWsUrls();if(!s||0===n.length)throw new e.ConnectionError("session-list sync websocket is unavailable",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[o,i]=r.appKey.split("#");if(!o||!i)throw new e.ValidationError("session-list appKey is invalid",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{appKey:r.appKey}});const a=s.loadSessionListCheckpoint(),c=(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:i,username:r.userId,lastSyncTime:(d=a.sessionsLastSyncTs,Math.max(0,d-e.SESSION_LIST_SYNC_OVERLAP_MS)),params:t.params});var d;const l=new za;let u=0,h=a.sessionsLastSyncTs;return await t.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:t.session.getRequestId(),encode:()=>l.encodeRequest(c),decode:e=>{const t=l.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===(n=s).code?new e.AuthenticationError(n.message,{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:n.code}}):1003===n.code?new e.SDKError(n.message,e.ERROR_CODES.SERVER_BUSY,{details:{protocol:"session-list",responseCode:n.code}}):1501===n.code||1001===n.code?new e.ValidationError(n.message,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:n.code}}):1503===n.code?new e.SDKError(n.message,e.ERROR_CODES.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:n.code}}):(n.code,new e.SDKError(n.message,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:n.code}}));var n;if(11!==s.type)throw new e.SDKError("session-list response type is invalid",e.ERROR_CODES.MESSAGE_DECODE_FAILED,{details:{responseType:s.type}});const o=s,i=o.header?.requestId;if(i&&i!==t.session.getRequestId())return;u+=1,e.logger.debug("Decoded session-list sync raw response",{requestId:t.session.getRequestId(),batchSequence:u,response:o});const a=La(o,r.userId),c=t.session.pushBatch({requestId:t.session.getRequestId(),batchSequence:u,sessions:a,isLastBatch:!0===o.isLastBatch,lastSyncFinishedTs:o.lastSyncFinishedTs});if("number"==typeof o.lastSyncFinishedTs&&(h=o.lastSyncFinishedTs),!c.done)return;return{done:!0,result:{items:t.session.getItems(),lastSyncFinishedTs:h}}}})},Wa=()=>Date.now(),ja={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Qa=(e,t)=>({status:e,determinedAt:Wa(),reason:t}),$a=t=>t instanceof e.SDKError&&(t.code===e.ERROR_CODES.SERVER_BUSY||1103===t.code),Ya=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:$a(e)});class Ja{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 fa,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 r=this.client.getCacheManager();if(!r)return[];this.client.emitSyncDataStart("conversation");const n=await this.tryDirectFallback(r);if(n)return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),n;try{const n=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let i=0;const a=await async function(e,t,s={}){const r={...da,...s};let n;for(let i=1;i<=r.maxAttempts;i++)try{return await e()}catch(o){if(n=o,!t(o))throw o;if(i>=r.maxAttempts)throw o;const e=la(i,r);await ua(e)}throw n}(async()=>{i+=1;const e=1===i?t:this.createRetrySession();e.start();try{return await Ha({client:this.client,session:e,params:s})}catch(r){throw e.fail(),r}},$a,ja),d={result:a,syncStartedAt:t.getStartedAt()},l=d.result.items;this.capabilityState={status:"available",determinedAt:Wa()};const u={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Wa()};try{await r.commitSessionListSync({items:l,mode:n,checkpoint:u,syncStartedAt:d.syncStartedAt})}catch(o){t.fail();const s=new e.StorageError("Session-list final persistence failed",{details:{cause:o instanceof Error?o.message:String(o)}});return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Ya(s)}),r.loadSessionList()}const h=r.loadSessionList();return r.updateConversationsFromServer(h.map(c.toConversationSummary),{syncStartedAt:d.syncStartedAt}),await r.flushPending(),this.client.emitConversationListUpdate("conversation","full"===n),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),h}catch(o){const s=o instanceof e.SDKError?o:new e.SDKError(o instanceof Error?o.message:String(o));t.fail();const n=(t=>t.code===e.ERROR_CODES.OPERATION_UNSUPPORTED||t.code===e.ERROR_CODES.AUTH_UNAUTHORIZED?{capabilityState:Qa("unsupported",t.message),shouldUseFallback:!0}:t.code===e.ERROR_CODES.AUTH_TOKEN_EXPIRED||t.code===e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:t.code===e.ERROR_CODES.SERVER_BUSY||1103===t.code?{shouldUseFallback:!0,shouldRetry:!0}:t.code===e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(s);n.capabilityState&&(this.capabilityState=n.capabilityState),n.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const i=await this.buildFallbackSessionList(r);return n.shouldUseFallback&&r.replaceSessionList(i),this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Ya(s)}),i}}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),r=this.client.isSessionListDnsProbeAvailable();if(!s&&!r){this.capabilityState=Qa("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new fa}async buildFallbackSessionList(e){return await(async(e,t)=>await ga(e,t))(e.loadConversationSummaries(),this.client)}}const Xa=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Za=async t=>{if("string"==typeof t||Xa(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Xa(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 e.SDKError("sync websocket frame payload type is invalid",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof t}})},ec=t=>{const s=Math.max(t-1,0),r=e.SYNC_WEBSOCKET_RETRY_INITIAL_DELAY*Math.pow(e.SYNC_WEBSOCKET_RETRY_BACKOFF_MULTIPLIER,s);return Math.min(r,e.SYNC_WEBSOCKET_RETRY_MAX_DELAY)},tc=async e=>{await new Promise(t=>{setTimeout(t,e)})},sc=e=>e instanceof Error?e:new Error(String(e));class rc{constructor(e){this.pending=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 e.SDKError("sync websocket session is cancelled",e.ERROR_CODES.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:t.requestId}});if(this.pending.has(t.requestId))throw new e.SDKError("sync websocket requestId is duplicated",e.ERROR_CODES.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(r){this.rejectPending(t.requestId,sc(r))}return await s}cancel(t="sync-websocket-cancelled"){this.cancelled=!0;const s=new e.SDKError("sync websocket cancelled",e.ERROR_CODES.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!==s.SOCKET_READY_STATE.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&&e.logger.warn("sync websocket retry started",this.buildLogContext({reason:t?.message}));try{return void(await this.openSocket())}catch(s){if(t=sc(s),this.cancelled||0===this.pending.size)throw t;if(this.attempt>=3)throw e.logger.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),t;const r=ec(this.attempt);e.logger.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:t.message})),await tc(r)}}throw new e.ConnectionError("sync websocket retry exhausted",{code:e.ERROR_CODES.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 e.ConnectionError("sync websocket urls are unavailable",{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const s=t[this.urlIndex%t.length];if(this.urlIndex+=1,!s)throw new e.ConnectionError("sync websocket url is invalid",{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=s,this.state="connecting",e.logger.warn("sync websocket connect started",this.buildLogContext());const r=e.getRuntimeGlobal(),n=this.socketAdapter??ss({webSocketCtor:r.WebSocket});if(!n)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let o=null;try{const t=await Promise.race([n.connect({url:s}),new Promise((t,s)=>{o=setTimeout(()=>{s(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},e.SYNC_WEBSOCKET_CONNECT_TIMEOUT)})]);o&&clearTimeout(o),this.socket=t,t.onMessage(e=>{this.socket===t&&this.handleMessage(e)}),t.onError(()=>{this.socket===t&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),t.onClose(e=>{if(this.socket===t)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:e.code,closeReason:e.reason}))}),this.state="open",this.resetIdleTimer(),e.logger.warn("sync websocket connected",this.buildLogContext())}catch(i){if(o&&clearTimeout(o),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),i instanceof e.ConnectionError)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 Za(e);if(!(await this.routeFrame(t)))return}catch(t){const e=sc(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(t){const s=[];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(n){this.pending.delete(e.requestId),e.reject(sc(n)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||r||(r={pending:e,frame:s.frame})}catch(n){s.push(sc(n))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&s.length===this.pending.size)throw new e.SDKError("sync websocket frame decode failed",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:s[0]?.message}});return e.logger.warn("sync websocket frame ignored",this.buildLogContext({reason:s[0]?.message??"requestId not matched"})),!1}handleSocketFailure(t){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(e.logger.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),void this.rejectAll(t)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(sc(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(t){if(t&&this.socket&&this.socket.readyState===s.SOCKET_READY_STATE.OPEN)try{this.socket.send(t.encode()).catch(e=>{this.rejectPending(t.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:e instanceof Error?e.message:String(e)}))}),e.logger.warn("sync websocket request sent",this.buildLogContext({requestId:t.requestId,dataTypes:[t.dataType]})),this.resetIdleTimer()}catch(r){this.rejectPending(t.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:r instanceof Error?r.message:String(r)}))}}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||(e.logger.warn("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},e.SYNC_WEBSOCKET_COMPLETE_CLOSE_DELAY))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},e.SYNC_WEBSOCKET_IDLE_TIMEOUT))}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 r=this.socket;this.socket=null,!r||r.readyState>=s.SOCKET_READY_STATE.CLOSING||(this.state="closing",r.close(e,t))}buildConnectionError(t,s,r={}){return new e.ConnectionError(t,{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:s,url:this.activeUrl,...r}})}buildLogContext(t={}){return{attempt:this.attempt,maxAttempts:3,url:e.sanitizeErrorUrl(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...t}}}const nc=async(t,s,r)=>{const{orgName:n,appName:o}=e.parseAppKey(t.appKey),i=`/${n}/${o}/user/${encodeURIComponent(t.userId)}/roster/metadata/version`,a=new e.RestClient(t.restBaseUrl,{requestAdapter:r,includeRequestId:!0});a.setAuthToken(t.token);try{return((t,s)=>{const r=Date.now(),n=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:r}};if(d.isRecord(t))return d.isRecord(t.data)?n(t.data):n(t);throw new e.ValidationError("Invalid contact metadata response",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{payload:t}})})(await a.get(i),s)}catch(c){if(c instanceof e.ValidationError)throw c;const t=c instanceof e.SDKError&&c.details?c.details:{};throw new e.RestTransportError("Contact metadata request failed",{code:e.ERROR_CODES.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 e.SDKError?c.code:void 0}})}},oc=e=>l.z.string().regex(/^https?:\/\/\S+$/i,e),ic=e=>l.z.string().regex(/^wss?:\/\/\S+$/i,e),ac=l.z.object({appKey:l.z.string().min(1,"appKey is required").optional(),appId:l.z.string().min(1,"appId is required").optional(),enableUserInfoSync:l.z.boolean().optional(),enableSyncData:l.z.array(l.z.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:l.z.boolean().optional(),deleteConversationOnGroupDestroyed:l.z.boolean().optional(),syncConversationListConfig:l.z.object({includeEmpty:l.z.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:l.z.boolean().optional(),useFixedDeviceId:l.z.boolean().optional(),deviceId:l.z.string().min(1,"deviceId is required").optional(),serviceConfig:l.z.object({dnsConfigUrls:l.z.array(oc("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:l.z.object({restApiUrl:oc("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:ic("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:oc("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:ic("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:l.z.boolean().optional(),customDeviceName:l.z.string().min(1,"customDeviceName is required").optional(),customOSPlatform:l.z.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:l.z.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:l.z.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:l.z.array(l.z.unknown()).optional(),platformAdapterOptions:l.z.object({prefer:l.z.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:l.z.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:l.z.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:l.z.ZodIssueCode.custom,path:["appKey"],message:"appKey or appId is required"}):s>1&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const r=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=r?.serverUrls&&"object"==typeof r.serverUrls?r.serverUrls:void 0;r?.dnsConfigUrls&&n&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),cc=l.z.object({userId:l.z.string().min(1,"userId is required"),token:l.z.string().min(1,"token is required")}),dc=l.z.string().trim().min(1,"token is required"),lc=l.z.object({channelName:l.z.string().trim().min(1,"channelName is required").optional()}).optional(),uc=l.z.array(l.z.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))),hc=l.z.object({protocol:l.z.string(),domain:l.z.string().optional(),ip:l.z.string().optional(),port:l.z.union([l.z.string(),l.z.number()]).optional()}).passthrough(),pc=l.z.object({app_key:l.z.string().optional(),rest:l.z.object({hosts:l.z.array(hc).nonempty()}),"msync-wx":l.z.object({hosts:l.z.array(hc).nonempty()}),"sync-ws":l.z.object({hosts:l.z.array(hc).nonempty()}).optional(),enableReportLogs:l.z.enum(["true","false"]).optional(),reportInterval:l.z.number().positive().finite().optional(),enableDataReport:l.z.enum(["true","false"]).optional(),enableMd5Check:l.z.enum(["true","false"]).optional(),uploadinparts_enable:l.z.enum(["true","false"]).optional()}).passthrough(),mc="5.1.0",gc=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],fc=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],yc=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function Ec(e){return"object"==typeof e&&null!==e}function Rc(e){return Array.isArray(e)?{hosts:e}:function(e){return Ec(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Ic(e,t,s){for(const r of t){const t=Rc(e[r]);if(t)return{key:r,section:t}}for(const[r,n]of Object.entries(e)){if(!s(r))continue;const e=Rc(n);if(e)return{key:r,section:e}}}function vc(s){if(!Ec(s))return t.Validator.validateOrThrow(pc,s);const r=Rc(s.rest),n=Ic(s,fc,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),o=Ic(s,yc,e=>{const t=e.toLowerCase();return!t.includes("msync")&&t.includes("sync")&&(t.includes("ws")||t.includes("socket"))}),i={...s,rest:r??s.rest,"msync-wx":n?.section};o?.section?i["sync-ws"]=o.section:"sync-ws"in i&&!Rc(i["sync-ws"])&&delete i["sync-ws"];const a="true"===(c=s.enableReportLogs)||!0===c?"true":"false"===c||!1===c?"false":void 0;var c;a&&(i.enableReportLogs=a);const d=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}(s.reportInterval);void 0!==d?i.reportInterval=d:delete i.reportInterval;const l=function(e){if("true"===e||"false"===e)return e}(s.enableDataReport);l?i.enableDataReport=l:delete i.enableDataReport;const u=function(e){if("true"===e||"false"===e)return e}(s.enableMd5Check);u?i.enableMd5Check=u:delete i.enableMd5Check;const h=function(e){if("true"===e||"false"===e)return e}(s.uploadinparts_enable);return h?i.uploadinparts_enable=h:delete i.uploadinparts_enable,n&&"msync-wx"!==n.key&&e.logger.warn("DNS config websocket section normalized",{sourceKey:n.key}),o&&"sync-ws"!==o.key&&e.logger.warn("DNS config sync websocket section normalized",{sourceKey:o.key}),t.Validator.validateOrThrow(pc,i)}function Sc(t,s){const r=t.domain||t.ip;if(!r)throw new e.ValidationError("DNS host missing domain/ip",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const n=void 0!==t.port?String(t.port):"";return`${"https"===s?"wss":"ws"}://${n&&"80"!==n&&"443"!==n?`${r}:${n}`:r}/websocket`}function Cc(e,t){return"https"===e?"https":"http"===e?"http":t}function Tc(t,s){const r=t.domain||t.ip;if(!r)throw new e.ValidationError("DNS rest host missing domain/ip",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const n=void 0!==t.port?String(t.port):"";return`${s}://${n&&"80"!==n&&"443"!==n?`${r}:${n}`:r}`}function Ac(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function Oc(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 bc(t,s,r){const n=new e.RestClient(t,{requestAdapter:r,includeRequestId:!0});let o="/easemob/server.json",i=!0;try{const e=new URL(t),s=""!==e.pathname&&"/"!==e.pathname,r=""!==e.search;(s||r)&&(o="",i=!1)}catch{o="/easemob/server.json",i=!0}if(i){o=`${o}?${(void 0!==s.appId?u.createQueryParams({app_id:s.appId,sdk_version:mc,file_version:"1"}):u.createQueryParams({app_key:s.appKey,_v:String(Date.now())})).toString()}`}return vc(await n.get(o))}function _c(t,s){const r=t["sync-ws"];return r&&Array.isArray(r.hosts)?r.hosts.map(t=>function(t,s){const r=t.domain||t.ip;if(!r)throw new e.ValidationError("DNS host missing domain/ip",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const n=void 0!==t.port?String(t.port):"";return`${"https"===s?"wss":"ws"}://${n&&"80"!==n&&"443"!==n?`${r}:${n}`:r}`}(t,Cc(t.protocol,s))).filter(e=>"string"==typeof e&&e.length>0):[]}async function Mc(t){const s=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:gc;if(0===s.length)throw new e.ValidationError("DNS_CONFIG list is empty",{code:e.ERROR_CODES.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 n;for(const a of s)try{const s=void 0!==t.appId?{appId:t.appId}:{appKey:t.appKey},n=await bc(a,s,t.requestAdapter),o=void 0!==t.appId?n.app_key:t.appKey;if("string"!=typeof o||0===o.length)throw new e.ValidationError("DNS app_key is required for appId initialization",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const i=Oc(Ac(n["msync-wx"].hosts,r));if(0===i.length)throw new e.ValidationError("DNS msync-wx hosts resolution failed",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const c=i[0];if(!c)throw new e.ValidationError("DNS msync-wx hosts resolution failed",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const d=Ac(n.rest.hosts,r);if(0===d.length)throw new e.ValidationError("DNS rest hosts resolution failed",{code:e.ERROR_CODES.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 e.ValidationError("DNS rest hosts resolution failed",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const u=i.map(e=>Sc(e,Cc(e.protocol,r))),h=Sc(c,Cc(c.protocol,r)),p=_c(n,r);return{appKey:o,websocketUrl:h,websocketUrls:u,syncWebsocketUrls:p,baseUrl:a,restBaseUrl:Tc(l,Cc(l.protocol,r)),dnsConfig:n}}catch(i){e.logger.warn("DNS config candidate failed",{baseUrl:a,reason:i instanceof Error?i.message:String(i),error:i instanceof Error&&"function"==typeof i.toJSON?i.toJSON():i}),n=i}const o={stage:"dns"};throw n&&(o.reason=n.message,"code"in n&&"number"==typeof n.code&&(o.causeCode=n.code)),new e.ConnectionError("DNS_CONFIG exhausted",{code:e.ERROR_CODES.CONNECTION_DNSLIST_FAILED,details:o})}const Nc=t=>new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),Dc=e=>{if(!d.isRecord(e))throw Nc("Invalid REST response");return d.isRecord(e.data)?e.data:e},wc=(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}}},Uc=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},Lc=t=>{const{orgName:s,appName:r}=e.parseAppKey(t.appKey);return`/${s}/${r}`},Pc=async(e,t)=>{const s=await e.get((e=>`${Lc(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Dc(e),s=wc(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw Nc("Invalid token expires response");return s})(s)},kc=async(e,t,s)=>{const r=await e.get(((e,t)=>{const s=t?.channelName??"*",r=u.createQueryParams({channelName:s});return`${Lc(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=Dc(e);return{appId:Uc(t,["app_id","appId"])??"",rtcToken:Uc(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Uc(t,["channel_name","channelName"])??"",rtcUid:wc(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:wc(t,["expires_in","expire","expireAt"])??0}})(r)},xc=async(e,t,s)=>{const r=await e.post((e=>`${Lc(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Dc(e),s={};for(const[r,n]of Object.entries(t)){const e=Number(r);!Number.isSafeInteger(e)||e<0||"string"!=typeof n||(s[e]=n)}return s})(r)},Fc=async(e,t)=>{const s=await e.get((e=>`${Lc(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=d.isRecord(e)&&Array.isArray(e.data)?e.data:[],r=[];for(const n of s){if(!d.isRecord(n))continue;const e=Uc(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&r.push(`${t.userId}/${e}`)}return r})(s,t)};class Bc{constructor(e){this.options=e,this.pendingGroups=new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,s){if(!e||!t)return;const r=this.pendingGroups.get(e)??new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,r),this.pendingOrder.push(e));const n=r.get(t);r.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(n?.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()),r=Math.max(1,this.options.maxBatchSize);for(let n=0;n<s.length;n+=r)this.readyGroups.push({groupId:e,targets:s.slice(n,n+r)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const t=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(t<0)return;const s=this.readyGroups.splice(t,1)[0];if(!s)return;this.activeGroupCount+=1,this.activeGroups.add(s.groupId),Promise.resolve(this.options.onFlushGroup(s)).catch(t=>{e.logger.warn("Group namecard hydration queue flush failed",{groupId:s.groupId,userIds:s.targets.map(e=>e.userId),error:t instanceof Error?t.message:String(t)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(s.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),s=t-e;return s<=0?t:e+Math.floor(Math.random()*(s+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Gc{constructor(e){this.options=e,this.pendingTargets=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 t=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<t&&this.readyBatches.length>0;){const t=this.readyBatches.shift();if(!t)return;const r=this.generation;this.activeCount+=1;const n=t.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let o;try{o=Promise.resolve(this.options.onFlush(n))}catch(s){o=Promise.reject(s instanceof Error?s:new Error(String(s)))}o.catch(s=>{const n=t.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(e.logger.warn("User info hydration queue flush failed",{targets:t.map(e=>e.userId),retrying:n.length>0,error:s instanceof Error?s.message:String(s)}),r===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 r=s[t];return void(r&&(s[t]=this.mergeTarget(r,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 qc=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Kc=class s{constructor(s){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t.ConnectionStatus.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=new Set,this.config={appKey:s.appKey,appId:s.appId,enableUserInfoSync:s.enableUserInfoSync,enableSyncData:[...s.enableSyncData],enableDeliveryReceipt:s.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:s.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...s.syncConversationListConfig},useCustomAttachmentUpload:s.useCustomAttachmentUpload,enableMd5Check:s.enableMd5Check,serviceConfig:{mode:s.serviceConfig.mode,dnsConfigUrls:[...s.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:s.serviceConfig.hasCustomDnsConfigUrls,serverUrls:s.serviceConfig.serverUrls},useFixedDeviceId:s.useFixedDeviceId,deviceId:s.deviceId,useReplacedMessageContents:s.useReplacedMessageContents,customDeviceName:s.customDeviceName,customOSPlatform:s.customOSPlatform,uiKitVersion:s.uiKitVersion,loginExtensionInfo:s.loginExtensionInfo,cacheEncryptionMode:s.cacheEncryptionMode,profileSync:{...s.profileSync},platformAdapterOptions:s.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=Ir(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new ca,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 Gc({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:e.USER_INFO_HYDRATION_MAX_CONCURRENCY,maxRetries:e.USER_INFO_HYDRATION_MAX_RETRIES,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Bc({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:e.GROUP_NAMECARD_HYDRATION_MIN_WINDOW_MS,maxBatchSize:e.GROUP_NAMECARD_HYDRATION_BATCH_SIZE,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[t.ConnectionEventName.CONNECTING]:e=>{this.updateState(e.state)},[t.ConnectionEventName.CONNECTED]:e=>{this.updateState(e.state)},[t.ConnectionEventName.DISCONNECTED]:e=>{this.updateState(e.state)},[t.ConnectionEventName.RECONNECT_FAILED]:e=>{this.updateState(e.state)},[o.ChatEventName.MESSAGE]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[o.ChatEventName.STREAM_MESSAGE]:e=>{this.handleIncomingConversationStreamMessage(e)},[t.InternalEventName.MESSAGE_SENT]:e=>{this.handleOutgoingConversationMessage(e)},[o.ChatEventName.MULTI_DEVICE_CONTACT]:e=>{this.handleMultiDeviceContactEvent(e)},[o.ChatEventName.MULTI_DEVICE_CONVERSATION]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[o.ContactEventName.ADDED]:e=>this.handleIncomingContactRosterEvent("add",e),[o.ContactEventName.AGREED]:e=>this.handleIncomingContactRosterEvent("add",e),[o.ContactEventName.INVITED]:e=>this.handleIncomingContactRosterEvent("none",e),[o.ContactEventName.REFUSE]:e=>this.handleIncomingContactRosterEvent("none",e),[o.ContactEventName.DELETED]:e=>this.handleIncomingContactRosterEvent("remove",e),[t.InternalEventName.GROUP_NOTIFY]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===o.GroupEventName.GROUP_DESTROYED&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[t.InternalEventName.CHATROOM_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[t.InternalEventName.CHAT_THREAD_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[t.InternalEventName.USER_INFO_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(r){const n=t.Validator.validateOrThrow(ac,r),o=n.customOSPlatform,i=s.normalizeServiceConfig(n.serviceConfig),a={appKey:n.appKey,appId:n.appId,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:s.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==o?n.customDeviceName:void 0,customOSPlatform:o,uiKitVersion:n.uiKitVersion,loginExtensionInfo:n.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:e.USER_INFO_HYDRATION_WINDOW_MS,userInfoBatchSize:e.USER_INFO_HYDRATION_BATCH_SIZE,groupNamecardWindowMs:e.GROUP_NAMECARD_HYDRATION_WINDOW_MS,groupNamecardMaxConcurrency:e.GROUP_NAMECARD_HYDRATION_MAX_CONCURRENCY},platformAdapterOptions:n.platformAdapterOptions},c=r.managers??[];if(s.instance){if(!s.isSameConfig(s.instance.config,a))throw new e.ValidationError("ChatClient already initialized with different config",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:s.instance.config,next:a}});return c.length>0&&s.instance.registerManagers(c),s.instance.validateOptionalCapabilityDependencies(),s.instance}return s.instance=new s(a),c.length>0&&s.instance.registerManagers(c),s.instance.validateOptionalCapabilityDependencies(),s.instance}async login(r){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const n=t.Validator.validateOrThrow(cc,r);if(this.state===t.ConnectionStatus.CONNECTING||this.state===t.ConnectionStatus.CONNECTED){const t=this.currentUserId&&this.currentUserId!==n.userId;throw new e.ConnectionError(t?"Another user is already logged in":"ChatClient is already connecting or connected",{code:t?e.ERROR_CODES.USER_ALREADY_LOGIN_ANOTHER:e.ERROR_CODES.AUTH_ALREADY_LOGIN,details:{stage:"auth",...t?{currentUserId:this.currentUserId,nextUserId:n.userId}:{}}})}const o=++this.loginAttempt;let i=this.config.appKey??null;this.activeAppKey=i,e.logger.warn("Login started",{userId:n.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const a=this.platformAdapter??Ir(this.config.platformAdapterOptions);this.platformAdapter=a,e.installDataReporter({requestAdapter:a.request,onDiagnostic:(t,s)=>{e.logger.warn(t,s)}});const c=e.startDataReportSession({appKey:i??"default#appkey",uid:n.userId,sdkVersion:mc,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(t=>{e.updateDataReportNetworkType(t)}).catch(()=>{e.updateDataReportNetworkType("unknown")});const l=e.startDataReportOperation({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:n.userId});let u,h,p;this.updateState(t.ConnectionStatus.CONNECTING),this.logReportEnabled=!1,e.setLogReportState("unknown");let m,g=!1,f=!1,y=!0;if("dns"===this.config.serviceConfig.mode){const s=l?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await Mc(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});i=t.appKey,this.activeAppKey=i,e.updateDataReportSession({appKey:i}),e.logger.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,g="true"===t.dnsConfig.enableReportLogs,m=t.dnsConfig.reportInterval,f="true"===t.dnsConfig.enableMd5Check,y="false"!==t.dnsConfig.uploadinparts_enable,s?.finish({code:200,success:!0}),e.applyDataReportDnsSwitch(t.dnsConfig.enableDataReport),e.logger.debug("DNS report switch resolved",{enabled:g})}catch(R){const r=R instanceof e.SDKError?R.code:-1,n=R instanceof Error?R.message:String(R);throw s?.finish({code:r,success:!1,description:n}),l?.finish({code:r,success:!1,description:n}),e.applyDataReportDnsSwitch(void 0),e.setLogReportState("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t.ConnectionStatus.DISCONNECTED),R}}else{const s=this.config.serviceConfig.serverUrls;if(!s?.wsUrl||!s.restApiUrl){const s=new e.ValidationError("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:e.ERROR_CODES.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:s.code,success:!1,description:s.message}),e.applyDataReportDnsSwitch(void 0),this.updateState(t.ConnectionStatus.DISCONNECTED),s}u=s.wsUrl,p=s.restApiUrl,f=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=s.syncWsUrl?[s.syncWsUrl]:[],this.contactSyncDnsResolved=!1,e.applyDataReportDnsSwitch(void 0)}if(!i){const s=new e.ValidationError("appKey is unavailable after service discovery",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter(),s}if(e.updateLogReportContext({restBaseUrl:p,appKey:i,userId:n.userId,token:n.token,requestAdapter:a.request}),e.setLogReportInterval(m),this.logReportEnabled=g,e.setLogReportState(g?"enabled":"disabled"),this.resetCore(),o!==this.loginAttempt){const s=new e.ConnectionError("Login cancelled",{code:e.ERROR_CODES.CONNECTION_CANCELLED,details:{stage:"auth"}});throw l?.finish({code:e.ERROR_CODES.CONNECTION_CANCELLED,success:!1,description:s.message}),this.updateState(t.ConnectionStatus.DISCONNECTED),this.activeAppKey=this.config.appKey??null,e.resetDataReporter(),s}this.core=new gi({serverUrl:u,serverUrls:h,userId:n.userId,token:n.token,appKey:i,restBaseUrl:p,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:f,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:c,platformAdapter:a,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),e.updateLogReportContext({resource:this.core.getClientResource()});const E=l?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:u});try{if(e.logger.warn("Connecting core websocket",{serverUrl:u,restBaseUrl:p,userId:n.userId}),await this.core.connect(),E?.finish({code:200,success:!0}),l?.finish({code:0,success:!0}),e.logger.warn("Core websocket connected",{userId:n.userId,resource:this.core.getClientResource()}),this.currentUserId=n.userId,e.updateDataReportSession({uid:n.userId}),this.restBaseUrl=p??null,this.authToken=n.token,this.clientResource=this.core.getClientResource(),await this.initCacheManager(n.userId),e.logger.warn("Cache initialized after login",{userId:n.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),await this.syncSelfUserInfoAfterLogin(),this.config.enableSyncData.includes("conversation")&&await this.refreshSessionList(this.config.syncConversationListConfig),this.triggerConfiguredSyncDataAfterLogin(n.userId),this.logReportEnabled)try{await e.reportLogsNow()}catch(R){e.logger.warn("Report logs on login failed",R)}}catch(R){const s=R instanceof e.SDKError?R.code:-1,r=R instanceof Error?R.message:String(R);throw E?.finish({code:s,success:!1,description:r}),l?.finish({code:s,success:!1,description:r}),this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter(),R}}async logout(){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.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(t.ConnectionStatus.DISCONNECTED),this.logReportEnabled=!1,e.setLogReportState("disabled"),e.stopLogReporter(),void e.resetDataReporter();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await e.reportLogsNow()}catch(r){e.logger.warn("Report logs on logout failed",r)}await this.core.disconnect()}finally{this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t.ConnectionStatus.DISCONNECTED),this.logReportEnabled=!1,e.setLogReportState("disabled"),e.stopLogReporter(),e.resetDataReporter()}}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 e.ValidationError("restBaseUrl is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new e.ValidationError("token is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new e.ValidationError("userId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const t=this.clientResource??this.core?.getClientResource();if(!t)throw new e.ValidationError("clientResource is required",{code:e.ERROR_CODES.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(s){const r=t.Validator.validateOrThrow(dc,s);if(!this.core||!this.currentUserId||this.state!==t.ConnectionStatus.CONNECTED)throw new e.ConnectionError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const n=this.getRestContext(),o={...n},i=new e.RestClient(o.restBaseUrl,{errorMap:qc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(r),e.logger.warn("Renew token started",{userId:n.userId});const a=await Pc(i,o);if(a<=Date.now())throw new e.ConnectionError("Token is expired",{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const c=this.core.renewToken(r,a);return this.authToken=r,e.updateLogReportContext({token:r}),e.logger.warn("Renew token succeeded",{userId:n.userId,expireAt:a}),c}async getRTCTokenInfo(s){const r=t.Validator.validateOrThrow(lc,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:qc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return o.setAuthToken(n.token),e.logger.warn("Get RTC token info started",{userId:n.userId,hasChannelName:Boolean(r?.channelName)}),kc(o,n,r)}async getUserIdsWithRTCUids(s){const r=t.Validator.validateOrThrow(uc,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:qc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return o.setAuthToken(n.token),e.logger.warn("Get userIds with RTC UIDs started",{userId:n.userId,count:r.length}),xc(o,n,r)}async getSelfIdsOnOtherPlatform(){const t=this.getRestContext(),s=new e.RestClient(t.restBaseUrl,{errorMap:qc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(t.token),e.logger.warn("Get self ids on other platform started",{userId:t.userId,clientResource:t.clientResource}),Fc(s,t)}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 rc({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===L.START_COMPLETED||e.stream.status===L.FULL||e.stream.status===L.COMPLETED||e.stream.status===L.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:dn(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 r=await h.resolveSingleContactUserInfo(t,{cacheManager:this.cacheManager,fetchUserInfos:s?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=r}async fetchContactEventUserInfos(t){if(0===t.length)return[];const s=this.getUserInfoReadCapability();if(!s)return[];try{return await s.getUserInfoByUserId({userIds:t})}catch(r){return e.logger.warn("Contact roster event user info fetch failed",{userIds:t,error:r}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const t=this.getUserInfoReadCapability();if(t)try{0===(await t.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&e.logger.warn("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(s){e.logger.warn("Self user info sync failed after login",{userId:this.currentUserId,error:s})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=on(e),s=e.sender.userId;if(!s||!this.cacheManager)return;const r=this.cacheManager.getUserInfoSummaries([s],!1)[0];if(r&&(e.sender={userId:s,nickname:r.nickname??e.sender.nickname,avatarUrl:r.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(r?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(s,t.userInfoUpdateTime):r||this.userInfoHydrationQueue.enqueue(s),"groupChat"!==e.conversationType)return;const n=this.cacheManager.getGroupNamecard(e.conversationId,s,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(n?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,s,t.namecardUpdateTime):n||this.groupNamecardHydrationQueue.enqueue(e.conversationId,s)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{rn.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};nn(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(t){const s=this.getUserInfoReadCapability();if(!s||0===t.length)return;const r=t.map(e=>e.userId);let n;try{n=await s.getUserInfoByUserId({userIds:r})}catch(l){throw e.logger.warn("User info hydration failed",{userIds:r,error:l}),l}const o=this.currentUserId,i=o?n.find(e=>e.userId===o):void 0,a=n.filter(e=>e.userId!==o);i&&this.dispatchOwnInfoUpdated(i),a.length>0&&this.dispatchUserInfoUpdated(a),n.length>0&&this.refreshConversationDisplayFromUserInfos(n.map(e=>({userId:e.userId})),"profile");const c=new Set(n.map(e=>e.userId)),d=r.filter(e=>!c.has(e));d.length>0&&e.logger.warn("User info hydration returned partial result",{requestedUserIds:r,missingUserIds:d})}async flushGroupNamecardHydrationBatch(t){const s=this.getGroupNamecardHydrationCapability();if(s&&0!==t.targets.length)try{await s.hydrateMessageProfileGroupNamecards(t.groupId,t.targets)}catch(r){e.logger.warn("Group namecard hydration returned partial result",{groupId:t.groupId,requestedUserIds:t.targets.map(e=>e.userId),error:r})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(t){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(r,n){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!r?.sender?.userId)throw new e.ValidationError("sender.userId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&r.sender.userId!==this.currentUserId)throw new e.ValidationError("sender.userId does not match current user",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(P(r))throw new e.MessageSendError("Stream message send is not supported",{code:e.ERROR_CODES.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:r.msgLocalId,retryable:!1}});if(!this.core||this.state!==t.ConnectionStatus.CONNECTED)throw new e.MessageSendError("ChatClient is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:r.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(r),this.core.sendMessage(r,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=new Set;for(const n of e){const e="groupChat"===n.conversationType?n.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),r=new Set(s.map(e=>e.userId));for(const n of t)r.has(n)||this.userInfoHydrationQueue.enqueue(n)}dispatchUserGroupNamecardUpdated(e,t,s){e&&t&&this.eventHub.dispatch(o.GroupEventName.USER_GROUP_NAMECARD_UPDATED,{groupId:e,userId:t,namecard:s})}async downloadAndParseCombinePayload(t){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,r){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.downloadAttachment(t)}decodeServerMessageMeta(t){if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.decodeServerMessageMeta(t)}registerManagers(t){if(0===t.length)return;const s=new Set;for(const r of t){const t=this.resolveManagerKey(r);if(s.has(t))throw this.buildManagerValidationError(`Manager key duplicated: ${t}`,e.ERROR_CODES.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t});s.add(t)}for(const e of t)this.registerManagerInput(e)}registerManagerInput(e){return s.isManagerConstructor(e)?this.registerManagerConstructor(e):this.registerManagerInstance(e)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),s=this.managerRegistry.get(t);if(s){if(s.constructor===e)return s;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const r=new e;return r.bind(this,this.managerEventContext),this.managerRegistry.set(t,r),this.registerManagerCapabilities(r),this.attachManager(t,r),r}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,r){return new e.ValidationError(`${t} requires explicit manager capability: ${s}`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} requires explicit manager capability: ${s}`,rule:"dependency"}],capability:s,requiredManagers:r}})}resolveManagerKey(t){if(s.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",e.ERROR_CODES.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}getManagerKeyFromConstructor(t){const s=t.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.ERROR_CODES.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.ERROR_CODES.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(t,s,r,n,o){return new e.ValidationError(t,{code:s,details:{fields:[{path:r,message:t,rule:n}],...o}})}buildManagerConflictError(t,s,r,n){return this.buildManagerValidationError("Manager key conflict",e.ERROR_CODES.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t,existingName:s,incomingName:r,reason:n})}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 aa({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(c.toConversationItem),r=this.buildConversationListPatch(this.conversationListSnapshot,s,t);(r.reset||0!==r.upserted.length||0!==r.removed.length||r.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=s,this.eventHub.dispatch(o.ChatEventName.CONVERSATION_LIST_UPDATE,{version:this.conversationListVersion,items:s,reason:e,patch:r}))}buildConversationListPatch(e,t,s){const r=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),o=new Set,i=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=r.get(e);t&&this.isConversationListItemEqual(t,d)||(i.push(d),o.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),o.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)o.add(this.buildConversationListKey(d));return{reset:s,upserted:i,removed:a,affectedKeys:[...o],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(t){this.config.enableSyncData.includes("contact")&&(e.logger.warn("Triggering automatic contact sync after login",{userId:t}),this.triggerContactSync()),this.config.enableSyncData.includes("group")&&(e.logger.warn("Triggering automatic group sync after login",{userId:t}),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 Ja(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const t=this.managerRegistry.get("contactManager");if(!t?.createSyncController)throw new e.ValidationError("ContactManager is required for contact sync",{code:e.ERROR_CODES.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 nc(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 e.ValidationError("GroupManager is required for group sync",{code:e.ERROR_CODES.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(o.ChatEventName.SYNC_DATA_START,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(o.ChatEventName.SYNC_DATA_FINISHED,e)}requireCacheManager(){if(!this.cacheManager)throw new e.ValidationError("cacheManager is required",{code:e.ERROR_CODES.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 e.logger.warn("Automatic contact sync sync-ws is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new e.SDKError("Contact sync websocket urls are unavailable",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw e.logger.warn("Automatic contact sync sync-ws is unavailable without dns service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new e.SDKError("Contact sync websocket urls are unavailable",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await Mc(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(s){throw e.logger.warn("Automatic contact sync sync-ws DNS resolve failed",{userId:this.currentUserId,reason:s instanceof Error?s.message:String(s)}),new e.SDKError("Contact sync websocket dns resolve failed",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:s instanceof Error?s.message:String(s)}})}if(0===this.contactSyncWsUrls.length)throw e.logger.warn("Automatic contact sync sync-ws is unavailable after DNS resolve",{userId:this.currentUserId,serviceConnectionMode:"dns"}),new e.SDKError("Contact sync websocket urls are unavailable",e.ERROR_CODES.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 e.ValidationError("token is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(t,s){const r=t.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new e.ValidationError("sync websocket URL must use ws or wss protocol");const n=r.indexOf("#"),o=n>=0?r.slice(n):"",i=n>=0?r.slice(0,n):r,a=i.indexOf("?"),c=a>=0?i.slice(0,a):i,d=a>=0?i.slice(a+1):"",l=c.indexOf("://")+3,u=c.indexOf("/",l),h=u<0||"/"===c.slice(u)?`${c}/ws`:c,p=d.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),m=encodeURIComponent(s).replace(/%20/g,"+");return p.push(`token=${m}`),`${h}?${p.join("&")}${o}`}shuffleContactSyncUrls(e){const t=[...e];for(let s=t.length-1;s>0;s-=1){const e=Math.floor(Math.random()*(s+1)),r=t[s],n=t[e];r&&n&&(t[s]=n,t[e]=r)}return t}buildContactRosterRequest(t){const s=this.getContactSyncRestContext(),{orgName:r,appName:n}=e.parseAppKey(s.appKey);return{type:h.RosterMessageType.REQUEST,header:{resource:s.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:r,app:n,username:s.userId,version:t,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 e.ValidationError("appKey is unavailable before DNSConfig resolution",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new e.ValidationError("appKey is unavailable for the current session",{code:e.ERROR_CODES.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,t){return e.appKey===t.appKey&&(e.appId===t.appId&&(!!s.isSameStringArray(e.enableSyncData,t.enableSyncData)&&(e.useCustomAttachmentUpload===t.useCustomAttachmentUpload&&(e.enableMd5Check===t.enableMd5Check&&(!!s.isSameServiceConfig(e.serviceConfig,t.serviceConfig)&&(e.useFixedDeviceId===t.useFixedDeviceId&&(e.deviceId===t.deviceId&&(e.useReplacedMessageContents===t.useReplacedMessageContents&&(e.customDeviceName===t.customDeviceName&&(e.customOSPlatform===t.customOSPlatform&&(e.platformAdapterOptions?.prefer===t.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===t.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.overrides===t.platformAdapterOptions?.overrides&&(e.uiKitVersion===t.uiKitVersion&&(e.cacheEncryptionMode===t.cacheEncryptionMode&&(e.enableUserInfoSync===t.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===t.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===t.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===t.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===t.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===t.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===t.profileSync.groupNamecardMaxConcurrency)))))))))))))))))))}static normalizeServiceConfig(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??gc,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:e?.serverUrls}}static normalizeSyncDataTypes(e){const t=[];for(const s of e)t.includes(s)||t.push(s);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}static isSameServiceConfig(e,t){if(e.mode!==t.mode)return!1;if(e.dnsConfigUrls.length!==t.dnsConfigUrls.length)return!1;for(let s=0;s<e.dnsConfigUrls.length;s+=1)if(e.dnsConfigUrls[s]!==t.dnsConfigUrls[s])return!1;return s.isSameServerUrls(e.serverUrls,t.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl&&e.syncRestApiUrl===t.syncRestApiUrl&&e.syncWsUrl===t.syncWsUrl)}};Kc.instance=null;let Vc=Kc;exports.AuthenticationError=e.AuthenticationError,exports.ConnectionError=e.ConnectionError,exports.MessageReceiveError=e.MessageReceiveError,exports.MessageSendError=e.MessageSendError,exports.NetworkError=e.NetworkError,exports.RestBusinessError=e.RestBusinessError,exports.RestTransportError=e.RestTransportError,exports.SDKError=e.SDKError,exports.StorageError=e.StorageError,exports.UploadError=e.UploadError,exports.ValidationError=e.ValidationError,exports.isSDKError=e.isSDKError,exports.setLogLevel=e.setLogLevel,exports.ChatManager=t.ChatManager,exports.RUNTIME_PLATFORMS=s.RUNTIME_PLATFORMS,exports.Group=i.Group,exports.GroupManager=i.GroupManager,exports.ContactManager=h.ContactManager,exports.ChatThread=p.ChatThread,exports.ChatThreadManager=p.ChatThreadManager,exports.ChatRoom=m.ChatRoom,exports.ChatRoomManager=m.ChatRoomManager,exports.PresenceManager=g.PresenceManager,exports.PushManager=f.PushManager,exports.UserInfoManager=y.UserInfoManager,exports.CONVERSATION_MARK={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},exports.CacheManager=aa,exports.ChatClient=Vc,exports.ImageType={ORIGINAL:"original",LARGE:"large"},exports.StreamMessageStatus=L,exports.createPlatformAdapter=Ir,exports.detectRuntimePlatform=(e,t)=>_t(t,e).platform;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/common-tHGz9VBk.cjs"),t=require("./chunks/chat-manager-BFd2Z4oY.cjs"),s=require("./chunks/reflection-proto-codec-CwrIKT1L.cjs"),r=require("./chunks/light-BcQg8h2W.cjs"),n=require("./chunks/event-system-TYhmgy4K.cjs"),o=require("./chunks/index-DJPAjXAp.cjs"),i=require("./chunks/profile-version-njNs7R5-.cjs"),a=require("./chunks/group-user-info-resolver-B-dyr__b.cjs"),c=require("./chunks/session-list-query-Dslj2k3t.cjs"),d=require("./chunks/cache-utils-gowrxNr8.cjs"),l=require("zod"),u=require("./chunks/query-params-BHyPuD2k.cjs"),h=require("./chunks/index-DtWkVcfb.cjs"),p=require("./managers/chat-thread/index.cjs"),m=require("./managers/chatroom/index.cjs"),g=require("./managers/presence/index.cjs"),f=require("./managers/push/index.cjs"),y=require("./managers/user-info/index.cjs"),E="onChatRoomDestroyed",R="onMembersJoined",I="onMembersExited",v="onRemovedFromChatRoom",C="onMuteListAdded",S="onMuteListRemoved",T="onAllowListAdded",A="onAllowListRemoved",O="onAllMemberMuteStateChanged",b="onAdminAdded",_="onAdminRemoved",M="onOwnerChanged",N="onAnnouncementChanged",D="onChatRoomInfoChanged",w="onAttributesUpdate",L="onAttributesRemoved",U={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function P(e){return"object"==typeof e.stream&&null!==e.stream}const k=0,x=1,F=2,B=3,G=4,q=0,K=1,V=2,z=3,H=4,j=5,W=6,Q=7,$=8,Y=0,J=1,X=2,Z=3,ee=4,te=5,se=6,re=7,ne=8,oe=0,ie=1,ae=2,ce=3,de=4,le=0,ue=1,he=2,pe=3,me=5,ge=0,fe=1,ye=2,Ee=0,Re=0,Ie=2,ve=0,Ce=1,Se=2,Te=3,Ae=4,Oe=5,be=6,_e=7,Me=8,Ne=9,De=10,we=11,Le=12,Ue=13,Pe=14,ke=15,xe=16,Fe=17,Be=18,Ge=19,qe=20,Ke=1,Ve=2,ze=3,He=4,je=5,We=6,Qe=7,$e=8,Ye="Sorry, user register limit",Je="Sorry, user register rate limit",Xe="Sorry, token expired",Ze="Sorry, token or password does not match login info",et="Sorry, user not found",tt="Sorry, the app month live count limit",st="Sorry, the app day live count limit",rt="Sorry, the app online count limit",nt={[Ce]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Se]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Te]:e.ERROR_CODES.VALIDATION_REQUIRED,[Ae]:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,[Oe]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[be]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[_e]:e.ERROR_CODES.AUTH_FORBIDDEN,[Ge]:e.ERROR_CODES.AUTH_FORBIDDEN,[Me]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[Ne]:e.ERROR_CODES.UNKNOWN,[De]:e.ERROR_CODES.UNKNOWN,[we]:e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE,[Le]:e.ERROR_CODES.AUTH_FORBIDDEN,[Ue]:e.ERROR_CODES.AUTH_LOGIN_TOO_MANY_DEVICES,[Pe]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[ke]:e.ERROR_CODES.AUTH_USER_MUTED,[xe]:e.ERROR_CODES.UNKNOWN,[Fe]:e.ERROR_CODES.UNKNOWN,[Be]:e.ERROR_CODES.MESSAGE_DECODE_FAILED,[qe]:e.ERROR_CODES.USER_DEVICE_CHANGED},ot=new Set([Ce,Se,Te,Ae,be,_e,Ge,Ne,De,we,Le,Ue,Pe,ke,xe,Fe,Be,qe]),it={[Ye]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Je]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Xe]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[Ze]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[et]:e.ERROR_CODES.AUTH_UNAUTHORIZED,blocked:e.ERROR_CODES.MESSAGE_BLOCKED_BY_RECIPIENT,"group not found":e.ERROR_CODES.GROUP_NOT_EXIST,"illegal chatroom tag":e.ERROR_CODES.VALIDATION_REQUIRED,"not in group or chatroom":e.ERROR_CODES.GROUP_NOT_JOINED,"exceed recall time limit":e.ERROR_CODES.MESSAGE_RECALL_TIME_LIMIT,"message recall disabled":e.ERROR_CODES.SERVICE_NOT_ENABLED,"group ack not open":e.ERROR_CODES.SERVICE_NOT_ENABLED,"group ack msg permission denied":e.ERROR_CODES.GROUP_PERMISSION_DENIED,"the message has expired":e.ERROR_CODES.MESSAGE_EXPIRED,"limit send group ack msg":e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,"not in group or chatroom white list":e.ERROR_CODES.MESSAGE_ILLEGAL_WHITELIST,nonroster:e.ERROR_CODES.USER_NOT_ON_ROSTER,"group is disabled":e.ERROR_CODES.GROUP_DISABLED,"roaming is not open":e.ERROR_CODES.SERVICE_NOT_ENABLED,"Sorry, message does not exist":e.ERROR_CODES.VALIDATION_REQUIRED,"Sorry, edit limit reached":e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,"Sorry, You do not have permission":e.ERROR_CODES.AUTH_FORBIDDEN,"Sorry, format is incorrect":e.ERROR_CODES.VALIDATION_REQUIRED,"Sorry, edit is not available":e.ERROR_CODES.SERVER_SERVING_DISABLED,"Sorry, edit fail":e.ERROR_CODES.MESSAGE_EDIT_FAILED},at=[["limit directed users",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.ERROR_CODES.AUTH_FORBIDDEN]],ct={[tt]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[st]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[rt]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,"sensitive words":e.ERROR_CODES.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"blocked by mod_antispam":e.ERROR_CODES.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"user is mute":e.ERROR_CODES.USER_MUTED_BY_ADMIN,"traffic limit":e.ERROR_CODES.MESSAGE_CURRENT_LIMITING,"Sorry, data is too large":e.ERROR_CODES.MESSAGE_SIZE_LIMIT},dt=(t,s)=>{if("number"!=typeof t)return{code:e.ERROR_CODES.UNKNOWN,retryable:!0};const r=((t,s)=>{if(s){if(t===Ce){const t=it[s];if(void 0!==t)return t;for(const[e,r]of at)if(s.includes(e))return r;try{const t=JSON.parse(s);if("moderation"===t.error_type)return e.ERROR_CODES.THIRD_MODERATION_FAILED;if("string"==typeof t.error_type)return e.ERROR_CODES.THIRD_DEFAULT_FAILED}catch{}return}return t===_e?ct[s]:t===Ge?e.ERROR_CODES.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===ke?e.ERROR_CODES.AUTH_USER_MUTED:void 0}})(t,s),n=nt[t]??e.ERROR_CODES.UNKNOWN;return{code:r??n,retryable:!ot.has(t)}},lt={[e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED]:"Message operation exceeded a service limit",[e.ERROR_CODES.AUTH_TOKEN_EXPIRED]:"Message cannot be sent because the authentication token expired",[e.ERROR_CODES.VALIDATION_REQUIRED]:"Message cannot be sent because the request is invalid",[e.ERROR_CODES.AUTH_UNAUTHORIZED]:"Message cannot be sent because authentication failed",[e.ERROR_CODES.AUTH_FORBIDDEN]:"Message operation is forbidden",[e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE]:"Message cannot be sent because the account is bound to another device",[e.ERROR_CODES.AUTH_LOGIN_TOO_MANY_DEVICES]:"Message cannot be sent because the account is logged in on too many devices",[e.ERROR_CODES.AUTH_USER_MUTED]:"Message cannot be sent because the user is muted in the group or chat room",[e.ERROR_CODES.MESSAGE_BLOCKED_BY_RECIPIENT]:"Message cannot be sent because you are blocked by the recipient",[e.ERROR_CODES.USER_MUTED_BY_ADMIN]:"Message cannot be sent because the user is globally muted",[e.ERROR_CODES.USER_DEVICE_CHANGED]:"Message cannot be sent because the current device has changed",[e.ERROR_CODES.USER_NOT_ON_ROSTER]:"Message cannot be sent because the recipient is not in your contact list",[e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR]:"Message cannot be sent because the server is unreachable",[e.ERROR_CODES.SERVER_SERVING_DISABLED]:"Message editing is not available",[e.ERROR_CODES.MESSAGE_DECODE_FAILED]:"Message processing failed",[e.ERROR_CODES.MESSAGE_INCLUDE_ILLEGAL_CONTENT]:"Message contains prohibited content",[e.ERROR_CODES.MESSAGE_SEND_TRAFFIC_LIMIT]:"Message sending traffic limit exceeded",[e.ERROR_CODES.MESSAGE_RECALL_TIME_LIMIT]:"The message recall time limit has been exceeded",[e.ERROR_CODES.SERVICE_NOT_ENABLED]:"The required messaging service is not enabled",[e.ERROR_CODES.MESSAGE_EXPIRED]:"The message has expired",[e.ERROR_CODES.MESSAGE_ILLEGAL_WHITELIST]:"The user is not in the group or chat room allowlist",[e.ERROR_CODES.MESSAGE_EXTERNAL_LOGIC_BLOCKED]:"The message was blocked by external logic",[e.ERROR_CODES.MESSAGE_CURRENT_LIMITING]:"Message sending rate limit exceeded",[e.ERROR_CODES.MESSAGE_SIZE_LIMIT]:"Message size exceeds the limit",[e.ERROR_CODES.MESSAGE_EDIT_FAILED]:"Message editing failed",[e.ERROR_CODES.GROUP_NOT_JOINED]:"The user is not in the group or chat room",[e.ERROR_CODES.GROUP_PERMISSION_DENIED]:"The user does not have permission to perform this group message operation",[e.ERROR_CODES.GROUP_NOT_EXIST]:"The group does not exist",[e.ERROR_CODES.GROUP_DISABLED]:"The group is disabled",[e.ERROR_CODES.THIRD_MODERATION_FAILED]:"The message was rejected by content moderation",[e.ERROR_CODES.THIRD_DEFAULT_FAILED]:"The message was rejected by a third-party service"},ut=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let s=0;s<e.length;s+=1){let r=e.charCodeAt(s);if(r>=55296&&r<=56319&&s+1<e.length){const t=e.charCodeAt(s+1);t>=56320&&t<=57343&&(r=65536+(r-55296<<10)+(t-56320),s+=1)}r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|63&r):r<=65535?t.push(224|r>>12,128|r>>6&63,128|63&r):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}return new Uint8Array(t)},ht=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0;s<e.length;s+=1){const r=e[s]??0;if(r<128){t+=String.fromCharCode(r);continue}if(r>=192&&r<224){const n=e[s+1]??0;t+=String.fromCharCode((31&r)<<6|63&n),s+=1;continue}if(r>=224&&r<240){const n=e[s+1]??0,o=e[s+2]??0;t+=String.fromCharCode((15&r)<<12|(63&n)<<6|63&o),s+=2;continue}const n=((7&r)<<18|(63&(e[s+1]??0))<<12|(63&(e[s+2]??0))<<6|63&(e[s+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),s+=3}return t};class pt{constructor(){this.lastEventKey=null}normalize(e,s){const r=(e=>{switch(e){case t.ConnectionStatus.CONNECTING:case t.ConnectionStatus.RECONNECTING:return t.ConnectionEventName.CONNECTING;case t.ConnectionStatus.CONNECTED:return t.ConnectionEventName.CONNECTED;case t.ConnectionStatus.DISCONNECTED:return t.ConnectionEventName.DISCONNECTED;case t.ConnectionStatus.RECONNECT_FAILED:return t.ConnectionEventName.RECONNECT_FAILED;default:return null}})(e);if(!r)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("|"))(r,s);return this.lastEventKey===n?null:(this.lastEventKey=n,{eventName:r,payload:s})}reset(){this.lastEventKey=null}}const mt={web:e.RUNTIME_PLATFORMS.WEB,"mp-weixin":e.RUNTIME_PLATFORMS.WECHAT_MINIAPP,"mp-alipay":e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,"mp-baidu":e.RUNTIME_PLATFORMS.BAIDU_MINIAPP,"mp-toutiao":e.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,"mp-lark":e.RUNTIME_PLATFORMS.LARK_MINIAPP,"mp-qq":e.RUNTIME_PLATFORMS.QQ_MINIAPP,"mp-kuaishou":e.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,"mp-jd":e.RUNTIME_PLATFORMS.JD_MINIAPP,"mp-360":e.RUNTIME_PLATFORMS.MINIAPP_360,"mp-harmony":e.RUNTIME_PLATFORMS.HARMONY_MINIAPP,"quickapp-webview":e.RUNTIME_PLATFORMS.QUICKAPP,"quickapp-webview-union":e.RUNTIME_PLATFORMS.QUICKAPP,"quickapp-webview-huawei":e.RUNTIME_PLATFORMS.QUICKAPP},gt=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},ft=e=>(e=>gt(e,"canIUse")&>(e,"getSystemInfo"))(e)||(e=>gt(e,"request")&>(e,"connectSocket"))(e),yt=e=>gt(e,"request")&>(e,"connectSocket")&>(e,"uploadFile"),Et=(t,s)=>s===e.RUNTIME_PLATFORMS.WECHAT_MINIAPP?t.wx:s===e.RUNTIME_PLATFORMS.QQ_MINIAPP?t.qq:s===e.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP?t.tt:s===e.RUNTIME_PLATFORMS.BAIDU_MINIAPP?t.swan:s===e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP?t.my:s===e.RUNTIME_PLATFORMS.DINGTALK_MINIAPP?t.dd:s===e.RUNTIME_PLATFORMS.JD_MINIAPP?t.jd:s===e.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP?t.ks:s===e.RUNTIME_PLATFORMS.UNIAPP?t.uni:void 0,Rt=e=>{const t=e?.miniGlobal;return ft(t)?t:e},It=e=>{const t=Rt(e);return yt(t)?t:void 0},vt=e=>void 0!==e.window&&void 0!==e.document,Ct=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),St=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(ft(t))return!0;try{if(!gt(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},Tt=t=>yt(t.wx)?e.RUNTIME_PLATFORMS.WECHAT_MINIAPP:yt(t.my)?e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP:yt(t.dd)?e.RUNTIME_PLATFORMS.DINGTALK_MINIAPP:yt(t.swan)?e.RUNTIME_PLATFORMS.BAIDU_MINIAPP:yt(t.tt)?e.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP:yt(t.qq)?e.RUNTIME_PLATFORMS.QQ_MINIAPP:yt(t.jd)?e.RUNTIME_PLATFORMS.JD_MINIAPP:yt(t.ks)?e.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP:void 0,At=e=>void 0!==Tt(e),Ot=t=>{const s=Tt(t);if(s)return s;try{const s=t.uni?.getSystemInfoSync?.(),r=s?.uniPlatform;if("string"==typeof r)return mt[r]??e.RUNTIME_PLATFORMS.UNIAPP}catch{return e.RUNTIME_PLATFORMS.UNIAPP}return vt(t)?e.RUNTIME_PLATFORMS.WEB:e.RUNTIME_PLATFORMS.UNIAPP},bt=(e,t)=>{const s=It(Et(e,t));if(s)return s;const r=It(e.uni);return r||(e.uni??e)},_t=(t,s)=>{const r=t??e.getRuntimeGlobal();if(s){const t=s===e.RUNTIME_PLATFORMS.UNIAPP||St(r),n=t?Ot(r):s;return{platform:s,hostPlatform:n,framework:t?"uniapp":vt(r)?"web":"native",global:t?bt(r,n):Rt(Et(r,s))??r}}if(St(r)){const t=Ot(r);return{platform:e.RUNTIME_PLATFORMS.UNIAPP,hostPlatform:t,framework:"uniapp",global:bt(r,t)}}return ft(r.swan)?{platform:e.RUNTIME_PLATFORMS.BAIDU_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.BAIDU_MINIAPP,framework:"native",global:Rt(r.swan)??r.swan}:ft(r.tt)?{platform:e.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,framework:"native",global:Rt(r.tt)??r.tt}:ft(r.dd)?{platform:e.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,framework:"native",global:Rt(r.dd)??r.dd}:ft(r.my)?{platform:e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,framework:"native",global:Rt(r.my)??r.my}:ft(r.wx)?{platform:e.RUNTIME_PLATFORMS.WECHAT_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.WECHAT_MINIAPP,framework:"native",global:Rt(r.wx)??r.wx}:ft(r.qq)?{platform:e.RUNTIME_PLATFORMS.QQ_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.QQ_MINIAPP,framework:"native",global:Rt(r.qq)??r.qq}:ft(r.jd)?{platform:e.RUNTIME_PLATFORMS.JD_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.JD_MINIAPP,framework:"native",global:Rt(r.jd)??r.jd}:ft(r.ks)?{platform:e.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,hostPlatform:e.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,framework:"native",global:Rt(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:e.RUNTIME_PLATFORMS.REACT_NATIVE,hostPlatform:e.RUNTIME_PLATFORMS.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:vt(r)?e.RUNTIME_PLATFORMS.ELECTRON_RENDERER:e.RUNTIME_PLATFORMS.ELECTRON_MAIN,hostPlatform:vt(r)?e.RUNTIME_PLATFORMS.ELECTRON_RENDERER:e.RUNTIME_PLATFORMS.ELECTRON_MAIN,framework:"electron",global:r}:Ct(r)||vt(r)?{platform:e.RUNTIME_PLATFORMS.WEB,hostPlatform:e.RUNTIME_PLATFORMS.WEB,framework:Ct(r)?"worker":"web",global:r}:{platform:e.RUNTIME_PLATFORMS.UNKNOWN,hostPlatform:e.RUNTIME_PLATFORMS.UNKNOWN,framework:"native",global:r}},Mt=t=>t===e.RUNTIME_PLATFORMS.WECHAT_MINIAPP||t===e.RUNTIME_PLATFORMS.QQ_MINIAPP||t===e.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP||t===e.RUNTIME_PLATFORMS.BAIDU_MINIAPP||t===e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||t===e.RUNTIME_PLATFORMS.DINGTALK_MINIAPP||t===e.RUNTIME_PLATFORMS.LARK_MINIAPP||t===e.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP||t===e.RUNTIME_PLATFORMS.JD_MINIAPP||t===e.RUNTIME_PLATFORMS.MINIAPP_360||t===e.RUNTIME_PLATFORMS.HARMONY_MINIAPP||t===e.RUNTIME_PLATFORMS.QUICKAPP||t===e.RUNTIME_PLATFORMS.UNIAPP,Nt=["request","upload","socket","proto"],Dt=(t,s=Nt)=>{const r=((e,t=Nt)=>t.filter(t=>!e[t]))(t,s);if(0!==r.length)throw e.createPlatformError("Platform missing required capabilities.",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{required:[...s],missing:r}})},wt={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}}}}}}}}}},Lt=t=>{if(!t||0===t.trim().length)throw e.createPlatformError("Proto type name is required.",{code:e.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:e.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:t}})};class Ut{constructor(){this.codecMap=new Map}register(e,t){Lt(e),this.codecMap.set(e,t)}registerType(t,s){this.register(t,{encode:r=>{const n=((t,s)=>{if("object"==typeof t&&null!==t)return t;throw e.createPlatformError("Proto payload must be an object.",{code:e.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:e.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:s,payloadType:typeof t}})})(r,t),o=s.fromObject(n);return s.encode(o).finish()},decode:e=>{const t=s.decode(e);return s.toObject(t,{longs:String,enums:Number,defaults:!1})}})}get(e){return Lt(e),this.codecMap.get(e)}getOrThrow(t){const s=this.get(t);if(s)return s;throw e.createPlatformError("Proto codec not found.",{code:e.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:e.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:t}})}}let Pt=!1,kt=null,xt=null,Ft=null;const Bt=e=>e.startsWith(".")?e.slice(1):e,Gt=e=>e instanceof r.lightExports.Namespace,qt=e=>e instanceof r.lightExports.Type,Kt=e=>{for(const t of e.nestedArray)qt(t)?s.installReflectionCodecRecursive(t):Gt(t)&&Kt(t)},Vt=()=>{Pt||(r.lightExports.util.Long=s.Long,r.lightExports.configure(),Pt=!0),s.installReflectionRuntime();const e=r.lightExports.Root.fromJSON(wt);return Kt(e),e},zt=(e,t)=>{const r=e.nestedArray;for(const n of r){if(qt(n)){const e=Bt(n.fullName);s.installReflectionCodecRecursive(n),t.registerType(e,n);continue}Gt(n)&&zt(n,t)}},Ht=(t,s,r)=>{const n=s instanceof Error?s.message:String(s);return e.createPlatformError(`Static proto ${r} failed.`,{code:e.PLATFORM_ERROR_CODE.PROTO_FAILED,stage:e.PLATFORM_ERROR_STAGE.PROTO,retryable:!1,details:{typeName:t,operation:r,cause:n}})},jt=()=>kt||(kt=Vt(),kt),Wt=()=>{if(Ft)return Ft;const e=(()=>{if(xt)return xt;const e=new Ut,t=jt();return zt(t,e),xt=e,e})();return Ft={encode(t,s){try{return e.getOrThrow(Bt(t)).encode(s)}catch(r){throw Ht(t,r,"encode")}},decode(t,s){try{return e.getOrThrow(Bt(t)).decode(s)}catch(r){throw Ht(t,r,"decode")}}},Ft},Qt=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,$t=e=>"function"==typeof e.on&&"function"==typeof e.off,Yt=(t,s,r)=>{if(Qt(t))return t.addEventListener(s,r),()=>{t.removeEventListener(s,r)};if($t(t)){const e=t;return e.on(s,r),()=>{e.off(s,r)}}throw e.createPlatformError("Socket event listener API is unsupported.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!1,details:{event:s}})},Jt=(t,s,r)=>{if(Qt(t)){const e=(...n)=>{t.removeEventListener(s,e),r(...n)};return t.addEventListener(s,e),()=>{t.removeEventListener(s,e)}}if($t(t)){const e=t;if("function"==typeof e.once)return e.once?.(s,r),()=>{e.off(s,r)};let n=()=>{};return n=Yt(t,s,(...e)=>{n(),r(...e)}),n}throw e.createPlatformError("Socket one-time listener API is unsupported.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!1,details:{event:s}})},Xt=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?Xt(e.data):null;var t},Zt=t=>{const s=new Set,r=new Set,n=new Set,o=new Set;return Yt(t,"open",()=>{s.forEach(e=>{e()})}),Yt(t,"message",(...e)=>{const t=Xt(e[0]);null!==t&&r.forEach(e=>{e(t)})}),Yt(t,"error",(...e)=>{const t=e[0];n.forEach(e=>{e(t)})}),Yt(t,"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);o.forEach(e=>{e(t)})}),{get readyState(){return t.readyState},send(s){if(t.readyState!==e.SOCKET_READY_STATE.OPEN)throw e.createPlatformError("Socket is not open.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{readyState:t.readyState}});return t.send(s),Promise.resolve()},close(e,s){t.close(e,s)},onOpen:e=>(s.add(e),()=>{s.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(n.add(e),()=>{n.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}},es=t=>{const s=t?.webSocketCtor;if(void 0!==s)return{connect:t=>new Promise((r,n)=>{let o;try{o=new s(t.url,t.protocols);try{o.binaryType="arraybuffer"}catch{}}catch(h){return void n(e.createPlatformError("Socket creation failed.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{cause:h instanceof Error?h.message:String(h)}}))}let i,a=()=>{},c=()=>{},d=!1;const l=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},u=()=>{d||(d=!0,a(),c(),l(),o.close(),n(e.createPlatformError("Socket connection timed out.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{url:t.url,reason:"timeout"}})))};a=Jt(o,"open",()=>{d||(d=!0,a(),c(),l(),r(Zt(o)))}),c=Jt(o,"error",t=>{if(d)return;d=!0,a(),c(),l();const s=t&&"object"==typeof t&&"type"in t?String(t.type):void 0;n(e.createPlatformError("Socket connection failed before open.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{eventType:s}}))}),"number"==typeof t.timeoutMs&&t.timeoutMs>0&&(i=setTimeout(u,t.timeoutMs))})}},ts=(t,s)=>{throw e.createPlatformError("Upload adapter execution failed.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:"abort"!==t,details:{reason:t,url:s.url}})},ss=t=>{const s=new FormData;return Object.entries(t.fields??{}).forEach(([e,t])=>{s.append(e,t)}),((t,s)=>{if("web-file"!==s.source.sourceType)throw e.createPlatformError("Web upload adapter only supports web-file source.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:s.source.sourceType}});const r=s.source.file;if(!r)throw e.createPlatformError("Upload source file is required for web-file uploads.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:s.source.sourceType}});const n="undefined"!=typeof Blob&&r instanceof Blob,o=s.source.name??"upload.bin",i=s.fileFieldName??"file";n?t.append(i,r,o):t.append(i,r)})(s,t),s},rs=(t,s,r)=>new Promise((n,o)=>{const i=t(),a=r.timeoutMs??s?.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,r),i.addEventListener("abort",()=>{try{ts("abort",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{ts("timeout",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{ts("network",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{n({status:i.status,body:i.responseText})});try{const e=ss(r);i.timeout=a,i.open(r.method??"POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,s])=>{e.setRequestHeader(t,s)})})(i,r.headers),i.send(e)}catch(c){o(e.createPlatformError("Upload adapter execution failed.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:c instanceof Error?c.message:String(c)}}))}}),ns=(e,t)=>e?"timeout":"abort",os=t=>{const s=Boolean(t&&"xhrFactory"in t)?t?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,r=t?.fetchImpl;if("function"==typeof s||"function"==typeof r)return{upload(n){if("function"==typeof s)return rs(s,t,n);if("function"==typeof r)return(async(t,s,r)=>{const n=r.timeoutMs??s?.timeoutMs??3e4;let o=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,a=i&&Number.isFinite(n)?setTimeout(()=>{o=!0,i.abort()},n):void 0,c=((e,t)=>e??t?.signal)(r.signal,i);try{const e=ss(r),s=await t(r.url,{method:r.method??"POST",headers:r.headers,body:e,signal:c}),n=await s.text(),o=r.source.size;return"number"==typeof o&&r.onProgress?.({loaded:o,total:o,percent:o>0?100:void 0}),{status:s.status,body:n}}catch(d){const t=d instanceof Error&&"AbortError"===d.name;throw e.createPlatformError("Upload adapter execution failed.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!t,details:{reason:t?ns(o):"network",url:r.url,cause:d instanceof Error?d.message:String(d)}})}finally{a&&clearTimeout(a)}})(r,t,n);throw e.createPlatformError("Upload adapter execution failed.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{reason:"missing-upload-runtime",url:n.url}})}}},is=(t,s)=>{const r=new t;return Object.entries(s.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append(s.fileFieldName??"file",(t=>{const s=t.source;if("rn-uri"!==s.sourceType||!s.uri)throw e.createPlatformError("React Native upload adapter only supports rn-uri source.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:s.sourceType}});return{uri:s.uri,name:s.name??"upload.bin",type:s.mimeType??"application/octet-stream"}})(s)),r},as=t=>{const s=t?.fetchImpl,r=t?.formDataCtor;if("function"==typeof s&&"function"==typeof r)return{async upload(n){const o=n.timeoutMs??t?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let a=!1;const c=i&&Number.isFinite(o)?setTimeout(()=>{a=!0,i.abort()},o):void 0;try{const e=is(r,n),t=await s(n.url,{method:n.method??"POST",headers:n.headers,body:e,signal:n.signal??i?.signal}),o=await t.text(),a=n.source.size;return"number"==typeof a&&n.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:t.status,body:o}}catch(d){if((t=>{if("object"!=typeof t||null===t)return!1;const s=t;return s.code===e.PLATFORM_ERROR_CODE.UPLOAD_FAILED&&s.stage===e.PLATFORM_ERROR_STAGE.UPLOAD})(d))throw d;const t=d instanceof Error&&"AbortError"===d.name;throw e.createPlatformError("React Native upload adapter execution failed.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!t||a,details:{url:n.url,reason:t?a?"timeout":"abort":"network",cause:d instanceof Error?d.message:String(d)}})}finally{void 0!==c&&clearTimeout(c)}}}},cs=(e,t)=>e+t&4294967295,ds=(e,t,s,r,n,o)=>{return cs((i=cs(cs(t,e),cs(r,o)))<<(a=n)|i>>>32-a,s);var i,a},ls=(e,t,s,r,n,o,i)=>ds(t&s|~t&r,e,t,n,o,i),us=(e,t,s,r,n,o,i)=>ds(t&r|s&~r,e,t,n,o,i),hs=(e,t,s,r,n,o,i)=>ds(t^s^r,e,t,n,o,i),ps=(e,t,s,r,n,o,i)=>ds(s^(t|~r),e,t,n,o,i),ms=(e,t)=>{let[s,r,n,o]=e;s=ls(s,r,n,o,t[0]??0,7,-680876936),o=ls(o,s,r,n,t[1]??0,12,-389564586),n=ls(n,o,s,r,t[2]??0,17,606105819),r=ls(r,n,o,s,t[3]??0,22,-1044525330),s=ls(s,r,n,o,t[4]??0,7,-176418897),o=ls(o,s,r,n,t[5]??0,12,1200080426),n=ls(n,o,s,r,t[6]??0,17,-1473231341),r=ls(r,n,o,s,t[7]??0,22,-45705983),s=ls(s,r,n,o,t[8]??0,7,1770035416),o=ls(o,s,r,n,t[9]??0,12,-1958414417),n=ls(n,o,s,r,t[10]??0,17,-42063),r=ls(r,n,o,s,t[11]??0,22,-1990404162),s=ls(s,r,n,o,t[12]??0,7,1804603682),o=ls(o,s,r,n,t[13]??0,12,-40341101),n=ls(n,o,s,r,t[14]??0,17,-1502002290),r=ls(r,n,o,s,t[15]??0,22,1236535329),s=us(s,r,n,o,t[1]??0,5,-165796510),o=us(o,s,r,n,t[6]??0,9,-1069501632),n=us(n,o,s,r,t[11]??0,14,643717713),r=us(r,n,o,s,t[0]??0,20,-373897302),s=us(s,r,n,o,t[5]??0,5,-701558691),o=us(o,s,r,n,t[10]??0,9,38016083),n=us(n,o,s,r,t[15]??0,14,-660478335),r=us(r,n,o,s,t[4]??0,20,-405537848),s=us(s,r,n,o,t[9]??0,5,568446438),o=us(o,s,r,n,t[14]??0,9,-1019803690),n=us(n,o,s,r,t[3]??0,14,-187363961),r=us(r,n,o,s,t[8]??0,20,1163531501),s=us(s,r,n,o,t[13]??0,5,-1444681467),o=us(o,s,r,n,t[2]??0,9,-51403784),n=us(n,o,s,r,t[7]??0,14,1735328473),r=us(r,n,o,s,t[12]??0,20,-1926607734),s=hs(s,r,n,o,t[5]??0,4,-378558),o=hs(o,s,r,n,t[8]??0,11,-2022574463),n=hs(n,o,s,r,t[11]??0,16,1839030562),r=hs(r,n,o,s,t[14]??0,23,-35309556),s=hs(s,r,n,o,t[1]??0,4,-1530992060),o=hs(o,s,r,n,t[4]??0,11,1272893353),n=hs(n,o,s,r,t[7]??0,16,-155497632),r=hs(r,n,o,s,t[10]??0,23,-1094730640),s=hs(s,r,n,o,t[13]??0,4,681279174),o=hs(o,s,r,n,t[0]??0,11,-358537222),n=hs(n,o,s,r,t[3]??0,16,-722521979),r=hs(r,n,o,s,t[6]??0,23,76029189),s=hs(s,r,n,o,t[9]??0,4,-640364487),o=hs(o,s,r,n,t[12]??0,11,-421815835),n=hs(n,o,s,r,t[15]??0,16,530742520),r=hs(r,n,o,s,t[2]??0,23,-995338651),s=ps(s,r,n,o,t[0]??0,6,-198630844),o=ps(o,s,r,n,t[7]??0,10,1126891415),n=ps(n,o,s,r,t[14]??0,15,-1416354905),r=ps(r,n,o,s,t[5]??0,21,-57434055),s=ps(s,r,n,o,t[12]??0,6,1700485571),o=ps(o,s,r,n,t[3]??0,10,-1894986606),n=ps(n,o,s,r,t[10]??0,15,-1051523),r=ps(r,n,o,s,t[1]??0,21,-2054922799),s=ps(s,r,n,o,t[8]??0,6,1873313359),o=ps(o,s,r,n,t[15]??0,10,-30611744),n=ps(n,o,s,r,t[6]??0,15,-1560198380),r=ps(r,n,o,s,t[13]??0,21,1309151649),s=ps(s,r,n,o,t[4]??0,6,-145523070),o=ps(o,s,r,n,t[11]??0,10,-1120210379),n=ps(n,o,s,r,t[2]??0,15,718787259),r=ps(r,n,o,s,t[9]??0,21,-343485551),e[0]=cs(s,e[0]),e[1]=cs(r,e[1]),e[2]=cs(n,e[2]),e[3]=cs(o,e[3])},gs=(e,t)=>{const s=new Array(16).fill(0);for(let r=0;r<16;r+=1){const n=t+4*r;s[r]=(e[n]??0)|(e[n+1]??0)<<8|(e[n+2]??0)<<16|(e[n+3]??0)<<24}return s},fs=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},ys=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)ms(t,gs(e,s));const r=new Array(16).fill(0);let n=0;for(;s<e.length;s+=1){const t=n>>2;r[t]=(r[t]??0)|(e[s]??0)<<n%4*8,n+=1}const o=n>>2;r[o]=(r[o]??0)|128<<n%4*8,n>55&&(ms(t,r),r.fill(0));const i=8*e.length;return r[14]=4294967295&i,r[15]=Math.floor(i/4294967296),ms(t,r),t.map(fs).join("")},Es=async t=>{if("function"==typeof createImageBitmap){const e=await createImageBitmap(t);return{image:e,width:e.width,height:e.height,cleanup:()=>{e.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw e.createPlatformError("Image decode capability is missing for current platform",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"image decode unavailable"}});const s=URL.createObjectURL(t);return new Promise((t,r)=>{const n=new Image;n.onload=()=>{t({image:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,cleanup:()=>{URL.revokeObjectURL(s)}})},n.onerror=()=>{URL.revokeObjectURL(s),r(e.createPlatformError("Image decode failed",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"image load error"}}))},n.src=s})},Rs=t=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(t))throw e.createPlatformError("Web image processor only supports web file source",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{sourceType:t.sourceType}});return t.file},Is=()=>({async getImageInfo(e){const t=Rs(e),s=await Es(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(t,s){const r=Rs(t),n=await Es(r);try{const r=((e,t,s)=>{const r=Math.min(e,t);if(r<=s)return{width:e,height:t};const n=s/r;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(n.width,n.height,s.maxShortEdge),i=((t,s)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(t,s);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=t,e.height=s,e}throw e.createPlatformError("Canvas capability is missing for current platform",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),a=i.getContext("2d");if(!a)throw e.createPlatformError("Canvas 2d context is missing",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1});a.drawImage(n.image,0,0,r.width,r.height);const c="image/png"===(o=t.mimeType)||"image/webp"===o?o:"image/jpeg",d=await(async(t,s,r)=>{if("convertToBlob"in t&&"function"==typeof t.convertToBlob)return t.convertToBlob({type:s,quality:r});if("toBlob"in t&&"function"==typeof t.toBlob)return new Promise((n,o)=>{t.toBlob(t=>{t?n(t):o(e.createPlatformError("Image encode failed",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},s,r)});throw e.createPlatformError("Canvas encode capability is missing for current platform",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,c,s.quality),l=(e=>e.name??"image")(t),u="undefined"!=typeof File?new File([d],l,{type:c,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??d,name:l,mimeType:c,size:u?.size??d.size},width:r.width,height:r.height,fileName:l,fileType:c,fileSize:u?.size??d.size,webFile:u}}finally{n.cleanup()}var o},async computeMd5(t){const s=Rs(t),r=await(async t=>{if("function"==typeof t.arrayBuffer)return t.arrayBuffer();if("undefined"==typeof FileReader)throw e.createPlatformError("Binary read capability is missing for current platform",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((s,r)=>{const n=new FileReader;n.onerror=()=>{r(e.createPlatformError("Binary read failed",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1}))},n.onload=()=>{n.result instanceof ArrayBuffer?s(n.result):r(e.createPlatformError("Binary read returned invalid result",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1}))},n.readAsArrayBuffer(t)})})(s);return ys(new Uint8Array(r))}}),vs=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)},Cs=t=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(t))throw e.createPlatformError("Miniapp image processor only supports miniapp path source",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{sourceType:t.sourceType}});return t.path},Ss=t=>{const s=t.getFileSystemManager?.();if(s)return s;throw e.createPlatformError("Miniapp file system capability is missing",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{capability:"getFileSystemManager"}})},Ts=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},As=async(t,s)=>new Promise((e,r)=>{t.getImageInfo({src:s,success:t=>{e(t)},fail:e=>{r(e instanceof Error?e:new Error(vs(e)))}})}).catch(t=>{throw e.createPlatformError("Miniapp image info read failed",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{src:s,cause:vs(t)}})}),Os=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,bs=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await As(e,t);return Os(t,s)},_s=t=>({async getImageInfo(e){const s=Cs(e),r=await As(t,s),n=Ts(r.type)??e.mimeType;return{width:r.width,height:r.height,mimeType:n,fileSize:e.size,isGif:"image/gif"===n}},async generateBigImage(s,r){const n=Cs(s);if("function"!=typeof t.compressImage)throw e.createPlatformError("Miniapp image compress capability is missing",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{capability:"compressImage"}});const o=await As(t,n),i=Os(n,o),a=((e,t,s)=>{const r=Math.min(e,t);if(r<=s)return{width:e,height:t};const n=s/r;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(o.width,o.height,r.maxShortEdge),c=await new Promise((e,s)=>{t.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:a.width,compressedHeight:a.height,success:t=>{t.tempFilePath?e(t.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(vs(e)))}})}).catch(t=>{throw e.createPlatformError("Miniapp image compress failed",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{src:i,cause:vs(t)}})}),d=await bs(t,c),l=await As(t,d),u=Ts(l.type)??s.mimeType,h=await(async(t,s,r)=>{const n=Ss(t);return n.getFileInfo?new Promise((e,t)=>{n.getFileInfo?.({filePath:s,success:t=>{e(t.size)},fail:e=>{t(e instanceof Error?e:new Error(vs(e)))}})}).catch(t=>{throw e.createPlatformError("Miniapp file info read failed",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{filePath:s,cause:vs(t)}})}):r})(t,d,s.size);return{source:{sourceType:"miniapp-path",path:d,name:s.name,mimeType:u,size:h},width:l.width,height:l.height,fileName:s.name,fileType:u,fileSize:h}},async computeMd5(s){const r=Cs(s),n=await bs(t,r),o=await(async(t,s)=>{const r=Ss(t),n=await new Promise((e,t)=>{r.readFile({filePath:s,success:t=>{e(t.data)},fail:e=>{t(e instanceof Error?e:new Error(vs(e)))}})}).catch(t=>{throw e.createPlatformError("Miniapp file read failed",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{filePath:s,cause:vs(t)}})});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)))})(t,n);return ys(o)}}),Ms=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),Ns=[/\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],Ds=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},ws=e=>{if(!e)return!1;const t=Ds(e,"name");if(t&&Ms.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Ds(e,"message"),Ds(e,"errMsg")].some(e=>null!==e&&Ns.some(t=>t.test(e)))},Ls=e=>{if(e instanceof Error)return e;const t=Ds(e,"message")??Ds(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Us="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ps=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),ks=t=>t===e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||t===e.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,xs=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),s=t.endsWith("==")?2:t.endsWith("=")?1:0,r=Math.max(0,Math.floor(3*t.length/4)-s),n=new Uint8Array(r);let o=0;for(let i=0;i<t.length;i+=4){const e=Us.indexOf(t[i]??""),s=Us.indexOf(t[i+1]??""),a=t[i+2]??"=",c=t[i+3]??"=",d="="===a?0:Us.indexOf(a),l="="===c?0:Us.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])o<r&&(n[o]=u>>t&255,o+=1)}return n.buffer},Fs=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Bs=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Gs=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Fs(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?Gs(s.data,t+1):e},qs=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Bs(e);if(Fs(e))try{return Bs(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Bs(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=qs(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=qs(s.buffer,t+1);if(!e)return;const r="number"==typeof s.byteOffset&&Number.isInteger(s.byteOffset)?s.byteOffset:0,n="number"==typeof s.byteLength&&Number.isInteger(s.byteLength)?s.byteLength:e.byteLength-r;if(r<0||n<0||r+n>e.byteLength)return;return e.slice(r,r+n)}},Ks=(t,s)=>{if("string"==typeof t)return t;const r=t instanceof Uint8Array?t:new Uint8Array(t);if(ks(s)){const n=(e=>{let t="";for(let s=0;s<e.length;s+=3){const r=e[s]??0,n=e[s+1],o=e[s+2],i=r<<16|(n??0)<<8|(o??0);t+=Us[i>>18&63],t+=Us[i>>12&63],t+=void 0===n?"=":Us[i>>6&63],t+=void 0===o?"=":Us[63&i]}return t})(r);return e.logger.warn("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:s,sourceType:t instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:r.byteLength,encodedCharacters:n.length,sourcePrefixHex:Ps(r.subarray(0,8))}),n}const n=new ArrayBuffer(r.byteLength);return new Uint8Array(n).set(r),n},Vs=(e,t)=>"string"!=typeof e&&ks(t),zs=(t,s)=>{const r=Gs(t.data);if("string"==typeof r){if(!ks(s))return r;const n=xs(r),o=new Uint8Array(n);return e.logger.warn("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:s,sourceType:r===t.data?"string":"wrapped-string",sourceCharacters:r.length,decodedBytes:n.byteLength,decodedPrefixHex:Ps(o.subarray(0,8)),decodedSuffixHex:Ps(o.subarray(Math.max(0,o.length-8)))}),n}const n=qs(r);if(!n){const n="object"==typeof t.data&&null!==t.data?t.data:void 0;return void e.logger.warn("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:s,sourceType:typeof r,sourceTag:Object.prototype.toString.call(t.data),sourceKeys:n?Object.keys(n).slice(0,10):[],isBuffer:t.isBuffer})}if(!ks(s))return n.buffer;const o=(e=>{let t="";for(const r of e){if(9!==r&&10!==r&&13!==r&&32!==r&&!(r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||43===r||45===r||47===r||61===r||95===r))return;t+=String.fromCharCode(r)}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(!o)return e.logger.warn("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:s,sourceType:Object.prototype.toString.call(r),sourceBytes:n.byteLength,sourcePrefixHex:Ps(n.subarray(0,8))}),n.buffer;const i=xs(o),a=new Uint8Array(i);return e.logger.warn("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:s,sourceType:Object.prototype.toString.call(r),sourceBytes:n.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:Ps(a.subarray(0,8)),decodedSuffixHex:Ps(a.subarray(Math.max(0,a.length-8)))}),i},Hs=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),js=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],Ws=e=>e instanceof Error?e.message:Hs(e)&&"string"==typeof e.errMsg?e.errMsg:Hs(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),Qs=e=>e?{...e}:{},$s=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,Ys=e=>$s(e.statusCode)?e.statusCode:$s(e.status)?e.status:void 0,Js=e=>{if(!Hs(e))return{};const t={};return Object.entries(e).forEach(([e,s])=>{"string"==typeof s&&(t[e]=s)}),t},Xs=e=>({...Js(e.headers),...Js(e.header)}),Zs=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},er=e=>{try{e.close()}catch{}},tr=(t,s)=>new Promise((r,n)=>{let o=!1,i=()=>{};const a=(t,r,a)=>{o||(o=!0,i(),n(e.createPlatformError(t,{code:e.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:e.PLATFORM_ERROR_STAGE.REQUEST,retryable:a,details:{url:s.url,method:"GET",cause:Ws(r)}})))},c=t.downloadFile?.({url:s.url,header:Qs(s.headers),timeout:s.timeoutMs??15e3,success:n=>{const c=n.tempFilePath??n.apFilePath;c?((e,t)=>new Promise((s,r)=>{const n=e.getFileSystemManager?.();n?n.readFile({filePath:t,success:e=>{const t=qs(e.data);t?s(t.buffer):r(new Error("downloaded file response is not binary"))},fail:r}):r(new Error("getFileSystemManager returned no file system manager"))}))(t,c).then(t=>{o||(o=!0,i(),e.logger.warn("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:s.url,filePathType:n.apFilePath?"apFilePath":"tempFilePath",status:n.statusCode??200,bytes:t.byteLength}),r({status:n.statusCode??200,headers:n.header??{},data:t}))}).catch(e=>{a("Mini program downloaded file read failed.",e,!1)}):a("Mini program download did not return a file path.",n,!1)},fail:e=>{a("Mini program file download failed.",e,!0)}});i=Zs(s.signal,()=>{c?.abort(),a("Mini program file download aborted.","abort",!1)})}),sr=t=>({request:s=>"arraybuffer"!==s.responseType||void 0!==s.method&&"GET"!==s.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(t)?new Promise((r,n)=>{let o=()=>{};const i=t.request({url:s.url,method:s.method??"GET",header:Qs(s.headers),data:s.body,timeout:s.timeoutMs??15e3,responseType:"arraybuffer"===s.responseType?"arraybuffer":"text",success:t=>{o();const i=Ys(t);void 0!==i?r({status:i,headers:Xs(t),data:t.data}):n(e.createPlatformError("Mini program request response status is invalid.",{code:e.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:e.PLATFORM_ERROR_STAGE.REQUEST,retryable:!1,details:{url:s.url,method:s.method??"GET",statusCode:t.statusCode,status:t.status}}))},fail:t=>{o(),n(e.createPlatformError("Mini program request failed.",{code:e.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:e.PLATFORM_ERROR_STAGE.REQUEST,retryable:!0,details:{url:s.url,method:s.method??"GET",cause:Ws(t)}}))}});o=Zs(s.signal,()=>{i.abort(),n(e.createPlatformError("Mini program request aborted.",{code:e.PLATFORM_ERROR_CODE.REQUEST_FAILED,stage:e.PLATFORM_ERROR_STAGE.REQUEST,retryable:!1,details:{url:s.url,method:s.method??"GET",reason:"abort"}}))})}):tr(t,s)}),rr=(t,s)=>({connect:r=>new Promise((n,o)=>{let i,a,c=!1;const d=()=>{void 0!==a&&(clearTimeout(a),a=void 0)},l=(t,s,n)=>{c||(c=!0,d(),i&&er(i),o(e.createPlatformError(s,{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:n,details:{url:r.url,cause:Ws(t)}})))},u=t=>{if(!(js(r=t,"send")&&js(r,"close")&&js(r,"onOpen")&&js(r,"onMessage")&&js(r,"onError")&&js(r,"onClose")))return void l(new Error("returnedType="+typeof t),"Mini program connectSocket did not return a SocketTask.",!1);var r;const o=t;if(c)return void er(o);i=o;const a=()=>{o.offOpen?.(u),o.offError?.(h)},u=()=>{c?er(o):(c=!0,d(),a(),n(((t,s,r=e.SOCKET_READY_STATE.CONNECTING)=>{const n=new Set,o=new Set,i=new Set,a=new Set;let c=r;return t.onOpen(()=>{c=e.SOCKET_READY_STATE.OPEN,n.forEach(e=>{e()})}),t.onMessage(e=>{const t=zs(e,s);void 0!==t&&o.forEach(e=>{e(t)})}),t.onError(e=>{i.forEach(t=>{t(e)})}),t.onClose(t=>{c=e.SOCKET_READY_STATE.CLOSED,a.forEach(e=>{e({code:t.code,reason:t.reason})})}),{get readyState(){return c},send(r){if(c!==e.SOCKET_READY_STATE.OPEN)throw e.createPlatformError("Mini program socket is not open.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{readyState:c}});return new Promise((n,o)=>{t.send({data:Ks(r,s),...Vs(r,s)?{isBuffer:!0}:{},success:n,fail:t=>{o(e.createPlatformError("Mini program socket send failed.",{code:e.PLATFORM_ERROR_CODE.SOCKET_FAILED,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!0,details:{cause:Ws(t)}}))}})})},close(s,r){c=e.SOCKET_READY_STATE.CLOSING,t.close({code:s,reason:r})},onOpen:e=>(n.add(e),()=>{n.delete(e)}),onMessage:e=>(o.add(e),()=>{o.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(a.add(e),()=>{a.delete(e)})}})(o,s,e.SOCKET_READY_STATE.OPEN)))},h=e=>{a(),l(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};o.onOpen(u),o.onError(h)};let h;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(a=setTimeout(()=>{l("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{h=t.connectSocket({url:r.url,...s===e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(r.protocols)?[...r.protocols]:"string"==typeof r.protocols?[r.protocols]:void 0,fail:e=>{l(e,"Mini program socket connect failed.",!0)}})}catch(m){return void l(m,"Mini program socket creation failed.",!0)}var p;"object"!=typeof(p=h)||null===p||"function"!=typeof p.then?u(h):Promise.resolve(h).then(e=>u(e),e=>l(e,"Mini program socket connect failed.",!0))})}),nr=t=>({upload(s){const r=s.method??"POST";return"POST"!==r?Promise.reject(e.createPlatformError("Mini program upload only supports POST.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{url:s.url,method:r,reason:"unsupported-method"}})):new Promise((r,n)=>{const o=(t=>{if("miniapp-path"!==t.sourceType||!t.path)throw e.createPlatformError("Mini program upload only supports miniapp-path source.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{sourceType:t.sourceType}});return t})(s.source);let i=()=>{};const a=t.uploadFile({url:s.url,filePath:o.path,name:s.fileFieldName??"file",header:Qs(s.headers),formData:s.fields,timeout:s.timeoutMs??3e4,success:t=>{i();const a=Ys(t);void 0!==a?r({status:a,body:t.data}):n(e.createPlatformError("Mini program upload response status is invalid.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{url:s.url,path:o.path,statusCode:t.statusCode,status:t.status}}))},fail:t=>{i(),n(e.createPlatformError("Mini program upload failed.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!0,details:{url:s.url,path:o.path,cause:Ws(t)}}))}});a.onProgressUpdate?.(e=>{s.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=Zs(s.signal,()=>{a.abort(),n(e.createPlatformError("Mini program upload aborted.",{code:e.PLATFORM_ERROR_CODE.UPLOAD_FAILED,stage:e.PLATFORM_ERROR_STAGE.UPLOAD,retryable:!1,details:{url:s.url,path:o.path,reason:"abort"}}))})})}}),or=(t,s)=>{const r=(t=>t===e.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||t===e.RUNTIME_PLATFORMS.DINGTALK_MINIAPP)(s);return{async getItem(e){if(js(t,"getStorageSync"))try{const s=(e=>Hs(e)&&"data"in e?e.data:e)(t.getStorageSync(r?{key:e}:e));return"string"==typeof s&&s.length>0?s:null}catch{return null}return js(t,"getStorage")?new Promise(s=>{t.getStorage({key:e,success:e=>{s("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{s(null)}})}):null},async setItem(e,s){if(js(t,"setStorageSync"))try{r?t.setStorageSync({key:e,data:s}):t.setStorageSync(e,s)}catch(n){if(ws(n))throw Ls(n)}else if(js(t,"setStorage"))return new Promise((r,o)=>{try{t.setStorage({key:e,data:s,success:r,fail:e=>{ws(e)?o(Ls(e)):r()}})}catch(n){if(ws(n))return void o(Ls(n));r()}})},async removeItem(e){if(js(t,"removeStorageSync"))try{t.removeStorageSync(r?{key:e}:e)}catch{}else if(js(t,"removeStorage"))return new Promise(s=>{try{t.removeStorage({key:e,success:s,fail:()=>{s()}})}catch{s()}})}}},ir=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>js(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 js(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),js(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{js(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},r=()=>{t(!1)};return js(e,"onAppShow")&&e.onAppShow(s),js(e,"onAppHide")&&e.onAppHide(r),t(!0),()=>{js(e,"offAppShow")&&e.offAppShow(s),js(e,"offAppHide")&&e.offAppHide(r)}}}),ar=(t,s=e.RUNTIME_PLATFORMS.WECHAT_MINIAPP,r=s)=>{const n=(t=>{if(js(t,"request")&&js(t,"connectSocket")&&js(t,"uploadFile"))return t;throw e.createPlatformError("Mini program platform capability is missing.",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(t),o="function"==typeof n.getImageInfo?_s(n):void 0;return{request:sr(n),socket:rr(n,r),upload:nr(n),runtime:ir(n,s),storage:or(n,r),imageProcessor:o}},cr=["request","upload","socket"],dr={request:"request",upload:"upload",socket:"connect"},lr=[e.RUNTIME_PLATFORMS.WEB,e.RUNTIME_PLATFORMS.ELECTRON_RENDERER,e.RUNTIME_PLATFORMS.REACT_NATIVE],ur=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},hr=e=>lr.includes(e),pr=(t,s)=>t!==e.RUNTIME_PLATFORMS.UNIAPP?hr(t):!At(s)&&!gr(s)&&vt(s),mr=e=>ur(e,"getImageInfo")&&ur(e,"getFileSystemManager"),gr=e=>!At(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),fr=(t,s)=>{if(hr(t)&&t!==e.RUNTIME_PLATFORMS.REACT_NATIVE)return Is();if(Mt(t)&&mr(s))return _s(s);if(t===e.RUNTIME_PLATFORMS.UNIAPP&&"object"==typeof s&&null!==s){const e=s;if(vt(e))return Is();if(mr(e.uni))return _s(e.uni);if(mr(e.wx))return _s(e.wx)}},yr=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=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())}},Er=(t,s,r,n)=>{if(t===e.RUNTIME_PLATFORMS.UNIAPP&&gr(r)&&void 0!==r.uni&&ft(r.uni))return{...ar(r.uni,t,s),proto:Wt()};if(((e,t)=>!pr(e,t)&&Mt(e))(t,r)&&ft(n))return{...ar(n,t,s),proto:Wt()};const o=r.XMLHttpRequest,i=pr(t,r),a=i?e.createWebRequestAdapter({fetchImpl:r.fetch}):void 0,c=i?es({webSocketCtor:r.WebSocket}):void 0,d=t===e.RUNTIME_PLATFORMS.REACT_NATIVE?as({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?os({xhrFactory:"function"==typeof o?()=>new o:void 0,fetchImpl:r.fetch}):void 0,l=i&&t!==e.RUNTIME_PLATFORMS.REACT_NATIVE?(u={platform:t,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const s=()=>{e(!0)},r=()=>{e(!1)};return t.addEventListener("online",s),t.addEventListener("offline",r),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",s),t.removeEventListener("offline",r)}},onAppVisibilityChange(e){const t=u.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=>()=>{}}))(t);var u;return{request:a,upload:d,socket:c,runtime:l,proto:Wt(),storage:yr(r),imageProcessor:i&&t!==e.RUNTIME_PLATFORMS.REACT_NATIVE?Is():fr(t,n)}},Rr=(t,s,r)=>{if(!s)return{...t,...r};const n=cr.filter(e=>void 0!==r[e]);if(n.length>0)throw e.createPlatformError("Transport adapter conflicts with network overrides.",{code:e.PLATFORM_ERROR_CODE.INIT_FAILED,stage:e.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{conflictingCapabilities:n}});const o=(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(r);return{...t,request:s.request,upload:s.upload,socket:s.socket,...o}},Ir=(t,s)=>{if(void 0!==t)return t;throw e.createPlatformError("Platform adapter initialization failed.",{code:e.PLATFORM_ERROR_CODE.INIT_FAILED,stage:e.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{capability:s}})},vr=t=>{(t=>{if(!t)return;const s=cr.flatMap(e=>{const s=dr[e];return ur(t[e],s)?[]:[`${e}.${s}`]});if(0!==s.length)throw e.createPlatformError("Transport adapter has invalid capabilities.",{code:e.PLATFORM_ERROR_CODE.INIT_FAILED,stage:e.PLATFORM_ERROR_STAGE.INIT,retryable:!1,details:{source:"transportAdapter",invalidCapabilities:s}})})(t?.transportAdapter);const s=e.getRuntimeGlobal(t?.runtimeInput),r=_t(s,t?.prefer),n=r.platform,o=Er(n,r.hostPlatform,s,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(t?.overrides,o),a=Rr(o,t?.transportAdapter,i),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);Dt(c);return{platform:n,platformId:n,capability:c,request:Ir(a.request,"request"),upload:Ir(a.upload,"upload"),socket:Ir(a.socket,"socket"),runtime:Ir(a.runtime,"runtime"),proto:Ir(a.proto,"proto"),storage:Ir(a.storage,"storage"),imageProcessor:a.imageProcessor}},Cr=t=>{if(t)return t;const s=e.getRuntimeGlobal(),r=es({webSocketCtor:s.WebSocket});if(r)return r;throw e.createPlatformError("Socket capability is missing for current platform.",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.SOCKET,retryable:!1,details:{capability:"socket"}})},Sr={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Tr{constructor(e={}){this.attemptCount=0,this.config={...Sr,...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 t=this.getRetryDelay();return e.logger.debug(`Waiting ${t}ms before retry (attempt ${this.attemptCount})`),new Promise(e=>setTimeout(e,t))}}const Ar={interval:3e4,timeout:6e4},Or="function"==typeof TextDecoder?new TextDecoder:null;class br{constructor(t={}){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=t=>{const s=this.extractMessageText(t);if(!s)return;const r=this.parseJson(s);if(!br.isRecord(r))return;"pong"===br.readString(r.type)&&(this.markAlive(),e.logger.debug("Pong received"))},this.config={...Ar,...t}}start(t,s,r){this.heartbeatTimer&&this.stop(),this.attachWebSocket(t),this.onTimeoutCallback=s||null,this.sendPing=r??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),e.logger.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),e.logger.debug("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===e.SOCKET_READY_STATE.OPEN)try{if(this.sendPing)this.sendPing();else{const t=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(t)).catch(t=>{e.logger.error("Failed to send ping:",t),this.resolveProbe(!1)})}this.resetTimeout(),e.logger.debug("Ping sent")}catch(t){e.logger.error("Failed to send ping:",t),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)?Or?.decode(t)??ht(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(()=>{e.logger.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(t,s){try{if(t.readyState!==e.SOCKET_READY_STATE.OPEN)return!1;this.attachWebSocket(t);const r=s??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},r);this.probeResolvers.push(s=>{clearTimeout(t),e(s)}),this.sendPingInternal()})}catch(r){return e.logger.warn("Heartbeat probe failed",r),!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 _r=null;function Mr(){return _r||(_r=jt()),_r}const Nr="websdk2:device-info",Dr="webim",wr="web",Lr=t=>{const s=Date.now(),r=t.deviceId,n=t.customOSPlatform,o=void 0!==n?t.customDeviceName:void 0,i=e.getRuntimeGlobal().localStorage,a=()=>{if(!i)return null;try{const t=i.getItem(Nr);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(i)try{i.setItem(Nr,JSON.stringify(e))}catch{}},d=e=>void 0===n?e:{deviceId:`custom${n}_${e.deviceUuid}`,deviceName:o??r,deviceUuid:e.deviceUuid};if(t.useFixedDeviceId){const e=a();if(e)return d(e);if(r===Dr){const e=`${wr}_${s}`,t=d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return c(t),t}if(void 0!==n){const e=d({deviceId:`webim_${wr}_${r}`,deviceName:r,deviceUuid:`${wr}_${s}`});return c(e),e}const t={deviceId:`webim_${wr}_${r}`,deviceName:`webim_${wr}_${r}`,deviceUuid:`webim_${wr}_${r}`};return c(t),t}if(r===Dr){const e=`random_${wr}_${s}`;return d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==n){return d({deviceId:`webim_${wr}_${r}`,deviceName:r,deviceUuid:`random_${wr}_${s}`})}return{deviceId:`webim_${wr}_${r}`,deviceName:`webim_${wr}_${r}`,deviceUuid:`webim_${wr}_${r}`}},Ur=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Pr=e=>{if(/^\d+$/.test(e))return e;const t=s.Long.fromString("1099511628211",!0);let r=s.Long.fromString("1469598103934665603",!0);for(let n=0;n<e.length;n+=1)r=r.xor(s.Long.fromInt(e.charCodeAt(n),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()},kr=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 s.Long(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},xr=e=>{const t=[];for(const[s,r]of Object.entries(e))if(void 0!==r)if("boolean"!=typeof r)if("number"!=typeof r)if("string"!=typeof r)try{t.push({key:s,type:$e,stringValue:JSON.stringify(r)})}catch{t.push({key:s,type:Qe,stringValue:Object.prototype.toString.call(r)})}else t.push({key:s,type:Qe,stringValue:r});else Number.isInteger(r)?t.push({key:s,type:Ve,varintValue:r}):t.push({key:s,type:We,doubleValue:r});else t.push({key:s,type:Ke,varintValue:r?1:0});return t},Fr=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 r="number"==typeof s.type?s.type:Qe;if(r!==Ke)if(r!==Ve&&r!==ze&&r!==He)if(r!==je)if(r!==We){if(r!==$e)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},Br=new Set(["mute"]),Gr={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},qr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Kr=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Vr=(e,t)=>{const s=e?.map(e=>qr(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},zr=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=Kr(t);if(!r)return;const n=r.muteExpire??r.mute_expire??r.expire??r.expired??r.expireAt??r.expiredAt,o=Number(n);return Number.isFinite(o)&&o>0?o:void 0},Hr=e=>{const t=Kr(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=Gr[r];if(!e)continue;let t=n;if(Br.has(r))t=!0===n||"true"===n;else if("max_users"===r){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},jr=e=>{const t=Kr(e);if(!t)return{attributes:{},keyList:[]};const s=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},r=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Array.isArray(s.successKeys)?s.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(n.map(e=>[e,r[e]]).filter(e=>"string"==typeof e[1])),keyList:n,from:qr(t.operator)??qr(t.username)}},Wr=(e,t)=>({eventName:e,payload:t}),Qr=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=qr(e.from?.name),r=(n=e.to,qr(n?.[0]?.name));var n;switch(e.operation){case 1:return Wr(E,t);case 10:return Wr(v,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:r??s});case 17:return Wr(R,{...t,memberIds:Vr(e.members,s),ext:e.ext??e.eventExt});case 18:return Wr(I,{...t,memberIds:Vr(e.members,s)});case 20:return Wr(M,{...t,oldOwnerId:s,newOwnerId:r});case 21:return Wr(b,{...t,adminId:r??s});case 22:return Wr(_,{...t,adminId:r??s});case 23:{const s=(e=>{const t=Kr(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const r={};for(const[n,o]of Object.entries(s)){const e=Number(o);n&&Number.isFinite(e)&&(r[n]=e)}return Object.keys(r).length>0?r:null})(e.ext??e.eventExt),n=s?Object.keys(s):Vr(e.members,r),o=46388736e5;return Wr(C,{...t,userIds:n,muteMembers:s??Object.fromEntries(n.map(e=>[e,o])),muteExpire:zr(e.reason,e.eventExt)??o})}case 24:return Wr(S,{...t,userIds:Vr(e.members,r)});case 25:return Wr(N,{...t,announcement:e.reason??""});case 26:return Wr(N,{...t,announcement:""});case 29:return Wr(T,{...t,userIds:Vr(e.members,r)});case 30:return Wr(A,{...t,userIds:Vr(e.members,r)});case 31:return Wr(O,{...t,isMuted:!0});case 32:return Wr(O,{...t,isMuted:!1});case 14:return Wr(D,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Hr(e.eventExt)});case 43:{const r=jr(e.eventExt);return Wr(w,{...t,attributes:r.attributes,from:r.from??s})}case 44:{const r=jr(e.eventExt);return Wr(L,{...t,keyList:r.keyList,from:r.from??s})}default:return null}},$r=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Yr={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Jr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Xr=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Zr=(e,t)=>{const s=e?.map(e=>Jr(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},en=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=Xr(t);if(!r)return;const n=r.muteExpire??r.mute_expire??r.expire??r.expired??r.expireAt??r.expiredAt,o=Number(n);return Number.isFinite(o)&&o>0?o:void 0},tn=e=>{const t=Xr(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=Yr[r];if(!e)continue;let t=n;if($r.has(r))t=!0===n||"true"===n;else if("max_users"===r){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(s[e]=t)}return Object.keys(s).length>0?s:void 0},sn=(e,t)=>{const s=Xr(t)??Xr(e);return o.normalizeGroupSharedFile(s??void 0)??void 0},rn=(e,t)=>{const s=Xr(t)??Xr(e);return Jr(s?.fileId)??Jr(s?.file_id)??Jr(e)??""},nn=(e,t)=>({eventName:e,payload:t}),on=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=Jr(e.from?.name),r=(o=e.to,Jr(o?.[0]?.name));var o;switch(e.operation){case 4:return nn(n.GroupEventName.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return nn(n.GroupEventName.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return nn(n.GroupEventName.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:r,reason:e.reason});case 7:return nn(n.GroupEventName.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return nn(n.GroupEventName.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return nn(n.GroupEventName.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return nn(n.GroupEventName.USER_REMOVED,t);case 1:return nn(n.GroupEventName.GROUP_DESTROYED,t);case 19:return nn(n.GroupEventName.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=Xr(e),s=t?.user_mute_time;if(!s||"object"!=typeof s||Array.isArray(s))return null;const r={};for(const[n,o]of Object.entries(s)){const e=Jr(n),t=Number(o);e&&Number.isFinite(t)&&t>0&&(r[e]=t)}return Object.keys(r).length>0?r:null})(e.ext),o=s?Object.keys(s):Zr(e.members,r);return nn(n.GroupEventName.MUTE_LIST_ADDED,{...t,userIds:o,muteExpire:o.map(e=>s?.[e]).find(e=>void 0!==e)??en(e.reason,e.eventExt)})}case 24:return nn(n.GroupEventName.MUTE_LIST_REMOVED,{...t,userIds:Zr(e.members,r)});case 29:return nn(n.GroupEventName.ALLOW_LIST_ADDED,{...t,userIds:Zr(e.members,r)});case 30:return nn(n.GroupEventName.ALLOW_LIST_REMOVED,{...t,userIds:Zr(e.members,r)});case 31:return nn(n.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return nn(n.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return nn(n.GroupEventName.ADMIN_ADDED,{...t,administratorId:r??s});case 22:return nn(n.GroupEventName.ADMIN_REMOVED,{...t,administratorId:r??s});case 20:return nn(n.GroupEventName.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:r});case 17:{const r=Zr(e.members,s);return nn(n.GroupEventName.MEMBERS_JOINED,{...t,memberIds:r})}case 18:{const r=Zr(e.members,s);return nn(n.GroupEventName.MEMBERS_EXITED,{...t,memberIds:r})}case 25:return nn(n.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return nn(n.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return nn(n.GroupEventName.SHARED_FILE_ADDED,{...t,sharedFile:sn(e.reason,e.eventExt)});case 28:return nn(n.GroupEventName.SHARED_FILE_DELETED,{...t,fileId:rn(e.reason,e.eventExt)});case 14:return nn(n.GroupEventName.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:tn(e.eventExt)});case 41:return nn(n.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return nn(n.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const r=(e=>{const t=Xr(e);if(!t)return{attribute:{}};const s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},r=Object.fromEntries(Object.entries(s).filter(e=>"string"==typeof e[1]));return{userId:Jr(t.username),attribute:r}})(e.eventExt);return nn(n.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:r.userId,attribute:r.attribute,from:s,source:e.source??"direct"})}default:return null}},an=new WeakMap,cn=(e,t)=>{an.set(e,t)},dn=e=>an.get(e)??null,ln=(e,t)=>{const s=dn(e);s&&cn(t,s)},un=new WeakMap,hn=e=>un.get(e),pn="singleChat",mn="groupChat",gn=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},fn=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}},yn=e=>{if(!Array.isArray(e))return;const t=e.map(e=>gn(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},En=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Rn=(...e)=>{for(const t of e){const e=gn(t);if(e)return e}},In=(e,t)=>Boolean(e&&t&&e===t),vn=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),Cn=(e,t,s)=>{const r=yn(e);if(r&&r.length>0)return r;const n=(t??[]).map(e=>gn(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const o=gn(s?.name);return o?[o]:[]},Sn=e=>{const t=fn(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}}},Tn=(t,s)=>{const r=Rn(t.to?.[0]?.clientResource);if(1!==t.to?.length||gn(t.to[0]?.name)!==s.userId||!vn(s.userId,r,s))return null;const n=(o=t.from,gn(o?.name)??"");var o;if(!n)return e.logger.warn("Discarded MultiDevice contact event without target user",{operation:t.operation}),null;const i=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice contact operation",{operation:t}),"UNKNOWN"}})(t.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:n,rosterVersion:t.rosterVersion,ext:t.ext,deviceId:r,timestamp:t.timestamp,raw:t.raw}},An=(t,s)=>{if(!t.groupId)return e.logger.warn("Discarded MultiDevice group event without groupId",{operation:t.operation}),null;const r=Rn(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!vn(gn(t.from?.name),r,s))return null;const n=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice group operation",{operation:t}),"UNKNOWN"}})(t.operation);if("UNKNOWN"===n)return null;const o=Cn(t.members,t.to,t.from);return{category:"group",operation:n,groupId:t.groupId,userIds:o.length>0?o:void 0,operatorId:gn(t.from?.name),groupName:t.groupName,deviceId:r,timestamp:t.timestamp,raw:t.raw}},On=(t,s)=>{if(!t.threadId)return e.logger.warn("Discarded MultiDevice thread event without threadId",{operation:t.operation}),null;const r=Rn(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!vn(gn(t.from?.name),r,s))return null;const n=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice thread operation",{operation:t}),"UNKNOWN"}})(t.operation);if("UNKNOWN"===n)return null;const o=Cn(t.members,t.to,t.from);return{category:"thread",operation:n,threadId:t.threadId,parentId:t.parentId,userIds:o.length>0?o:void 0,operatorId:gn(t.from?.name),threadName:t.threadName,deviceId:r,timestamp:t.timestamp,raw:t.raw}},bn=(t,s)=>{if("pin"===t.operation||"pin_delete"===t.operation)return null;const r=Rn(t.res,t.raw?.resource,t.raw?.clientResource);if(In(r,s.clientResource))return e.logger.debug("Discarded same-device MultiDevice conversation echo",{operation:t.operation,conversationId:t.id}),null;const n="chat"===(o=t.type)||"singleChat"===o?pn:mn;var o;const i=gn(t.id)??(n===pn?gn(t.from):void 0);if(!i)return e.logger.warn("Discarded MultiDevice conversation event without conversationId",{operation:t.operation}),null;const a=(t=>{switch(t){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 e.logger.warn("Discarded unknown MultiDevice conversation operation",{operation:t}),"UNKNOWN"}})(t.operation);return"UNKNOWN"===a?null:{category:"conversation",operation:a,conversationId:i,conversationType:n,mark:"mark"===t.operation||"mark_delete"===t.operation?Sn(t.ext):void 0,operatorId:gn(t.from),deviceId:r,timestamp:fn(t.ts),raw:t.raw}},_n=(t,s)=>{const r=Rn(t.resource,t.raw?.resource,t.raw?.clientResource);if(In(r,s.clientResource))return e.logger.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:t.to}),null;const n=gn(t.to);if(!n)return e.logger.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const o=gn(t.lastMsgId),i=yn(t.msgIdList)??(o?[o]:void 0),a=fn(t.deleteTime);if(!i&&void 0===a)return e.logger.warn("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:n}),null;const c=(t=>t&&"deleteRoaming"!==t&&"MESSAGE_REMOVED"!==t?(e.logger.warn("Discarded unknown MultiDevice message-removed operation",{operation:t}),"UNKNOWN"):"MESSAGE_REMOVED")(t.messageRoamingType);return"UNKNOWN"===c?null:{category:"messageRemoved",operation:c,conversationId:n,conversationType:"groupchat"===t.chatType||"groupChat"===t.chatType?mn:pn,messageIds:i,beforeTimestamp:a,deviceId:r,raw:t.raw}},Mn=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var Nn=4096,Dn=65547,wn=15,Ln=2113929216,Un=65536,Pn=65536,kn=10485760,xn={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Fn={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Bn(e){if(!(e>0))return Pn;if(e<=Pn)return Pn;if(e>1073741823)return e;for(var t=Pn;t<e;)t*=2;return t}var Gn={byU16:0,byU32:1},qn=0,Kn=1,Vn=2,zn=0,Hn=1;function jn(e,t){return e[t]|e[t+1]<<8}function Wn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Qn(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var $n="fast";function Yn(e){return 2654435761*(e>>>0)>>>20&4095}function Jn(e){return 2654435761*(e>>>0)>>>19&8191}function Xn(e,t,s){if("fast"===$n){var r=Wn(e,t);return s===Gn.byU16?Jn(r):Yn(r)}throw new Error("Unsupported hash strategy: "+$n)}function Zn(e,t,s,r,n){s[t]=e-n}function eo(e,t,s,r,n){Zn(t,Xn(e,t,r),s,0,n)}function to(e,t,s,r){return t[e]+r}function so(e,t,s,r,n){return to(Xn(e,t,r),s,0,n)}function ro(e,t,s,r){for(var n=t;t<r-3;){if(Wn(e,t)!==Wn(e,s)){for(;t<r&&e[t]===e[s];)t++,s++;return t-n}t+=4,s+=4}for(;t<r&&e[t]===e[s];)t++,s++;return t-n}function no(e,t,s,r,n,o,i,a,c,d){var l,u,h,p=e.hashTable,m=r,g=m-e.dictSize,f=e.dictionary,y=e.dictionaryStart,E=y+e.dictSize,R=e.dictSize>0?E-r:0,I=r,v=r+n,C=v-12,S=v-5,T=0,A=o>0?o:s.length,O=0;if(n>Ln)return 0;switch(c){case qn:default:l=r,u=r;break;case Kn:l=r-e.currentOffset,u=r-e.dictSize;break;case Vn:l=r-e.currentOffset,u=r}if(a===Gn.byU16&&n>=Dn)return 0;if(n<13)return ao(t,s,I,v,T,A,i);eo(t,m,p,a,l),h=Xn(t,++m,a);e:for(;;){var b,_,M=m,N=1,D=64;do{var w=h;if(m=M,M+=N,N=D++>>>6,M>C)return ao(t,s,I,v,T,A,i);b=to(w,p,0,l),c===Vn&&(b<r?(O=R,u=y):(O=0,u=r)),h=Xn(t,M,a),Zn(m,w,p,0,l)}while(d===Hn&&b<g||a!==Gn.byU16&&b+65535<m||!oo(t,f,m,b,O,c,r));for(;m>I&&b+O>u;){var L=b+O-1;if(t[m-1]!==(c===Vn&&b<r?f[L-y+e.dictionaryStart]:t[L]))break;m--,b--}var U=m-I;if(_=T++,i&&T+U+8+Math.floor(U/255)>A)return 0;if(U>=wn){var P=U-wn;for(s[_]=240;P>=255;)s[T++]=255,P-=255;s[T++]=P}else s[_]=U<<4;if(U>=16&&s.set&&t.subarray)s.set(t.subarray(I,I+U),T),T+=U;else for(var k=0;k<U;k++)s[T++]=t[I+k];t:for(;;){var x;if(Qn(s,T,m-b),T+=2,c===Vn&&b<r){var F=m+(E-(b+O));if(F>S&&(F=S),(m+=4+(x=io(t,f,m+4,b+O+4-y+e.dictionaryStart,F,E-y)))===F&&F<S){var B=ro(t,m,r,S);x+=B,m+=B}}else m+=4+(x=ro(t,m+4,b+4,S));if(i&&T+6+(x>>>8)>A)return 0;if(x>=15){for(s[_]+=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[_]+=x;if(I=m,m>C)break e;if(eo(t,m-2,p,a,l),b=so(t,m,p,a,l),c===Vn&&(b<r?(O=R,u=y):(O=0,u=r)),eo(t,m,p,a,l),!((d!==Hn||b>=g)&&b+65535>=m&&oo(t,f,m,b,O,c,r)))break t;s[_=T++]=0}h=Xn(t,++m,a)}return ao(t,s,I,v,T,A,i)}function oo(e,t,s,r,n,o,i){var a,c=Wn(e,s);o===Vn&&r+n<i?a=Wn(t,r+n):a=Wn(e,r+n);return c===a}function io(e,t,s,r,n,o,i){for(var a=s;r<o&&s<n&&t[r]===e[s];)r++,s++;return s-a}function ao(e,t,s,r,n,o,i){var a=r-s;if(i&&n+a+1+Math.floor((a+255-wn)/255)>o)return 0;if(a>=wn){for(t[n++]=240,a-=wn;a>=255;)t[n++]=255,a-=255;t[n++]=a}else t[n++]=a<<4;var c=s,d=r,l=d-c;if(l>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),n),n+=l;else for(var u=c;u<d;u++)t[n++]=e[u];return n}function co(e,t,s,r){var n,o=0;if(r&&t.ip>=s)return-1;do{if(o+=n=e[t.ip++],t.ip>s)return-1;if(o>2147483647)return-1}while(255===n);return o}function lo(e,t,s,r,n,o,i,a,c,d,l,u,h){if(null==e)return-1;if(o<0)return-1;var p=s,m=s+r,g=n,f=n+o,y=l-h,E=u+h,R=h<65536;if(0===o)return 1===r&&0===e[p]?0:-1;if(0===r)return-1;for(;;){var I,v,C,S;if(p>=m)return-(p-s)-1;if((v=(I=e[p++])>>>4)===wn){var T=co(e,b={ip:p},m-wn,!0);if(p=b.ip,-1===T)return-(p-s)-1;if(g+(v+=T)<g)return-(p-s)-1;if(p+v<p)return-(p-s)-1}if(C=g+v,i&&(C>f-12||p+v>m-8)||!i&&C>f-8){if(!i&&C!==f)return-(p-s)-1;if(i&&(p+v!==m||C>f))return-(p-s)-1;if(v>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+v),g);else for(var A=0;A<v;A++)t[g+A]=e[p+A];p+=v,g+=v;break}if(v>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+v),g);else for(A=0;A<v;A++)t[g+A]=e[p+A];if(g=C,(p+=v)+2>m)return-(p-s)-1;var O=jn(e,p);if(p+=2,S=C-O,R&&S+h<l)return-(p-s)-1;if(0===O)return-(p-s)-1;if(15===(v=15&I)){var b;T=co(e,b={ip:p},m-5+1,!1);if(p=b.ip,-1===T)return-(p-s)-1;if(g+(v+=T)<g)return-(p-s)-1}if(v+=4,d===Vn&&S<l){if(g+v>f-5)return-(p-s)-1;if(v<=l-S){var _=E-(l-S);for(A=0;A<v;A++)t[g+A]=t[_+A];g+=v}else{var M=l-S;for(_=E-M,A=0;A<M;A++)t[g+A]=t[_+A];var N=v-M;if(N>(g+=M)-l)for(var D=l,w=g+N;g<w;)t[g++]=t[D++];else{for(A=0;A<N;A++)t[g+A]=t[l+A];g+=N}}}else{if(S<y)return-(p-s)-1;if(C=g+v,g-S<8)for(t[g]=t[S],t[g+1]=t[S+1],t[g+2]=t[S+2],t[g+3]=t[S+3],g+=4,S+=4;g<C;)t[g++]=t[S++];else for(;g<C;)t[g++]=t[S++]}}return i?g-n:p-s}function uo(){return{hashTable:new Uint32Array(Nn),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function ho(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function po(e,t,s,r,n,o,i,a){r=r||0;var c=e.dictionaryStart+e.dictSize,d=r;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,r=0;r<e.hashTable.length;r++)e.hashTable[r]<t?e.hashTable[r]=0:e.hashTable[r]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=s-e.dictSize}}(e);var l,u=r+n;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?Hn:zn;return e.dictionary&&c===r?(l=no(e,t,s,r,n,i||0,a||!1,Gn.byU32,Kn,h),e.dictSize+=n,e.currentOffset+=n,l):(l=no(e,t,s,r,n,i||0,a||!1,Gn.byU32,Vn,h),e.dictionary=t,e.dictionaryStart=r,e.dictSize=n,e.currentOffset+=n,l)}function mo(e,t,s,r){var n=e.dictionaryStart+e.dictSize;r>65536&&(r=65536),r>e.dictSize&&(r=e.dictSize);var o=n-r;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(o,o+r),s);else for(var i=0;i<r;i++)t[s+i]=e.dictionary[o+i];return e.dictionary=t,e.dictionaryStart=s,e.dictSize=r,r}function go(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function fo(e,t,s,r){return e.prefixSize=r,e.prefixEnd=s+r,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function yo(e,t,s,r,n,o,i){var a;if(e.prefixEnd===o){if((a=lo(t,s,r,n,o,i,!0,0,0,Vn,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=lo(t,s,r,n,o,i,!0,0,0,Vn,o,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=o+a}return a}function Eo(e){var t=(e=e||{}).minWorkArea||Pn,s=e.maxWorkArea||kn,r=e.shrinkThreshold||t;t<Pn&&(t=Pn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=Un+t,this.maxBufferSize=Un+s,this.shrinkThreshold=Un+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:xn.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=uo()}function Ro(e){var t=(e=e||{}).minWorkArea||Pn,s=e.maxWorkArea||kn,r=e.shrinkThreshold||t;t<Pn&&(t=Pn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=Un+t,this.maxBufferSize=Un+s,this.shrinkThreshold=Un+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:xn.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Eo.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<Un?this.offset:Un,n=this.offset>Un?this.offset-Un:0;t.set(this.ringBuffer.subarray(n,n+r),0),mo(this.stream,t,0,r),s=r}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Eo.prototype.compress=function(e,t){var s=e.length;if(s<=0)return Fn.PARAM_ERROR;if(s>this.maxBufferSize-Un)return Fn.PARAM_ERROR;if(s>this.ringBufferSize-Un){var r=Bn(s),n=Un+r;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Fn.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(mo(this.stream,this.ringBuffer,0,Un),this.offset=Un);var o=this.offset;this.ringBuffer.set(e,o);var i=po(this.stream,this.ringBuffer,t,o,s,0,t.length,!0);return i<=0?Fn.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),i)},Eo.prototype.reset=function(){this.offset=0,ho(this.stream)},Eo.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Eo.prototype._tryAutoShrink=function(){this.shrinkMode!==xn.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===xn.AUTO_IMMEDIATE||this.shrinkMode===xn.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Eo.prototype.getWorkArea=function(){return this.ringBufferSize-Un},Eo.prototype.getRingBufferSize=function(){return this.ringBufferSize},Eo.prototype.getBaseBufferSize=function(){return this.minBufferSize},Eo.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Eo.prototype.getCurrentOffset=function(){return this.offset},Eo.prototype.getShrinkMode=function(){return this.shrinkMode},Eo.prototype.setShrinkMode=function(e){this.shrinkMode=e},Eo.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Eo.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Un,s=this.maxBufferSize-Un;if(e<t||e>s)return Fn.PARAM_ERROR;this.shrinkThreshold=Un+e},Ro.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<Un?this.offset:Un,n=this.offset>Un?this.offset-Un:0;t.set(this.ringBuffer.subarray(n,n+r),0),s=r,fo(this.streamDecode,0,0,r)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Ro.prototype.decompress=function(e,t,s){var r=e.length;if(r<=0||s<=0)return Fn.PARAM_ERROR;if(s>this.maxBufferSize-Un)return Fn.PARAM_ERROR;if(s>this.ringBufferSize-Un){var n=Bn(s),o=Un+n;if(o>this.maxBufferSize&&(o=this.maxBufferSize),!this._resizeBuffer(o))return Fn.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var i=this.offset-Un;i>0&&this.ringBuffer.set(this.ringBuffer.subarray(i,i+Un),0),fo(this.streamDecode,this.ringBuffer,0,Un),this.offset=Un}var a=yo(this.streamDecode,e,this.ringBuffer,0,r,this.offset,s);return a<=0?Fn.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Ro.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Ro.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Ro.prototype._tryAutoShrink=function(){this.shrinkMode!==xn.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===xn.AUTO_IMMEDIATE||this.shrinkMode===xn.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Ro.prototype.getWorkArea=function(){return this.ringBufferSize-Un},Ro.prototype.getRingBufferSize=function(){return this.ringBufferSize},Ro.prototype.getBaseBufferSize=function(){return this.minBufferSize},Ro.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Ro.prototype.getCurrentOffset=function(){return this.offset},Ro.prototype.getShrinkMode=function(){return this.shrinkMode},Ro.prototype.setShrinkMode=function(e){this.shrinkMode=e},Ro.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Ro.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Un,s=this.maxBufferSize-Un;if(e<t||e>s)return Fn.PARAM_ERROR;this.shrinkThreshold=Un+e};const Io={LZ4_MAX_INPUT_SIZE:Ln,BLOCK_MAX_SIZE:65536,DICT_SIZE:Un,DEFAULT_WORK_AREA:Pn,DEFAULT_MAX_WORK:kn,SHRINK_MODE:xn,LZ4_ERROR:Fn,alignToPowerOf2:Bn,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".');$n=e},getHashStrategy:function(){return $n},compress:function(e,t,s,r,n){if(null==e)return 0;if(null==t)return 0;if(s=s||0,r=void 0===r?e.length:r,n=n||0,s<0||n<0)return 0;if(r<0)return 0;if(s+r>e.length)return 0;if(r>Ln)return 0;if(0===r)return t.length>n?(t[n]=0,1):0;var o=r<Dn?Gn.byU16:Gn.byU32;return no({hashTable:new Uint32Array(o===Gn.byU16?8192:Nn),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,0,!1,o,qn,zn)},compressLimited:function(e,t,s,r,n,o){if(null==e)return 0;if(null==t)return 0;if(s=s||0,r=void 0===r?e.length:r,n=n||0,s<0||n<0)return 0;if(r<0||o<0)return 0;if(s+r>e.length)return 0;if(r>Ln)return 0;if(o<1)return 0;if(0===r)return t[n]=0,1;var i=r<Dn?Gn.byU16:Gn.byU32;return no({hashTable:new Uint32Array(i===Gn.byU16?8192:Nn),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,o,!0,i,qn,zn)},compressBound:function(e){return e<0||e>Ln?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,s,r,n,o){return null==e||null==t?-1:(n=n||0,(s=s||0)<0||n<0||r<0||o<0||s+r>e.length||n+o>t.length?-1:lo(e,t,s,r,n,o,!0,0,0,qn,n,null,0))},decompressFast:function(e,t,s,r,n){return lo(e,t,s=s||0,0,r=r||0,n,!1,0,0,Kn,r-65536,0,65536)},createStream:uo,resetStream:ho,loadDict:function(e,t,s,r){if(e.initCheck&&ho(e),r<4)return e.dictionary=null,e.dictSize=0,0;r>65536&&(s=s+r-65536,r=65536);var n=s-e.currentOffset;e.dictionary=t,e.dictionaryStart=s,e.dictSize=r,e.currentOffset+=r;for(var o=s,i=s+r;o<=i-4;)eo(t,o,e.hashTable,Gn.byU32,n),o+=3;return r},compressContinue:po,saveDict:mo,createStreamDecode:go,setStreamDecode:fo,decompressSafeContinue:yo,RingBufferEncoder:Eo,RingBufferDecoder:Ro,_hashU16:Jn,_hashU32:Yn,_TABLE_TYPE:Gn},vo=268435455,Co=new Uint32Array(256);let So=!1;function To(e){!function(){if(!So){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;Co[e]=t>>>0}So=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const r=e[s]??0;t=t>>>8^(Co[255&(t^255&r)]??0)}return(4294967295^t)>>>0}var Ao=(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))(Ao||{});const Oo=268435455;class bo{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Io.DEFAULT_WORK_AREA,maxWorkArea:Io.DEFAULT_MAX_WORK,shrinkMode:Io.SHRINK_MODE.MANUAL};this.encoder=new Io.RingBufferEncoder(e),this.decoder=new Io.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>Oo)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=Io.compressBound(t.length),r=new Uint8Array(s),n=this.encoder.compress(t,r);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const o=r.subarray(0,n),i=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>vo)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=To(t),c=new Uint8Array(i.length+4+n);let d=0;c.set(i,d),d+=i.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(o,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},r=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let s=0,r=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,s|=(127&n)<<r,!(128&n))return s>>>0;if(r+=7,r>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,s);if(r>Oo)throw new Error(`Original size exceeds maximum allowed: ${r}`);if(t.length<s.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+s.offset,4).getUint32(0,!1);s.offset+=4;const o=t.subarray(s.offset),i=new Uint8Array(r),a=this.decoder.decompress(o,i,r);if(a<0||a!==r)throw new Error(`LZ4 decompression failed: expected ${r}, got ${a}`);const c=To(i);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return i}reset(){this.encoder.reset(),this.decoder.reset()}}const _o=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Mo=(e,t)=>s.encodeWithReflection(e,t).finish();class No{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Lr({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:[Ee],compressType:[Re],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 t=Mr(),s=t.lookupType("easemob.pb.Provision"),r=t.lookupType("easemob.pb.MSync"),n={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Re],encryptType:[Ee],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}:{}},o=Mo(s,n),i={version:0,guid:Ur({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:B,deviceId:0,encryptType:[Ee],payload:o,traceId:e.createTraceId()};return Mo(r,i)}encodeHeartbeat(){const t=Mr(),s=t.lookupType("easemob.pb.CommUnreadUL"),r=t.lookupType("easemob.pb.MSync"),n=Mo(s,{}),o={version:0,encryptType:[Ee],command:x,payload:n,traceId:e.createTraceId()};return Mo(r,o)}encodeStatisticRebuild(){const t=Mr(),s=t.lookupType("easemob.pb.StatisticsBody"),r=t.lookupType("easemob.pb.Meta"),n=t.lookupType("easemob.pb.CommSyncUL"),o=t.lookupType("easemob.pb.MSync"),i=Mo(s,{operation:0}),a=r.decode(new Uint8Array);a.id=Date.now(),a.ns=le,a.payload=i;const c=n.decode(new Uint8Array);c.meta=a;const d=Mo(n,c);return Mo(o,{version:0,encryptType:[Ee],command:k,payload:d,traceId:e.createTraceId()})}decodeProvision(e){const t=Mr().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},r="number"==typeof s.errorCode?s.errorCode:Ce,n="string"==typeof s.reason?s.reason:void 0,o="string"==typeof t.resource?t.resource:void 0,i="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:r===ve,statusCode:r,reason:n,resource:o,authToken:i,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Mr().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=Mr().lookupType("easemob.pb.CommSyncDL").decode(e),s=Array.isArray(t.metas)?t.metas:[],r=[];for(const n of s){const e=this.decodeStatisticMeta(n);e&&r.push(e)}return r}decodeMsync(e){const t=Mr().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(t){const s=Mr(),r=s.lookupType("easemob.pb.CommSyncDL"),n=s.lookupType("easemob.pb.MessageBody"),o=r.decode(t);e.logger.debug("decodeSync commSyncDl",{hasMetas:Array.isArray(o.metas)});const i=Array.isArray(o.metas)?o.metas:[],a=this.decodeAck(o);a?.ok&&(a.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const c=kr(o.metaId),d=kr(o.nextKey),l=o.queue??void 0,u="boolean"==typeof o.isLast?o.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:a,messages:h,notifies:p.length>0?p:void 0,metaId:c,queue:l,nextKey:d,isLast:u,replacedMessage:e}}for(const e of i){const t=this.decodeChatMeta(e,n);t&&h.push(t);const s=this.decodeChatActionMeta(e,n);s&&p.push(s);const r=this.decodeNotifyMeta(e);r.length>0&&p.push(...r)}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,r=s.payload;let n=null;if(r instanceof Uint8Array?n=r:r instanceof ArrayBuffer?n=new Uint8Array(r):ArrayBuffer.isView(r)&&(n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!n)return null;if(("number"==typeof s.ns?s.ns:void 0)!==ue)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const r=e;return this.decodeMessage(s,r)}catch{return null}}decodeChatActionMeta(t,s){if(!t||"object"!=typeof t)return null;const r=t,n=r.payload;let o=null;if(n instanceof Uint8Array?o=n:n instanceof ArrayBuffer?o=new Uint8Array(n):ArrayBuffer.isView(n)&&(o=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),!o)return null;if(("number"==typeof r.ns?r.ns:void 0)!==ue)return null;try{const t=s.decode(o);if(!t||"object"!=typeof t)return null;const n=t,i="number"==typeof n.type?n.type:q;if(i!==H&&i!==W&&i!==Q&&i!==$&&i!==j)return null;const a=this.readJid(r.to),c=Number(kr(r.timestamp))||Date.now(),d=this.resolveActionConversationType(a.domain,n.meta,n),{senderId:l,receiverId:u}=this.resolveIncomingMessageParties(r,n,d),h=this.resolveActionConversationId(l,u,d);if(i===Q)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===H){e.logger.debug("Received READ_ACK MessageBody",n);const t=(Array.isArray(n.ackMessageIds)?n.ackMessageIds:[]).map(e=>kr(e)).filter(e=>Boolean(e)),s=kr(n.ackMessageId);if(0===t.length&&s&&t.push(s),0===t.length||!h)return null;const r=Fr(Array.isArray(n.ext)?n.ext.filter(_o):void 0),o=_o(r.group_ack_count)?r.group_ack_count:{},i=t.flatMap(e=>{const t=o[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:t,conversationId:h,conversationType:"groupChat"===d?"groupChat":"singleChat",timestamp:c,..."groupChat"===d?{receiptDetails:i}:{}}}}if(i===j){const e=kr(n.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(i===W){const e=kr(n.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=kr(n.editMessageId),m=(Array.isArray(n.contents)?n.contents:[])[0],g=m?this.decodeContent(m):null;if(!p||!h||!g)return null;const f=this.resolveModifiedInfo(n.meta);return{type:"message_updated",data:{messageId:p,conversationId:h,conversationType:d,timestamp:c,message:{type:g.type,body:g.body,ext:Fr(n.ext),...f?{modifiedInfo:f}:{}}}}}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!==me&&s!==pe&&s!==he&&s!==le)return[];const r=t.payload;let n=null;return r instanceof Uint8Array?n=r:r instanceof ArrayBuffer?n=new Uint8Array(r):ArrayBuffer.isView(r)&&(n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),n?s===pe?this.decodeRosterMeta(t,n):s===he?this.decodeMucMeta(t,n):s===le?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(t,s){try{const r=Mr(),n=r.lookupType("easemob.pb.StatisticsBody").decode(s);if("string"!=typeof n.location||0===n.location.length)return[];const o=JSON.parse(n.location);if(!_o(o)||!Array.isArray(o.group_ack))return[];const i=this.readMetaTimestamp(t)??Date.now(),a=new Map;for(const e of o.group_ack){if(!_o(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[s,r]of Object.entries(e)){if("groupId"===s)continue;const e="number"==typeof r?r:"string"==typeof r&&r.trim().length>0?Number(r):Number.NaN;!s||!Number.isInteger(e)||e<0||a.set(s,{conversationId:t,count:e})}}return e.logger.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:i,receiptDetails:[{messageId:e,count:s}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==le)return null;const s=t.payload;let r=null;if(s instanceof Uint8Array?r=s:s instanceof ArrayBuffer?r=new Uint8Array(s):ArrayBuffer.isView(s)&&(r=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!r)return null;try{const e=Mr(),t=e.lookupType("easemob.pb.StatisticsBody").decode(r);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=Mr(),r=s.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof r.operation?r.operation:-1,o=this.readRosterJid(r.from),i=this.readRosterJidList(r.to),a="string"==typeof r.reason?r.reason:"",c="string"==typeof r.rosterVer&&r.rosterVer.trim().length>0?r.rosterVer:void 0,d=o.name??"",l=i[0]?.name??"";if(!d&&!l)return[];const u=Tn({operation:n,from:o,to:i,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:r},this.msyncCodecContext());if(u)return[this.createMultiDeviceNotify(u)];const h=this.mapRosterOperationToEvent(n,{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=Mr(),r=s.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof r.operation?r.operation:-1,o=!0===r.isChatroom,i=!0===r.isThread,a=this.readJid(r.from),c=Array.isArray(r.to)?r.to.map(e=>this.readJid(e)):[],d=r.eventInfo&&"object"==typeof r.eventInfo?r.eventInfo:void 0,l=Array.isArray(r.members)?r.members.filter(e=>"string"==typeof e):[],u=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(i){const t=On({operation:n,threadId:this.readJid(r.mucId).name??"",threadName:"string"==typeof r.mucName?r.mucName:void 0,parentId:this.readJid(r.mucParentId).name??void 0,from:a,to:c,members:l,timestamp:this.readMetaTimestamp(e),raw:r},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const s=37===n&&c.some(e=>e.name===this.context.userId),o=this.readJid(r.mucId).name??"",i=this.readJid(r.mucParentId).name??"";return s&&o&&i?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:o,name:"string"==typeof r.mucName?r.mucName:void 0,muc_parent_id:i,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!o){const t=An({operation:n,groupId:this.readJid(r.mucId).name??"",groupName:"string"==typeof r.mucName?r.mucName:void 0,from:a,to:c,reason:"string"==typeof r.reason?r.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:l,timestamp:this.readMetaTimestamp(e),raw:r},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=o?Qr({operation:n,chatRoomId:this.readJid(r.mucId).name??"",chatRoomName:"string"==typeof r.mucName?r.mucName:void 0,from:a,to:c,reason:"string"==typeof r.reason?r.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof r.ext?r.ext:void 0,members:l}):on({operation:n,groupId:this.readJid(r.mucId).name??"",groupName:"string"==typeof r.mucName?r.mucName:void 0,from:a,to:c,reason:"string"==typeof r.reason?r.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof r.ext?r.ext:void 0,members:l,source:u});return h?[{type:o?"chatroom":"group",eventName:o?"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&&un.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(t){try{let s="";for(let e=0;e<t.length;e+=1){const r=t[e];if(void 0===r)return[];s+=`%${r.toString(16)}`}const r=decodeURIComponent(s),n=JSON.parse(r);e.logger.debug("Decoded MSync notify payload",{payload:n});const o="string"==typeof n.type?n.type:"";if(!o)return[];if("thread"===o){return[{type:o,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:_o(n.data)?n.data:n}}]}if("conv"===o){const e=_o(n.data)?n.data:n,t=[],s="string"==typeof e.op?e.op:"";if("pin"===s||"pin_delete"===s)return[{type:o,eventName:"onPinnedMessageChanged",data:e}];const r=bn({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 r&&t.push(this.createMultiDeviceNotify(r)),t}if("roaming_delete"===o){const e=_o(n.data)?n.data:n,t=_n({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"===o){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const s=[];for(const r of e){if(!En(r))continue;const e=Rn(r.operator_resource,r.resource,r.clientResource);if(In(e,t.clientResource))continue;const n=gn(r.group)??gn(r.user);if(!n||!En(r.data))continue;const o=gn(r.group)?mn:pn,i=r.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:o,remindType:gn(i.type),silentMode:i,deviceId:e,raw:r})}return s})(_o(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:o,data:n.data??n}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,s=Number(kr(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:Mn(e.category),data:e}}decodeNotice(e){const t=Mr().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Mr().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(t){const s=Mr(),r=s.lookupType("easemob.pb.CommSyncUL"),n=s.lookupType("easemob.pb.MSync"),o=Mo(r,{queue:t}),i={version:0,encryptType:[Ee],command:k,payload:o,traceId:e.createTraceId()};return Mo(n,i)}encodeLastSession(t,s){const r=Mr(),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i=Mo(n,{queue:t,key:s}),a={version:0,encryptType:[Ee],command:k,payload:i,traceId:e.createTraceId()};return Mo(o,a)}encodeChatMessage(t,s){const r=Mr(),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i=this.buildChatMeta(t,s),a=Mo(n,{meta:i}),c={version:0,encryptType:[Ee],command:k,payload:a,traceId:e.createTraceId()};return Mo(o,c)}encodeCombineMessageMeta(e){const t=Mr().lookupType("easemob.pb.Meta"),s=Pr(e.msgServerId||e.msgLocalId),r=this.buildChatMeta(e,s,!0);return Mo(t,r)}buildChatMeta(e,t,s=!1){const r=Mr().lookupType("easemob.pb.MessageBody"),n=this.buildContent(e),o=this.resolveMessageProfileVersionFields(e),i=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:[n],ext:xr(e.ext??{}),...i?{meta:i}:{},...o,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},u=Mo(r,l),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e);return{id:t,to:Ur({appKey:this.context.appKey,name:d,domain:h,clientResource:s?void 0:a.clientResource}),...s?{timestamp:e.timestamp}:{},ns:ue,payload:u,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}}}encodeActionMessage(t,s){const r=Mr(),n=r.lookupType("easemob.pb.MessageBody"),o=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),a=r.lookupEnum("easemob.pb.MessageBody.EditScope"),c=this.resolveOutboundMessageTarget(t.conversationId,t.conversationType),d=t.body&&t.messageType?[this.buildContent({msgServerId:t.messageId??"",msgLocalId:s,from:this.context.userId,to:t.conversationId,sender:{userId:this.context.userId},conversationId:t.conversationId,conversationType:t.conversationType,type:t.messageType,sendStatus:"sending",ext:t.ext??{},timestamp:Date.now(),body:t.body})]:[],l={type:this.resolveActionMessageType(t),from:{name:this.context.userId},to:{name:c.name},contents:d,ext:xr(t.ext??{})};"recall"!==t.kind&&"deliveryAck"!==t.kind||(l.ackMessageId=t.messageId),"sendMessageReadReceipts"===t.kind&&(l.ackMessageIds=t.messageIds,"groupChat"===t.conversationType&&(l.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===t.kind&&(l.sendToPeer=t.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===t.kind&&(l.sendToPeer=t.sendToPeer??!1,l.clearAllUnreadMessageCount=t.clearAllUnreadMessageCount??!0),"update"===t.kind&&(l.editMessageId=t.messageId,l.editScope=t.ext&&Object.keys(t.ext).length>0?a.values.BODY_AND_EXT:a.values.BODY);const u=Mo(n,l);if("clearAllConversationUnreadMessageCount"===t.kind){const t=n.decode(u),r=n.fields.clearAllUnreadMessageCount;e.logger.debug("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:s,messageType:l.type,fieldId:r?.id,requestedValue:l.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(t,"clearAllUnreadMessageCount"),decodedValue:t.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const h={id:s,to:Ur({appKey:this.context.appKey,name:c.name,domain:"singleChat"===t.conversationType?this.context.domain:"conference.easemob.com",clientResource:c.clientResource}),ns:ue,payload:u,routetype:ge,directedUsers:[],ext:[]},p=Mo(o,{meta:h}),m={version:0,encryptType:[Ee],command:k,payload:p,traceId:e.createTraceId()};return Mo(i,m)}encodeChatRoomOperation(t,s){const r=Mr(),n=r.lookupType("easemob.pb.MUCBody"),o=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),a={mucId:Ur({appKey:this.context.appKey,name:t.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===t.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===t.operation&&(void 0!==t.ext&&(a.ext=t.ext),void 0!==t.leaveOtherRooms&&(a.leaveOtherRooms=t.leaveOtherRooms));const c=Mo(n,a),d={id:s,from:Ur({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:he,payload:c},l=Mo(o,{meta:d}),u={version:0,encryptType:[Ee],command:k,payload:l,traceId:e.createTraceId()};return Mo(i,u)}decodeServerMessageMeta(e){const t=Mr(),s=t.lookupType("easemob.pb.Meta"),r=t.lookupType("easemob.pb.MessageBody");try{const t=s.decode(e);return this.decodeChatMeta(t,r)}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?ut(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 Pr(e)}decodeChatRoomJoinInfo(t){const s=Mr().lookupType("easemob.pb.MUCBody");for(const n of t){if(!_o(n)||n.ns!==he)continue;const t=n.payload,o=t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):void 0;if(o)try{const e=s.decode(o);if(!_o(e)||!_o(e.status))continue;const t=e.status.chatroomInfo;if("string"!=typeof t||""===t)continue;const r=JSON.parse(t);if(!_o(r))continue;const n=r[this.context.userId];if(!_o(n))continue;const i=n;return{..."boolean"==typeof i.is_all_mute?{isAllMembersMuted:i.is_all_mute}:{},..."number"==typeof i.create_timestamp?{createTimestamp:i.create_timestamp}:{},..."boolean"==typeof i.is_in_white_list?{isInAllowlist:i.is_in_white_list}:{},..."number"==typeof i.member_count?{memberCount:i.member_count}:{},muteExpireTimestamp:"number"==typeof i.mute_duration&&0!==i.mute_duration?i.mute_duration:-1}}catch(r){e.logger.error("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=kr(e.metaId);if(!t||"0"===t)return;const s=e.status??{},r="number"==typeof s.errorCode?s.errorCode:Ce,n="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:kr(e.serverId),ok:r===ve,statusCode:r,reason:n}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:K;if(!this.isPublicMessageType(s))return null;const r=(Array.isArray(t.contents)?t.contents:[])[0];if(!r)return null;const n=this.resolveConversationType(s),{senderUserId:o,senderId:i,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=i===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:i:a,l=this.decodeContent(r);if(!l)return null;const u=Fr(t.ext),h=Fr(e.ext),p=Number(kr(e.timestamp))||Date.now(),m=kr(e.id),g=this.resolveBroadcast(h),f=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),E=this.resolveContentReplaced(y),R=this.resolveReactions(y),I=this.resolveModifiedInfo(y),v=this.resolveChatThreadMessageContext(y),C=this.resolveChatThreadOverview(y),S=this.resolveProfileVersionTime(t.userInfoUpdateTime),T=this.resolveProfileVersionTime(t.namecardUpdateTime),A={msgServerId:m,msgLocalId:"",from:i,to:a,sender:{userId:o},conversationId:d,conversationType:n,type:l.type,sendStatus:"sent",ext:u,timestamp:p,body:l.body,direct:c,isOnline:this.resolveMessageIsOnline(s,h)};cn(A,{userInfoUpdateTime:S,namecardUpdateTime:T});const O=this.decodeStreamMeta(t.stream,r);O&&(A.type="text",A.body={content:O.fullText},A.stream=O),void 0!==g&&(A.isBroadcast=g),void 0!==f&&(A.priority=f),void 0!==E&&(A.isContentReplaced=E),R&&(A.reactions=R),I&&(A.modifiedInfo=I),v&&(A.isChatThread=!0,A.chatThread=v);const b=this.resolvePeerRead(y,n,c);void 0!==b&&(A.isPeerRead=b);const _=this.resolveGroupReadCount(y,n);void 0!==_&&(A.groupReadCount=_),C&&(A.chatThreadOverview=C);const M=t.msgConfig;return M?.allowGroupAck&&(A.needReadReceipt=!0),A}resolveMessageProfileVersionFields(e){const t=dn(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 i.normalizeProfileVersionSeconds(kr(e))}isPublicMessageType(e){return e===K||e===V||e===z}resolveMessageIsOnline(e,t){if(e===z)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,r=Number(kr(s.streamSeq));if(!Number.isFinite(r))return;const n="number"==typeof s.streamStatus?s.streamStatus:ae,o="number"==typeof s.streamError?s.streamError:0,i="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:r,status:this.mapStreamStatus(n,o),errorType:o,finishReason:i,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?U.ERROR:e===oe?U.START:e===ie?U.START_COMPLETED:e===ce?U.COMPLETED:e===de?U.FULL:U.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(s){if("text"===s.type){const e=s.body;return{type:Y,text:e.content}}if("cmd"===s.type){const e=s.body;return{type:se,action:e.action}}if("custom"===s.type){const e=s.body;return{type:re,customEvent:e.event,customExts:xr(e.params??{})}}if("location"===s.type){const e=s.body;return{type:Z,latitude:e.latitude,longitude:e.longitude,address:e.address,buildingName:e.buildingName}}if("image"===s.type){const t=s.body,r=t.isGif||t.isOriginalImage?"original":"large";return{type:J,displayName:t.filename,remotePath:t.originalImageUrl??"",imageType:e.toProtocolImageType(r),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"===s.type){const e=s.body;return{type:X,displayName:e.filename,remotePath:e.url,secretKey:e.secret,fileLength:e.fileLength,duration:e.duration,size:e.width&&e.height?{width:e.width,height:e.height}:void 0,thumbnailRemotePath:e.thumbnailUrl,thumbnailSecretKey:e.secret,thumbnailDisplayName:e.filename}}if("voice"===s.type){const e=s.body;return{type:ee,displayName:e.filename,remotePath:e.url,secretKey:e.secret,fileLength:e.fileLength,duration:e.duration,thumbnailDisplayName:e.filename}}if("combine"===s.type){const e=s.body;return{type:Y,subType:0,text:t.getCombineCompatibleTextSidecar(s)??"版本过低",displayName:e.filename,remotePath:e.url,secretKey:e.secret,fileLength:e.fileLength,title:e.title,summary:e.summary,combineLevel:e.combineLevel}}const r=s.body;return{type:te,displayName:r.filename,remotePath:r.url,secretKey:r.secret,fileLength:r.fileLength,thumbnailDisplayName:r.filename}}decodeContent(t){const s="number"==typeof t.type?t.type:Y,r="string"==typeof t.remotePath&&t.remotePath.length>0||"string"==typeof t.title&&t.title.length>0||"string"==typeof t.summary&&t.summary.length>0||"number"==typeof t.combineLevel&&t.combineLevel>0,n=Object.prototype.hasOwnProperty.call(t,"subType")&&0===t.subType;if(s===ne||s===Y&&(n||r)){return{type:"combine",body:{title:"string"==typeof t.title?t.title:"",summary:"string"==typeof t.summary?t.summary:"",filename:"string"==typeof t.displayName?t.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof t.remotePath?t.remotePath:void 0,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,combineLevel:"number"==typeof t.combineLevel?t.combineLevel:0}}}if(s===Y)return{type:"text",body:{content:"string"==typeof t.text?t.text:""}};if(s===se)return{type:"cmd",body:{action:"string"==typeof t.action?t.action:""}};if(s===re){const e=Fr(t.customExts);return{type:"custom",body:{event:"string"==typeof t.customEvent?t.customEvent:"",params:e}}}if(s===Z)return{type:"location",body:{latitude:"number"==typeof t.latitude?t.latitude:0,longitude:"number"==typeof t.longitude?t.longitude:0,address:"string"==typeof t.address?t.address:void 0,buildingName:"string"==typeof t.buildingName?t.buildingName:void 0}};if(s===J){const s=t.size??{},r="number"==typeof s.width?s.width:0,n="number"==typeof s.height?s.height:0,o=e.fromProtocolImageType(t.imageType)===e.IMAGE_TYPE_ORIGINAL,i="string"==typeof t.remotePath?t.remotePath:"",a=e.deriveImageUrls(i,{deriveVariants:!this.useCustomAttachmentUpload}),c="string"==typeof t.thumbnailRemotePath&&t.thumbnailRemotePath.length>0?t.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof t.displayName?t.displayName:"image",filetype:"application/octet-stream",width:r,height:n,isGif:1===t.subType,isOriginalImage:o,originalImageUrl:a.originalImageUrl,bigImageUrl:a.bigImageUrl,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,thumbnailUrl:c??a.thumbnailUrl}}}if(s===X){const e=t.size??{},s="number"==typeof e.width?e.width:void 0,r="number"==typeof e.height?e.height:void 0,n="string"==typeof t.thumbnailRemotePath?t.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof t.duration?t.duration:0,width:s,height:r,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,thumbnailUrl:n}}}if(s===ee){return{type:"voice",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof t.duration?t.duration:0,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0}}}if(s===te){return{type:"file",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0}}}return null}resolveChatType(e){switch(e.conversationType){case"groupChat":return V;case"chatRoom":return z;default:return K}}resolveActionConversationType(e,t,s){const r=this.resolveConversationTypeFromMeta(t);if(r)return r;const n=s?.msgConfig&&"object"==typeof s.msgConfig?s.msgConfig:null;return!0===n?.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,r=("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"===r||"singleChat"===r)return"singleChat";if("chat:group"===r||"groupChat"===r)return"groupChat";if("chat:room"===r||"chatRoom"===r)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 r=e.slice(s.length);return r?{name:this.context.userId,clientResource:r}:{name:e}}resolveIncomingMessageParties(e,t,s){const r=this.readJid(e.from),n=this.readJid(e.to),o=this.readJid(t.from),i=this.readJid(t.to),a=o.name??r.name??"",c=i.name??n.name??"";if(!("singleChat"===s&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:r.clientResource&&r.clientResource!==this.context.clientResource?`${a}/${r.clientResource}`:a,receiverId:n.clientResource?`${c}/${n.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return Q;case"sendMessageReadReceipts":return H;case"deliveryAck":return j;case"recall":return W;case"update":return $;default:return K}}resolveConversationType(e){return e===V?"groupChat":e===z?"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?xr({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?ye:this.resolveDeliverOnlineOnly(e)?fe:ge}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),r=this.parseMetaPayload(t);return s&&r?{...r,...s}:s??r??e??t}resolvePeerRead(e,t,s){if("singleChat"!==t||"SEND"!==s)return;const r=this.parseMetaPayload(e);return"boolean"==typeof r?.isRead?r.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const s=this.parseMetaPayload(e),r=s?.group_read_ack;return"number"==typeof r&&Number.isInteger(r)&&r>=0?r:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),s=t?.edit_msg;if(!_o(s))return;const r="string"==typeof s.operator?s.operator:"",n=this.toFiniteNumber(s.count),o=this.toFiniteNumber(s.edit_time);return r&&void 0!==n&&void 0!==o?{operatorId:r,operationCount:n,operationTime:o}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),s=t?.thread;if(!_o(s)||0===Object.keys(s).length)return;const r=this.readString(s.msg_parent_id??s.messageId),n=this.readString(s.muc_parent_id??s.parentId);if(!r||!n)return;const o=this.readString(s.thread_name??s.chatThreadName);return{messageId:r,parentId:n,...o?{chatThreadName:o}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),s=t?.thread_overview??t?.threadOverview;if(!_o(s)||0===Object.keys(s).length)return;const r=this.readString(s.id??s.thread_id??s.chatThreadId),n=this.readString(s.muc_parent_id??s.parentId);if(!r||!n)return;const o=this.readString(s.name),i=this.resolveChatThreadOverviewLastMessage(s.last_message??s.lastMessage,r);return{chatThreadId:r,parentId:n,...o?{name:o}:{},...void 0!==i?{lastMessage:i}:{},...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(!_o(e)||0===Object.keys(e).length)return null;const s=this.readString(e.msgId??e.msg_id??e.id);if(!s)return null;const r=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),o=this.readString(n?.from)??this.readString(e.from)??"",i=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=_o(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=o===this.context.userId?"SEND":"RECEIVE";return{msgServerId:s,msgLocalId:"",from:o,to:i,sender:{userId:o},conversationId:h,conversationType:"groupChat",type:l,sendStatus:"sent",ext:_o(n?.ext)?n.ext:{},timestamp:r,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(_o(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(t,s,r){if(!s){return{content:this.readString(r.msg??r.content??r.text)??""}}switch(t){case"text":default:return{content:this.readString(s.msg??s.content??s.text)??""};case"image":{const t=this.readString(s.url)??"",r=e.deriveImageUrls(t,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(s.filename)??"image",filetype:this.readString(s.filetype)??"application/octet-stream",width:this.toFiniteNumber(s.width)??0,height:this.toFiniteNumber(s.height)??0,isGif:!0===s.isGif,isOriginalImage:!1,originalImageUrl:r.originalImageUrl,bigImageUrl:r.bigImageUrl,thumbnailUrl:this.readString(s.thumb)??r.thumbnailUrl,secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)}}case"voice":return{url:this.readString(s.url)??"",filename:this.readString(s.filename)??"voice",filetype:this.readString(s.filetype)??"application/octet-stream",duration:this.toFiniteNumber(s.duration??s.length)??0,secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)};case"video":return{url:this.readString(s.url)??"",filename:this.readString(s.filename)??"video",filetype:this.readString(s.filetype)??"application/octet-stream",duration:this.toFiniteNumber(s.duration??s.length)??0,width:this.toFiniteNumber(s.width),height:this.toFiniteNumber(s.height),thumbnailUrl:this.readString(s.thumb),secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)};case"file":return{url:this.readString(s.url)??"",filename:this.readString(s.filename)??"file",filetype:this.readString(s.filetype)??"application/octet-stream",secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength)};case"location":return{latitude:this.toFiniteNumber(s.lat??s.latitude)??0,longitude:this.toFiniteNumber(s.lng??s.longitude)??0,address:this.readString(s.addr??s.address),buildingName:this.readString(s.buildingName)};case"cmd":return{action:this.readString(s.action)??""};case"custom":return{event:this.readString(s.event??s.customEvent)??"",params:_o(s.params??s.customExts)?s.params??s.customExts:{}};case"combine":return{title:this.readString(s.title)??"",summary:this.readString(s.summary)??"",filename:this.readString(s.filename)??"combine",filetype:"application/octet-stream",url:this.readString(s.url),secret:this.readString(s.secret),fileLength:this.toFiniteNumber(s.file_length??s.fileLength),combineLevel:this.toFiniteNumber(s.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(ht(t));return _o(e)?e:null}catch{return null}}if(_o(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return _o(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(_o).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?[]:[Ie]}configureCompression(e,t){if(!e||!e.includes(Ie))return void this.disableCompression();this.compressor||(this.compressor=new bo);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===Ao.UPLINK_ONLY||s===Ao.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===Ao.DOWNLINK_ONLY||s===Ao.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Ao.UPLINK_ONLY:1===e?Ao.DOWNLINK_ONLY:2===e?Ao.BIDIRECTIONAL:Ao.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Ao.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Do=t=>new e.ConnectionError("Connection attempt cancelled",{code:e.ERROR_CODES.CONNECTION_CANCELLED,details:{stage:t,cancelled:!0,retryable:!0}}),wo=t=>t instanceof e.ConnectionError&&t.code===e.ERROR_CODES.CONNECTION_CANCELLED&&!0===t.details?.cancelled;class Lo{constructor(s,r){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=new Set,this.offlineMessageQueueReports=new Map,this.offlineMessageQueueCounts=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:e.HEARTBEAT_INTERVAL,autoReconnectNumMax:10,connectTimeout:e.CONNECT_TIMEOUT,...s},this.eventHub=r,this.msyncCodec=new No({appKey:s.appKey,useCustomAttachmentUpload:s.useCustomAttachmentUpload,userId:s.userId,token:s.token,useReplacedMessageContents:s.useReplacedMessageContents,useFixedDeviceId:s.useFixedDeviceId,deviceId:s.deviceId,customDeviceName:s.customDeviceName,customOSPlatform:s.customOSPlatform,uiKitVersion:s.uiKitVersion,loginExtensionInfo:s.loginExtensionInfo,serviceId:s.serviceId}),this.serverUrls=this.normalizeServerUrls(s),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:t.ConnectionStatus.DISCONNECTED,serverUrl:this.config.serverUrl,userId:s.userId,token:s.token,reconnectAttempts:0},this.connectionRetry=new Tr({maxAttempts:this.config.autoReconnectNumMax,initialDelay:e.RECONNECT_INITIAL_DELAY,maxDelay:e.RECONNECT_MAX_DELAY,backoffMultiplier:e.RECONNECT_BACKOFF_MULTIPLIER}),this.heartbeatManager=new br({interval:this.config.heartBeatWait,timeout:e.HEARTBEAT_TIMEOUT}),this.connectionEventNormalizer=new pt,this.socketAdapter=this.resolveSocketAdapter(s),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[t.InternalEventName.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 r=Date.now();if(s<=r)throw new e.ConnectionError("Token is expired",{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=t,this.connection.token=t,this.msyncCodec.updateToken(t),this.setupTokenLifecycle(t,s,r),e.logger.warn("Connection token renewed",{userId:this.config.userId,expireAt:s}),{token:t,expireAt:s}}handleOnline(){if(e.logger.warn("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0,this.terminalDisconnectError)return void e.logger.warn("Network online recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});const s=this.offlineRecoverPending?t.ConnectionEventReason.OFFLINE_RECOVER:t.ConnectionEventReason.ONLINE;this.offlineRecoverPending=!1,this.resumeReconnect(s)}handleOffline(){e.logger.warn("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.stopHeartbeat(),this.closeWebSocket(t.ConnectionEventReason.OFFLINE,!0),e.logger.warn("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(this.terminalDisconnectError)return void e.logger.warn("Foreground recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void e.logger.warn("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const s=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==s)return;this.closeWebSocket(t.ConnectionEventReason.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(t.ConnectionEventReason.HEARTBEAT_FAILED)}}catch(r){if(e.logger.warn("Foreground heartbeat check failed",r),this.reconnectInProgress||this.websocket!==s)return;this.closeWebSocket(t.ConnectionEventReason.HEARTBEAT_FAILED,!0,!0),this.resumeReconnect(t.ConnectionEventReason.HEARTBEAT_FAILED)}}resumeReconnect(s){if(this.terminalDisconnectError)e.logger.warn("Reconnect recovery skipped",{guard:"terminal-disconnect",reason:s,...this.getReconnectDiagnostic()});else if(this.isLoggedIn)return this.reconnectTask||this.reconnectInProgress?(this.pendingReconnectReason=s,void e.logger.warn("Reconnect recovery queued",{guard:"reconnect-in-progress",reason:s,...this.getReconnectDiagnostic()})):void(this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),e.logger.warn("Reconnect recovery requested",{reason:s,...this.getReconnectDiagnostic()}),this.triggerReconnect(s)))}handleSendTimeout(s){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||s.reason===t.ConnectionEventReason.SEND_TIMEOUT&&e.logger.warn("Message send timeout received without reconnect",s))}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(t){if(!(t instanceof e.ConnectionError))return!1;const s=t.details;if(!s||"object"!=typeof s)return!1;return!1===s.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(ht(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?.(Do("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 e.ConnectionError("Login timeout",{code:e.ERROR_CODES.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",retryable:!0}})}async waitForReconnectDelay(){const t=this.connectionRetry.getRetryDelay(),s=this.resolveLoginStageTimeout(t);if(s<=0)throw this.requireLoginTimeoutError();e.logger.warn("Reconnect retry scheduled",{delayMs:Math.round(s),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise((e,t)=>{this.reconnectDelayReject=e=>{this.reconnectDelayReject=null,t(e)},this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,this.reconnectDelayReject=null,e()},s)})}buildConnectionEventPayload(t,s){const r=this.connection.error instanceof e.ConnectionError?this.connection.error:void 0;return{state:t,reason:s,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,s){if(e===t.ConnectionStatus.DISCONNECTED&&!this.hasEverConnected)return;if(e===t.ConnectionStatus.RECONNECT_FAILED&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t.ConnectionStatus.DISCONNECTED||e===t.ConnectionStatus.RECONNECT_FAILED))return;const r=this.buildConnectionEventPayload(e,s),n=this.connectionEventNormalizer.normalize(e,r);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(s,r,n,o=!1){const i=this.connection.status!==s;(i||o)&&(i&&(this.connection.status=s,this.connection.lastConnectedAt=s===t.ConnectionStatus.CONNECTED?Date.now():void 0),n&&this.dispatchConnectionEvent(s,r),e.logger.debug("Connection status updated",{status:s,reason:r,attempt:this.reconnectAttempts,forceEmit:o}))}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 r=Math.max(t-s,0),n=s+Math.floor(.8*r);this.tokenLifecycle={token:e,issuedAt:s,expireAt:t,willExpireAt:n,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(n-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(t){if(t&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const s=JSON.parse(t);if(!s||"object"!=typeof s)return void e.logger.warn("Provision auth token has invalid payload");const r=Number(s.expires_in);if(!Number.isFinite(r))return void e.logger.warn("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(s){e.logger.warn("Failed to parse provision auth token expiration",s)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,e.logger.warn("Token will expire"),this.eventHub.dispatch(t.ConnectionEventName.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 s=this.tokenLifecycle;s.expiredEmitted||(s.expiredEmitted=!0,e.logger.warn("Token expired"),this.eventHub.dispatch(t.ConnectionEventName.TOKEN_EXPIRED,void 0))}isTokenExpiredConnectionError(t){return t instanceof e.ConnectionError&&t.code===e.ERROR_CODES.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(s){e.logger.warn("Connection closing because token expired",{source:s}),this.connection.error=new e.ConnectionError("Token expired",{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:s,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(t.ConnectionEventReason.TOKEN_EXPIRED,!0,!0),this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.TOKEN_EXPIRED,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(t.ConnectionEventReason.HEARTBEAT_FAILED)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,e.HEARTBEAT_TIMEOUT)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(s){if(!this.reconnectInProgress)if(this.connection.status!==t.ConnectionStatus.CONNECTED&&this.connection.status!==t.ConnectionStatus.CONNECTING){this.isLoginPhase=!0,this.activeLoginDeadline=s??null,this.terminalDisconnectError=null,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(t.ConnectionEventReason.LOGIN,!0),this.isLoggedIn=!0}catch(r){throw this.isLoggedIn=!1,r instanceof e.ConnectionError&&r.code===e.ERROR_CODES.CONNECTION_LOGIN_TIMEOUT&&"login"===r.details?.stage&&(this.cancelActiveConnectionAttempt(),this.closeWebSocket(t.ConnectionEventReason.ERROR,!1,!1),this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.ERROR,!1)),r}finally{this.isLoginPhase=!1,this.activeLoginDeadline=null}}else e.logger.warn("Connection already established or connecting")}async connectWithRetry(s,r){if(e.logger.warn("Reconnect flow requested",{reason:s,throwOnFailure:r,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void e.logger.warn("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:s,...this.getReconnectDiagnostic()});if(this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket)return;if(this.reconnectPaused)return void e.logger.warn("Reconnect flow skipped",{guard:"reconnect-paused",reason:s,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let n=null,o=null,i=null;const a=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),e.logger.warn("Reconnect flow started",{reason:s,throwOnFailure:r,maxAttempts:a,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<a;){if(this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(!this.isLoginPhase&&(this.reconnectPaused||!this.isOnline||!this.isLoggedIn)){i=Do("ws");break}this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const r=this.isLoginPhase?t.ConnectionStatus.CONNECTING:t.ConnectionStatus.RECONNECTING;e.logger.warn("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:a,reason:s,nextStatus:r,...this.getReconnectDiagnostic()}),this.updateStatus(r,s,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(s)}catch(c){if(n=c,this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(wo(c)){i=c,e.logger.warn("Reconnect attempt cancelled",{attempt:this.reconnectAttempts,reason:s,...this.getReconnectDiagnostic()});break}if(e.logger.warn("Connection attempt failed",{attempt:this.reconnectAttempts,reason:s,error:n}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(n))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(n)){o=n;break}}if(this.connectionRetry.getAttemptCount()>=a)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){e.logger.warn("Reconnect retry loop interrupted",{reason:s,attempt:this.reconnectAttempts,maxAttempts:a,...this.getReconnectDiagnostic()});break}try{await this.waitForReconnectDelay()}catch(c){if(!wo(c))throw c;i=c,e.logger.warn("Reconnect retry delay cancelled",{reason:s,attempt:this.reconnectAttempts,...this.getReconnectDiagnostic()});break}}if(i){if(r)throw i;return}if(o){if(this.connection.error=o,r)throw this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.ERROR,!1),o;return this.reconnectPaused=!0,void this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.ERROR,!0)}if(r)throw this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.ERROR,!1),n??new e.ConnectionError("Connection failed",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,e.logger.warn("Reconnect attempts exhausted",{reason:s,attempt:this.reconnectAttempts,maxAttempts:a,lastError:n,...this.getReconnectDiagnostic()}),this.updateStatus(t.ConnectionStatus.RECONNECT_FAILED,t.ConnectionEventReason.LIMIT,!0)}finally{this.reconnectInProgress=!1,e.logger.warn("Reconnect flow finished",{reason:s,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.cancelActiveConnectionAttempt(),this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(t.ConnectionEventReason.RECONNECT,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(s){this.updateStatus(t.ConnectionStatus.CONNECTED,s,!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),e.logger.warn("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}triggerReconnect(s){if(e.logger.warn("Reconnect trigger received",{reason:s,...this.getReconnectDiagnostic()}),this.terminalDisconnectError)return e.logger.warn("Reconnect trigger skipped",{guard:"terminal-disconnect",reason:s,...this.getReconnectDiagnostic()}),Promise.resolve();if(!this.isLoggedIn)return e.logger.warn("Reconnect trigger skipped",{guard:"not-logged-in",reason:s,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectTask)return e.logger.warn("Reconnect task reused",{reason:s,...this.getReconnectDiagnostic()}),this.reconnectTask;if(this.reconnectInProgress)return e.logger.warn("Reconnect trigger skipped",{guard:"reconnect-in-progress-without-task",reason:s,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectPaused)return e.logger.warn("Reconnect trigger skipped",{guard:"reconnect-paused",reason:s,...this.getReconnectDiagnostic()}),Promise.resolve();this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket&&this.closeWebSocket(s,!0,!0);const r=this.connectWithRetry(s,!1).finally(()=>(this.reconnectTask===r&&(this.reconnectTask=null),this.startPendingReconnectIfNeeded()??void 0));return this.reconnectTask=r,r}recoverConnectionForSend(){return this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket?Promise.resolve():this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.isLoginPhase||0===this.config.autoReconnectNumMax?(e.logger.warn("Send connection recovery skipped",{guard:"connection-not-recoverable",...this.getReconnectDiagnostic()}),Promise.resolve()):this.reconnectTask?(e.logger.warn("Send connection recovery reused",this.getReconnectDiagnostic()),this.reconnectTask):(this.reconnectPaused=!1,this.resetReconnectState(),e.logger.warn("Send connection recovery requested",this.getReconnectDiagnostic()),this.triggerReconnect(t.ConnectionEventReason.RECONNECT))}startPendingReconnectIfNeeded(){const s=this.pendingReconnectReason;return this.pendingReconnectReason=null,!s||null!==this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.connection.status===t.ConnectionStatus.CONNECTED&&this.websocket?null:(this.reconnectPaused=!1,this.resetReconnectState(),e.logger.warn("Queued reconnect recovery started",{reason:s,...this.getReconnectDiagnostic()}),this.triggerReconnect(s))}handleDisconnection(s){e.logger.warn("Connection disconnection handled",{reason:s,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t.ConnectionStatus.DISCONNECTED,s,!0),s!==t.ConnectionEventReason.TOKEN_EXPIRED&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(s))}closeWebSocket(e,s,r=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),r&&this.updateStatus(t.ConnectionStatus.DISCONNECTED,e,s)):r&&this.updateStatus(t.ConnectionStatus.DISCONNECTED,e,s)}createWebSocketConnection(){const s=this.resolveLoginStageTimeout(this.config.connectTimeout);return s<=0?Promise.reject(this.requireLoginTimeoutError()):new Promise((r,n)=>{const o=++this.connectionAttemptGeneration,i=this.pickNextServerUrl();e.logger.debug("WebSocket connecting",{url:i}),this.clearSocketListeners();let a=!1,c=!1,d=null;const l=()=>{this.connectionAttemptGeneration===o&&(this.activeConnectionAttemptCancel=null)},u=e=>{a||(a=!0,d&&(clearTimeout(d),d=null),l(),n(e))};this.activeConnectionAttemptCancel=()=>{const e=Do(c?"provision":"ws");this.rejectPendingProvision(e),u(e)},d=setTimeout(()=>{e.logger.warn("WebSocket connection attempt timed out",{url:i,connectTimeout:s,...this.getReconnectDiagnostic()}),u(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new e.ConnectionError("Connection timeout",{code:e.ERROR_CODES.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},s),this.socketAdapter.connect({url:i,timeoutMs:s}).then(s=>{if(a||o!==this.connectionAttemptGeneration||this.reconnectPaused)return e.logger.warn("WebSocket connection result discarded",{url:i,cancelled:a||o!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),s.close(),void u(Do("ws"));d&&(clearTimeout(d),d=null),this.websocket=s,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(s,this.socketGeneration),c=!0,this.startProvision().then(()=>{if(this.resetProvisionHandlers(),a||o!==this.connectionAttemptGeneration||this.reconnectPaused)return e.logger.warn("Provision result discarded",{url:i,cancelled:a||o!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),this.closeWebSocket(t.ConnectionEventReason.ERROR,!1,!1),void u(Do("provision"));a||(a=!0,d&&(clearTimeout(d),d=null),l(),r())}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(t.ConnectionEventReason.ERROR,!1,!1),u(e instanceof Error?e:new Error(String(e)))})}).catch(s=>{if(a)return;const r=s instanceof e.ConnectionError?s:new e.ConnectionError("Failed to create WebSocket",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:s instanceof Error?s.message:String(s)}});this.handleConnectionError(r,t.ConnectionEventReason.ERROR),u(r)})}).catch(s=>{if(s instanceof e.ConnectionError)throw s;const r=new e.ConnectionError("Failed to create WebSocket",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:s instanceof Error?s.message:String(s)}});throw this.handleConnectionError(r,t.ConnectionEventReason.ERROR),r})}cancelActiveConnectionAttempt(){this.activeConnectionAttemptCancel?.()}handleWebSocketClose(s){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(e.logger.warn("WebSocket closed",{code:s.code,reason:s.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(t.ConnectionEventReason.CLOSE))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new e.ConnectionError("Provision interrupted",{code:e.ERROR_CODES.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(t,s){e.logger.error("Connection error:",t),this.connection.error=t,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null);const r=t instanceof e.ConnectionError?t:new e.ConnectionError(t.message,{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",retryable:!0}});if(this.rejectPendingProvision(r)||this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(s)}handleTerminalConnectionError(s,r){if(e.logger.warn("Terminal connection error received",{code:s.code,message:s.message,details:s.details}),this.connection.error=s,this.terminalDisconnectError=s,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(t.ConnectionStatus.DISCONNECTED,r,!0,!0)}async handleWebSocketMessage(s,r){try{if(r!==this.socketGeneration)return;e.logger.debug("WebSocket message received",{dataType:typeof s});const o=await this.msyncCodec.normalizeIncoming(s);if(r!==this.socketGeneration)return;if(e.logger.debug("handleWebSocketMessage data",{length:o.length}),!o.length)return;const i=this.msyncCodec.decompressIncoming(o);if(!i){const s=null!==this.provisionReject;return e.logger.error("Failed to decompress mSync payload, closing connection",{stage:s?"provision":"connected"}),void(s?(this.rejectPendingProvision(new e.ConnectionError("Failed to decompress Provision payload",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(t.ConnectionEventReason.ERROR,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(i))return void e.logger.debug("Ignore server normal close payload",{length:i.length});let a=null;try{a=this.msyncCodec.decodeMsync(i)}catch(n){const t=n instanceof Error?n:new Error("Failed to decode mSync payload");if(t instanceof RangeError)return void e.logger.warn("Discard invalid mSync payload",{length:i.length,message:t.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 e.logger.warn("Invalid mSync payload signature",{length:i.length,prefixHex:Array.from(i.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),t}switch(this.heartbeatManager.markAlive(),e.logger.debug("handleWebSocketMessage decoded",{command:a.command}),a.command){case B:this.handleProvisionMessage(a.payload);break;case G:this.handleLogoutMessage(a.payload);break;case F:this.handleNoticeMessage(a.payload);break;case x:this.handleUnreadMessage(a.payload);break;case k:this.handleSyncMessage(a.payload)}}catch(n){const s=n instanceof Error?n:new Error("Failed to handle mSync payload");e.logger.error("Failed to handle mSync payload",s),this.handleConnectionError(s,t.ConnectionEventReason.ERROR)}}startProvision(){const t=this.resolveLoginStageTimeout(e.PROVISION_TIMEOUT);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 e.ConnectionError("Provision timeout",{code:e.ERROR_CODES.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},t);try{const t=this.msyncCodec.encodeProvision();e.logger.debug("startProvision provision",{length:t.length}),this.sendMsyncPayload(t)}catch{this.provisionReject?.(new e.ConnectionError("Provision send failed",{code:e.ERROR_CODES.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{e.logger.warn("Provision rejected",{statusCode:s.statusCode,reason:s.reason});const t=dt(s.statusCode,s.reason),r=t.code===e.ERROR_CODES.UNKNOWN?e.ERROR_CODES.CONNECTION_PROVISION_REJECTED:t.code;this.provisionReject?.(new e.ConnectionError("Provision rejected",{code:r,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,r=!!t&&this.isSelfQueue(t),n=!!t&&this.isQueueInList(t);t&&s&&(r||n||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(t){const{queues:s}=this.msyncCodec.decodeUnread(t),r=s.filter(e=>this.getQueueId(e));if(r.length){r.length!==s.length&&e.logger.warn("Unread queues without usable identity were ignored",{ignoredCount:s.length-r.length}),this.startOfflineMessageSync(r);for(const e of r)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(s){const r=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(s));if(r)return void this.handleTerminalConnectionError(r,t.ConnectionEventReason.ERROR);if(!this.messageReceiver)return;const n=this.messageReceiver.handleSyncPayload(s);if(e.logger.debug("handleSyncMessage result",{result:n}),!n)return;(void 0!==n.queue||void 0!==n.nextKey||void 0!==n.isLast)&&this.handleSyncQueueState(n)}handleSyncQueueState(t){e.logger.debug("[QueueSync] handleSyncQueueState",{isLast:t.isLast,nextKey:t.nextKey,queueName:t.queue?this.getQueueName(t.queue):null,queueId:t.queue?this.getQueueId(t.queue):null,queuesLength:this.queues.length});const s=this.resolveSyncQueueState(t);if(!s)return t.queue&&t.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):t.queue&&t.nextKey?void this.sendLastSession(t.queue,t.nextKey):void 0;const{queue:r,queueId:n}=s;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(n)){const e=this.offlineMessageQueueCounts.get(n)??0;this.offlineMessageQueueCounts.set(n,e+t.messages.length),this.offlineMessageTotalCount+=t.messages.length}const o=t.nextKey;if(t.isLast)return this.finishOfflineMessageQueue(n),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(o){if(o!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=o,this.currentQueueId=n,this.currentQueue=r,void this.sendLastSession(r,o);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(t){const s=t.queue&&"object"==typeof t.queue?t.queue:void 0,r=s?this.getQueueName(s):null,n=s?this.getQueueId(s):null,o=void 0!==s&&null!==n&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,s)));if(s&&n&&o)return{queue:s,queueId:n};const i=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=i??a??this.queues[0],d=c?this.getQueueName(c):null,l=c?this.getQueueId(c):null;return c&&l?(e.logger.warn("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:r,responseQueueId:n,fallbackQueueName:d,fallbackQueueId:l,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:t.isLast,hasNextKey:Boolean(t.nextKey)}),{queue:c,queueId:l}):null}handleLogoutMessage(t){const s=this.msyncCodec.decodeLogout(t);e.logger.warn("Logout message received",s)}resolveStatisticDisconnectError(t){for(const s of t)switch(s.operation){case 1:return new e.ConnectionError("User has been removed",{code:e.ERROR_CODES.USER_REMOVED,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 2:return new e.ConnectionError("The user is already logged on another device",{code:e.ERROR_CODES.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:s.operation,retryable:!1,...s.reason?{loginInfoCustomExt:s.reason}:{}}});case 3:return new e.ConnectionError("The user was kicked by changing password",{code:e.ERROR_CODES.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:s.operation,retryable:!1}});case 4:return new e.ConnectionError("The user was kicked by other device",{code:e.ERROR_CODES.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(t.ConnectionEventReason.CLOSE,!0,!0),this.updateStatus(t.ConnectionStatus.DISCONNECTED,t.ConnectionEventReason.CLOSE,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),e.logger.warn("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){return Cr(e.socketAdapter)}attachSocketListeners(s,r){this.clearSocketListeners(),this.socketDisposers=[s.onMessage(e=>{this.websocket===s&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(e,r)))}),s.onError(()=>{if(this.websocket!==s)return;e.logger.warn("WebSocket error",{stage:"ws"});const r=new e.ConnectionError("WebSocket connection error",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(r,t.ConnectionEventReason.ERROR)}),s.onClose(e=>{this.websocket===s&&this.handleWebSocketClose(e)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(t){if(this.websocket&&this.websocket.readyState===e.SOCKET_READY_STATE.OPEN)try{const s=this.msyncCodec.prepareOutgoing(t);e.logger.debug("WebSocket send payload",{length:s.length}),Promise.resolve(this.websocket.send(s)).catch(t=>{e.logger.error("Failed to send mSync payload",t),this.websocket?.close()})}catch(s){e.logger.error("Failed to send mSync payload",s),this.websocket?.close()}}sendBackqueue(t){this.currentQueue=t,this.currentQueueId=this.getQueueId(t),this.nextKey=null;const s=this.msyncCodec.encodeBackQueue(t);e.logger.debug("sendBackqueue payload",{length:s.length}),this.sendMsyncPayload(s)}sendLastSession(t,s){e.logger.debug("sendLastSession queue",{queueName:this.getQueueName(t),nextKey:s});const r=this.msyncCodec.encodeLastSession(t,s);this.sendMsyncPayload(r)}sendNextQueue(){e.logger.debug("sendNextQueue queues",{size:this.queues.length});const t=this.queues[0];t&&this.sendBackqueue(t)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(s){const r=new Set;for(const e of s){const t=this.getQueueId(e);t&&r.add(t)}if(0!==r.size){for(const e of r)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.startDataReportOperation({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of r){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(t.ConnectionEventName.OFFLINE_MESSAGE_SYNC_START,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const s=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:s}),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(t.ConnectionEventName.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),r=this.msyncCodec.getContext();return t===r.userId&&s===r.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"),r=this.getQueueResource(e);if(s)return`domain:${s}|resource:${r??""}`;if(r)return`resource:${r}`;const n=this.getQueueField(e,"appKey");return n?`appKey:${n}`: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),r=this.getQueueId(t);return null!==s&&s===r}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 Uo=new Uint8Array([99,109]),Po=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ko=e=>Array.isArray(e)&&e.every(Po),xo=e=>"string"==typeof e?e:void 0,Fo=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bo=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},Go=(t,s)=>{const r=t[s],n=t[s+1],o=t[s+2],i=t[s+3];if("number"!=typeof r||"number"!=typeof n||"number"!=typeof o||"number"!=typeof i)throw new e.MessageReceiveError("Combine payload length header is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});return r<<24|n<<16|o<<8|i},qo=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},Ko=(e,t)=>{const s=Mr().lookupType(e).decode(t);if(!Po(s))throw new Error(`${e} decoded result is invalid`);return s},Vo=e=>Po(e)&&"string"==typeof e.name?e.name:"",zo=(t,s,r)=>{const n=(ko(t.contents)?t.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const o=(t=>{const s=Fo(t.type)??Y,r=Boolean(xo(t.remotePath))||Boolean(xo(t.title))||Boolean(xo(t.summary))||(Fo(t.combineLevel)??0)>0,n=s===Y&&0===t.subType&&r;if(s===ne||n){const e=Fo(t.combineLevel)??0;return{type:"combine",body:{title:xo(t.title)??"",summary:xo(t.summary)??"",filename:xo(t.displayName)??"combine",filetype:"application/octet-stream",url:xo(t.remotePath),secret:xo(t.secretKey),fileLength:Fo(t.fileLength),combineLevel:e},combineLevel:e}}if(s===Y)return{type:"text",body:{content:xo(t.text)??""}};if(s===se)return{type:"cmd",body:{action:xo(t.action)??""}};if(s===re){const e=Fr(ko(t.customExts)?t.customExts:void 0);return{type:"custom",body:{event:xo(t.customEvent)??"",params:e}}}if(s===Z)return{type:"location",body:{latitude:Fo(t.latitude)??0,longitude:Fo(t.longitude)??0,address:xo(t.address),buildingName:xo(t.buildingName)}};if(s===J){const s=Po(t.size)?t.size:{},r=xo(t.remotePath)??"",n=e.deriveImageUrls(r),o=xo(t.thumbnailRemotePath),i=e.fromProtocolImageType(t.imageType)===e.IMAGE_TYPE_ORIGINAL;return{type:"image",body:{localUrl:"",filename:xo(t.displayName)??"image",filetype:"application/octet-stream",width:Fo(s.width)??0,height:Fo(s.height)??0,isGif:1===t.subType,isOriginalImage:i,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:xo(t.secretKey),fileLength:Fo(t.fileLength),thumbnailUrl:o??n.thumbnailUrl}}}if(s===X){const e=Po(t.size)?t.size:{};return{type:"video",body:{url:xo(t.remotePath)??"",filename:xo(t.displayName)??"video",filetype:"application/octet-stream",duration:Fo(t.duration)??0,width:Fo(e.width),height:Fo(e.height),secret:xo(t.secretKey),fileLength:Fo(t.fileLength),thumbnailUrl:xo(t.thumbnailRemotePath)}}}if(s===ee)return{type:"voice",body:{url:xo(t.remotePath)??"",filename:xo(t.displayName)??"voice",filetype:"application/octet-stream",duration:Fo(t.duration)??0,secret:xo(t.secretKey),fileLength:Fo(t.fileLength)}};if(s===te)return{type:"file",body:{url:xo(t.remotePath)??"",filename:xo(t.displayName)??"file",filetype:"application/octet-stream",secret:xo(t.secretKey),fileLength:Fo(t.fileLength)}};return null})(n);if(!o)throw new Error("MessageBody content type is unsupported");const i=Vo(t.from)||Vo(r?.from)||`unknown-${s}`,a=Vo(t.to)||Vo(r?.to)||`unknown-${s}`,c=(d=t.type)===V?"groupChat":d===z?"chatRoom":"singleChat";var d;const l=a||i,u=Number(kr(r?.timestamp))||Date.now(),h=Fr(ko(t.ext)?t.ext:void 0),p={msgServerId:kr(r?.id),msgLocalId:"",type:o.type,sender:{userId:i},conversationId:l,conversationType:c,timestamp:u,body:o.body,ext:h};return"number"==typeof o.combineLevel&&(p.body.combineLevel=o.combineLevel),p},Ho=(e,t)=>{const s=[];try{const n=Ko("easemob.pb.Meta",e),o=(r=n.payload)instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):void 0;if(o&&o.length>0){const e=Ko("easemob.pb.MessageBody",o);return zo(e,t,n)}s.push("Meta payload is empty")}catch(n){s.push(n instanceof Error?n.message:String(n))}var r;try{const s=Ko("easemob.pb.MessageBody",e);return zo(s,t)}catch(n){s.push(n instanceof Error?n.message:String(n))}try{const s=Ko("easemob.pb.MessageBody.Content",e);return zo({type:K,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[s],ext:[]},t)}catch(n){s.push(n instanceof Error?n.message:String(n))}throw new Error(s.join("; "))},jo=(t,s)=>{const r=ht(t);try{const t=JSON.parse(r);if(!Po(t))throw new e.MessageReceiveError("Combine payload item is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{index:s}});return t}catch(n){if(n instanceof e.MessageReceiveError)throw n;try{return Ho(t,s)}catch(o){throw new e.MessageReceiveError("Combine payload item parse failed",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{index:s,cause:n instanceof Error?n.message:String(n),protobufCause:o instanceof Error?o.message:String(o)}})}}},Wo=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Qo{constructor(t,s,r,n){this.websocket=null,this.pendingMessages=new Map,this.ackTimeout=e.MESSAGE_TIMEOUT,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=s,this.eventHub=r,this.msyncCodec=t,this.attachmentUploader=n??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(t,s){const r=this.msyncCodec.toProtocolId(t.msgLocalId);if(P(t))throw new e.MessageSendError("Stream message send is not supported",{code:e.ERROR_CODES.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==e.SOCKET_READY_STATE.OPEN){const s=this.msyncCodec.toProtocolId(t.msgLocalId);throw new e.MessageSendError("WebSocket is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:s,retryable:!0}})}let n={...t,sendStatus:"sending"};ln(t,n),e.logger.debug("Message send queued",{msgLocalId:t.msgLocalId,protocolId:r,type:t.type,conversationType:t.conversationType,conversationId:t.conversationId});try{const e="combine"===n.type?this.prepareCombineMessage(n):n,t={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,s):e,sendStatus:"sending"};ln(n,t),n=t,s?.onSending?.(t);const r=await this.doSendMessage(t);return s?.onSuccess?.(r),r}catch(o){const e={...n,sendStatus:"failed"};throw ln(n,e),s?.onFailed?.(e,o instanceof Error?o:new Error(String(o))),o}}async sendAction(t,s){const r=this.msyncCodec.toProtocolId(`${t.kind}:${t.messageId??t.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===t.kind&&e.logger.debug("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:r,conversationId:t.conversationId,conversationType:t.conversationType,sendToPeer:t.sendToPeer,clearAllUnreadMessageCount:t.clearAllUnreadMessageCount});const n=this.msyncCodec.encodeActionMessage(t,r);"clearAllConversationUnreadMessageCount"===t.kind&&e.logger.debug("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:r,payloadBytes:n.byteLength});const o="recall"===t.kind?"MSYNC_RECALLMESSAGE":"update"===t.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${t.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(r,n,s,this.createPendingDataReport({category:"message",operationName:o,operationType:"MESSAGE",requestName:o,msgId:t.messageId,messageType:Wo(t.conversationType)}))}async sendChatRoomOperation(e,t){const s=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),r=this.msyncCodec.encodeChatRoomOperation(e,s),n="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(s,r,t,this.createPendingDataReport({category:"chatroom",operationName:n,operationType:"CHATROOM",requestName:n,msgId:e.chatRoomId}))}async doSendMessage(t){const s=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:t.msgLocalId,messageType:Wo(t.conversationType)});return new Promise((r,n)=>{const o=this.msyncCodec.toProtocolId(t.msgLocalId),i=setTimeout(()=>{this.pendingMessages.delete(o),this.finishPendingDataReport(s,{code:e.ERROR_CODES.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),n(new e.MessageSendError("Message ACK timeout",{code:e.ERROR_CODES.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(o,{kind:"message",message:t,protocolId:o,timeoutId:i,resolve:e=>{clearTimeout(i),r(e)},reject:e=>{clearTimeout(i),n(e)},report:s});try{if(!this.websocket||this.websocket.readyState!==e.SOCKET_READY_STATE.OPEN)throw new e.MessageSendError("WebSocket is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(t,o),a=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(a)).catch(r=>{const a=r instanceof Error?r.message:String(r);this.pendingMessages.delete(o),clearTimeout(i),this.finishPendingDataReport(s,{code:-1,success:!1,description:a}),e.logger.warn("Message send socket failure",{msgLocalId:t.msgLocalId,protocolId:o,websocketReadyState:this.websocket?.readyState??null,cause:a}),n(new e.MessageSendError(`WebSocket send failed: ${a}`,{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0,cause:a}}))}),e.logger.debug("Message sent",{msgLocalId:t.msgLocalId,protocolId:o})}catch(a){if(this.pendingMessages.delete(o),clearTimeout(i),this.finishPendingDataReport(s,{code:a instanceof e.MessageSendError?a.code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof e.MessageSendError)throw a;throw new e.MessageSendError("Message encode failed",{code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,details:{msgLocalId:t.msgLocalId,protocolId:o,retryable:!0}})}})}async sendProtocolPayload(t,s,r,n){return new Promise((o,i)=>{const a=setTimeout(()=>{this.pendingMessages.delete(t),this.finishPendingDataReport(n,{code:e.ERROR_CODES.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),i(new e.MessageSendError("Message ACK timeout",{code:e.ERROR_CODES.MESSAGE_ACK_TIMEOUT,details:{protocolId:t,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(t,{kind:"action",protocolId:t,timeoutId:a,createAckError:r,resolve:o,reject:i,report:n});try{if(!this.websocket||this.websocket.readyState!==e.SOCKET_READY_STATE.OPEN)throw new e.MessageSendError("WebSocket is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0}});const r=this.msyncCodec.prepareOutgoing(s);Promise.resolve(this.websocket.send(r)).catch(s=>{const r=s instanceof Error?s.message:String(s);this.pendingMessages.delete(t),clearTimeout(a),this.finishPendingDataReport(n,{code:-1,success:!1,description:r}),i(new e.MessageSendError(`WebSocket action send failed: ${r}`,{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{protocolId:t,retryable:!0,cause:r}}))})}catch(c){if(this.pendingMessages.delete(t),clearTimeout(a),this.finishPendingDataReport(n,{code:c instanceof e.MessageSendError?c.code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,success:!1,description:c instanceof Error?c.message:String(c)}),c instanceof e.MessageSendError)throw c;i(new e.MessageSendError("Message encode failed",{code:e.ERROR_CODES.MESSAGE_ENCODE_FAILED,details:{protocolId:t,retryable:!1}}))}})}prepareCombineMessage(s){const r=s.body,n=r.messageList??[];t.validateCombineMessageList(n);const o=t.calculateCombineLevel(n);t.ensureCombineLevel(o);const i=((t,s)=>{try{const r=t.map((t,r)=>{const n=s(t,r);if(0===n.length)throw new e.MessageSendError("Combine payload item encode failed",{code:e.ERROR_CODES.COMBINE_ENCODE_FAILED,details:{index:r}});return n}),n=Uo.length+r.reduce((e,t)=>e+4+t.length,0)+1,o=new Uint8Array(n);let i=0;o.set(Uo,i),i+=Uo.length;for(const e of r){const t=Bo(e.length);o.set(t,i),i+=t.length,o.set(e,i),i+=e.length}const a=qo(o.subarray(0,o.length-1));return o[o.length-1]=a,o}catch(r){if(r instanceof e.MessageSendError)throw r;throw new e.MessageSendError("Combine payload encode failed",{code:e.ERROR_CODES.COMBINE_ENCODE_FAILED,details:{cause:r instanceof Error?r.message:String(r)}})}})(n,e=>this.msyncCodec.encodeCombineMessageMeta(e)),a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i);const c=new File([a],r.filename||"combine",{type:r.filetype||"application/octet-stream"}),d=t.createLocalFileUrl(c);if(!d&&!this.attachmentUploader)throw new e.MessageSendError("Combine payload local url generation failed",{code:e.ERROR_CODES.COMBINE_ENCODE_FAILED});t.attachmentFileStore.set(s.msgLocalId,c);const l={...s,body:{...r,combineLevel:o,fileLength:i.byteLength,filename:r.filename||"combine",filetype:r.filetype||"application/octet-stream",url:d??r.url}};return ln(s,l),t.copyCombineCompatibleTextSidecar(s,l),l}handleAck(s,r,n,o){const i=this.pendingMessages.get(s);if(!i)return void e.logger.debug("Received ACK without a tracked pending message",{protocolId:s});if("action"===i.kind)return this.pendingMessages.delete(s),this.finishPendingDataReport(i.report,{code:200,success:!0}),void i.resolve({protocolId:s,serverId:r??"",statusCode:0,chatRoomInfo:o});const a={...i.message,...this.resolveReplacedMessage(i.message,n),sendStatus:"sent",msgServerId:r||n?.msgServerId||i.message.msgServerId};ln(i.message,a),this.pendingMessages.delete(s),this.finishPendingDataReport(i.report,{code:200,success:!0}),"image"!==a.type&&"video"!==a.type&&"voice"!==a.type&&"file"!==a.type&&"combine"!==a.type||t.attachmentFileStore.delete(a.msgLocalId),e.logger.debug("Message ACK matched",{protocolId:s,msgLocalId:a.msgLocalId,msgServerId:a.msgServerId??null,type:a.type,conversationType:a.conversationType,conversationId:a.conversationId}),this.eventHub.dispatch(t.InternalEventName.MESSAGE_SENT,a),i.resolve(a)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(t,s){const r=this.pendingMessages.get(t);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(t),this.finishPendingDataReport(r.report,{code:s instanceof e.MessageSendError?s.code:-1,success:!1,description:s.message}),void r.reject(s);const n={...r.message,sendStatus:"failed"};ln(r.message,n),this.pendingMessages.delete(t),this.finishPendingDataReport(r.report,{code:s instanceof e.MessageSendError?s.code:-1,success:!1,description:s.message}),e.logger.warn("Message send failed after ACK/error",{protocolId:t,msgLocalId:n.msgLocalId,type:n.type,conversationType:n.conversationType,conversationId:n.conversationId,error:s.message}),r.reject(s)}handleAckFailure(e,t,s,r){const n=this.pendingMessages.get(e);if(n)return"action"===n.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t,success:!1,description:s??r.message}),void n.reject(n.createAckError?.(t,s)??r)):void this.handleSendError(e,r)}setWebSocket(e){this.websocket=e}destroy(){for(const[t,s]of this.pendingMessages)clearTimeout(s.timeoutId),this.finishPendingDataReport(s.report,{code:-1,success:!1,description:"Message sender destroyed"}),s.reject(new e.MessageSendError("Message sender destroyed",{code:e.ERROR_CODES.MESSAGE_SENDER_DESTROYED,details:"message"===s.kind?{msgLocalId:s.message.msgLocalId,protocolId:t,retryable:!1}:{protocolId:t,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(t){if(("message"===t.category?this.messageReportCount:this.chatRoomReportCount)>=e.DATA_REPORT_CORRELATION_LIMIT){return void(("message"===t.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(e.logger.warn("DataReport correlation limit reached",{category:t.category}),"message"===t.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const s=e.startDataReportOperation({operationName:t.operationName,operationType:t.operationType,msgId:t.msgId,messageType:t.messageType});if(s)return"message"===t.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:t.category,operation:s,request:s.startRequest({requestName:t.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(t,s){t&&!t.released&&(t.released=!0,t.request.finish(s),t.operation.finish(s),"message"===t.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<e.DATA_REPORT_CORRELATION_LIMIT&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<e.DATA_REPORT_CORRELATION_LIMIT&&(this.chatRoomReportSaturated=!1)))}}class $o{constructor(e){this.sessions=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: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),r=t.stream.seq;return s.chunksBySeq.has(r)?{duplicate:!0,session:s}:(s.chunksBySeq.set(r,t),s.lastActivityTs=Date.now(),t.stream.status!==U.START&&t.stream.status!==U.START_COMPLETED||null!==s.startSeq||(s.startSeq=r),{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 r=[];for(;t.chunksBySeq.has(s);){const e=t.chunksBySeq.get(s);if(!e)break;r.push(e),s+=1}return r}markDispatched(e,t,s){const r=this.sessions.get(e);if(!r)return;const n=t.stream.seq;r.lastDispatchedSeq=Math.max(r.lastDispatchedSeq,n),r.fullText=s,r.chunksBySeq.delete(n)}markCompleted(e,t,s){const r=this.getOrCreate(e);r.completed=!0,r.completedReason=t,r.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,r]of this.sessions)r.lastActivityTs<t&&(t=r.lastActivityTs,e=s);e&&this.sessions.delete(e)}}class Yo{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new $o}handle(t){const s=this.resolveMessageId(t);if(!s)return void e.logger.warn("stream message id missing, skip dispatch");if(this.completedIds.has(s))return void e.logger.debug("stream message already completed, ignore",{msgId:s});if(t.stream.status===U.FULL)return void this.handleFullChunk(s,t);const r=this.cache.get(s);if(r?.completed)return void e.logger.debug("stream session completed, ignore chunk",{msgId:s,seq:t.stream.seq});const{duplicate:n}=this.cache.addChunk(s,t);n?e.logger.debug("stream duplicate chunk ignored",{msgId:s,seq:t.stream.seq}):t.stream.errorType>0?this.dispatchServerError(s,t):this.dispatchSequentialChunks(s)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(t){const s=this.cache.getSequentialChunks(t);if(0!==s.length)for(const e of s){const s=this.cache.get(t);if(!s)return;const r=s.fullText,o=e.stream.deltaText,i=`${r}${o}`,a=e.stream.errorType>0?U.ERROR:e.stream.status,c=this.buildDispatchMessage(e,{status:a,fullText:i,deltaText:o});if(this.eventHub.dispatch(n.ChatEventName.STREAM_MESSAGE,c),this.cache.markDispatched(t,e,i),a===U.START_COMPLETED||a===U.COMPLETED||a===U.ERROR){const e=a===U.ERROR?"timeout_error":"normal";return this.cache.markCompleted(t,e,i),this.cache.clear(t),void this.markCompleted(t)}}else e.logger.debug("stream chunks pending for missing seq",{msgId:t})}handleFullChunk(e,t){const s=this.cache.get(e),r=s?.fullText??"",o=this.resolveFullText(t,r),i=this.resolveDeltaText(r,o,t.stream.deltaText),a=!s||-1===s.lastDispatchedSeq&&0===s.chunksBySeq.size,c=t.stream.errorType>0?U.ERROR:a?U.START_COMPLETED:U.COMPLETED,d=this.buildDispatchMessage(t,{status:c,fullText:o,deltaText:i});this.eventHub.dispatch(n.ChatEventName.STREAM_MESSAGE,d);const l=c===U.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,l,o),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const s=this.cache.get(e),r=s?.fullText??"",o=this.resolveFullText(t,r),i=this.resolveDeltaText(r,o,t.stream.deltaText),a=this.buildDispatchMessage(t,{status:U.ERROR,fullText:o,deltaText:i});this.eventHub.dispatch(n.ChatEventName.STREAM_MESSAGE,a),this.cache.markCompleted(e,"timeout_error",o),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 r=e.body.content;return r&&r.length>=t.length?r:`${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 Jo{constructor(e=100){this.seenIds=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 Xo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Zo{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new Yo(s),this.messageContexts=new Map,this.recentMessageIds=new Jo(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(t){try{e.logger.debug("handleSyncPayload payload",{length:t.length});const s=this.msyncCodec.decodeSync(t);e.logger.debug("handleSyncPayload result",{ack:Boolean(s.ack),messageCount:s.messages.length});const{ack:r,messages:n}=s;s.notifies&&s.notifies.length>0&&this.handleNotifies(s.notifies),r&&(e.logger.debug("Decoded sync ACK",{ok:r.ok,protocolId:r.protocolId,serverId:r.serverId??null,statusCode:r.statusCode??null,reason:r.reason??null,hasReplacedMessage:Boolean(s.replacedMessage)}),this.handleAck(r,s.replacedMessage));for(const e of n)this.dispatchMessage(e);return s}catch(s){e.logger.error("Failed to decode sync payload",s)}return null}handleAck(t,s){if(t.ok)return e.logger.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));e.logger.warn("ACK rejected",{protocolId:t.protocolId,statusCode:t.statusCode,reason:t.reason,hasReplacedMessage:Boolean(s)});const r=((t,s)=>{const r=dt(t,s),n=r.code===e.ERROR_CODES.UNKNOWN?e.ERROR_CODES.MESSAGE_SEND_FAILED:r.code;return{code:n,message:lt[n]??(s?`Message send failed: ${s}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(t.statusCode,t.reason),n=new e.MessageSendError(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,n)}dispatchMessage(t){if(P(t))return void this.streamMessageHandler.handle(t);this.rememberMessageContext(t),this.sendDeliveryAckIfNeeded(t);const s=this.resolveMessageContextId(t);this.recentMessageIds.checkAndRecord(s)?e.logger.debug("Duplicate message ignored",{messageId:s}):(this.eventHub.dispatch(n.ChatEventName.MESSAGE,t),e.logger.debug("Message received",{msgServerId:t.msgServerId}))}sendDeliveryAckIfNeeded(t){if(!this.enableDeliveryReceipt)return;if("singleChat"!==t.conversationType)return;const s=this.msyncCodec.getContext().userId;s&&t.from!==s&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:t.from,conversationType:"singleChat",messageId:t.msgServerId??t.msgLocalId}).catch(t=>{e.logger.warn("Failed to send delivery ack",t)})}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(n.ChatEventName.MESSAGE_READ_RECEIPTS,t)}handleUserInfoNotify(e){const s="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(!s)return;const r=e.data;if(!r||"object"!=typeof r)return;const n=r,o="string"==typeof n.username?n.username:"string"==typeof n.userId?n.userId:"user_metadata_updated"===s?this.msyncCodec.getContext().userId:"",i=n.metadata&&"object"==typeof n.metadata&&!Array.isArray(n.metadata)?n.metadata:null,a="number"==typeof n.lastModified?n.lastModified:"string"==typeof n.lastModified?Number(n.lastModified):Number.NaN;if(!o||!i||!Number.isFinite(a))return;const c={notifyType:s,userId:o,metadata:i,lastModified:a};this.eventHub.dispatch(t.InternalEventName.USER_INFO_NOTIFY,c)}handleContactNotify(t){if(e.logger.debug("[RosterSync] handleContactNotify",{eventName:t.eventName,type:t.type}),"string"!=typeof t.eventName)return;if(t.eventName!==n.ContactEventName.INVITED&&t.eventName!==n.ContactEventName.DELETED&&t.eventName!==n.ContactEventName.ADDED&&t.eventName!==n.ContactEventName.REFUSE&&t.eventName!==n.ContactEventName.AGREED)return;const s=t.data;if(!s||"object"!=typeof s)return;const r=s;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(t.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const s=t,r=Array.isArray(s.values)?s.values:[];if(0===r.length)return;const o=[];for(const n of r){if(!n||"object"!=typeof n)continue;const e=n,t=this.normalizePresenceStatus(e.status),s="string"==typeof e.uid?e.uid:"";s&&o.push({userId:s,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==o.length&&this.eventHub.dispatch(n.PresenceEventName.STATUS_CHANGE,o)}handleGroupNotify(e){const s=e.data;if(!s||"object"!=typeof s)return;const r=s;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(t.InternalEventName.GROUP_NOTIFY,r)}handleChatRoomNotify(e){const s=e.data;if(!s||"object"!=typeof s)return;const r=s;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(t.InternalEventName.CHATROOM_NOTIFY,r)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const s of t){if(!Xo(s)||"string"!=typeof s.messageId)continue;const e=this.resolveReactionConversationContext(s);e&&this.eventHub.dispatch(n.ChatEventName.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(!Xo(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 r="string"==typeof t.ext?t.ext:"",o="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",a="string"==typeof t.id?t.id:"";r&&i&&a&&this.eventHub.dispatch(n.ChatEventName.PINNED_MESSAGE_CHANGED,{messageId:r,conversationId:"chat"===o?i:a,conversationType:"chat"===o?"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(!Xo(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(!Xo(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 r=s[0];if(!r)return null;const n=this.resolveMessageReceiptContext(r,t.conversationId,t.conversationType);if("groupChat"===n.conversationType){const e=new Set(s),r=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!Xo(t))return[];const s=t.messageId,r=t.count;return"string"==typeof s&&e.has(s)&&"number"==typeof r&&Number.isInteger(r)&&r>=0?[{messageId:s,count:r}]:[]}):[];return{messageIds:s,conversationId:n.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:r}}return{messageIds:s,conversationId:n.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!Xo(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(n.ChatEventName.MESSAGE_DELIVERED,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!Xo(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(n.ChatEventName.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(!Xo(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Xo(t.message)||"string"!=typeof t.message.type||!Xo(t.message.body)||!Xo(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Xo(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(n.ChatEventName.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:r,...n}=t;return{...n,content:s}}handleChatThreadNotify(e){const s=e.data;if(!s||"object"!=typeof s)return;const r=s;"onChatThreadChange"===r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(t.InternalEventName.CHAT_THREAD_NOTIFY,r)}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 r=this.messageContexts.get(e);return r||("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:"",r="string"==typeof e.channel_type?e.channel_type:"";if(!t||!s)return null;if("groupChat"===r||"groupchat"===r||"group"===r)return{conversationId:s,conversationType:"groupChat",from:t,to:s};if(""!==r&&"chat"!==r&&"singleChat"!==r)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)Xo(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)!Xo(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 ei=e=>e instanceof Error?e.message:String(e);class ti{constructor(t){this.requestAdapter=e.resolveRequestAdapter(t)}async downloadAndParse(s){const r=s.url.trim();if(!r)throw new e.ValidationError("Combine message url is required",{code:e.ERROR_CODES.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const n="number"==typeof s.maxItems?s.maxItems:t.MAX_COMBINE_MESSAGE_COUNT;t.ensureCombineItemLimit(1,n);const o=e.appendAttachUrlParams(r,s.secret);try{const r=await this.requestAdapter.request({url:o,method:"GET",responseType:"arraybuffer",timeoutMs:s.timeoutMs??15e3,headers:{[e.REQUEST_ID_HEADER]:e.createTraceId()}});if(401===r.status||403===r.status)throw new e.AuthenticationError(401===r.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===r.status?e.ERROR_CODES.AUTH_UNAUTHORIZED:e.ERROR_CODES.AUTH_FORBIDDEN,details:{url:o,httpStatus:r.status}});if(r.status>=400)throw new e.MessageReceiveError("Combine payload download failed",{code:e.ERROR_CODES.COMBINE_DOWNLOAD_FAILED,details:{status:r.status,url:o}});const i=(t=>{if(t.length<Uo.length+1)throw new e.MessageReceiveError("Combine payload is too short",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const s=t.subarray(0,Uo.length);if(s[0]!==Uo[0]||s[1]!==Uo[1])throw new e.MessageReceiveError("Combine payload header is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const r=t.subarray(0,t.length-1),n=qo(r),o=t[t.length-1]??0;if(o!==n)throw new e.MessageReceiveError("Combine payload checksum failed",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{expectedChecksum:n,actualChecksum:o}});const i=[];let a=Uo.length;const c=t.length-1;for(;a<c;){if(a+4>c)throw new e.MessageReceiveError("Combine payload length header is incomplete",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const s=Go(t,a);if(a+=4,s<=0||a+s>c)throw new e.MessageReceiveError("Combine payload item length is invalid",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{itemLength:s}});const r=t.subarray(a,a+s);a+=s;const n=jo(r,i.length);i.push(n)}if(a!==c)throw new e.MessageReceiveError("Combine payload has unexpected trailing bytes",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED,details:{offset:a,expected:c}});return i})((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 ut(t);throw new e.MessageReceiveError("Combine payload response type is invalid",{code:e.ERROR_CODES.COMBINE_DOWNLOAD_FAILED})})(r.data));return t.ensureCombineItemLimit(i.length,n),t.validateCombineMessageList(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 e.ValidationError||i instanceof e.AuthenticationError||i instanceof e.MessageReceiveError)throw i;throw new e.MessageReceiveError("Combine payload download or parse failed",{code:e.ERROR_CODES.COMBINE_DOWNLOAD_FAILED,details:{cause:ei(i),url:o}})}}}const si=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"}},ri=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 ni{constructor(t){this.requestAdapter=e.resolveRequestAdapter(t)}async download(t,s=15e3){if("image"!==t.type&&"video"!==t.type&&"voice"!==t.type&&"file"!==t.type)throw new e.ValidationError("message does not contain downloadable attachment",{code:e.ERROR_CODES.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:r,secret:n}=(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 e.ValidationError("attachment url is required",{code:e.ERROR_CODES.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});let o;try{o=await this.requestAdapter.request({url:e.appendAttachUrlParams(r,n),method:"GET",responseType:"arraybuffer",timeoutMs:s,headers:{[e.REQUEST_ID_HEADER]:e.createTraceId()}})}catch(i){if("object"==typeof i&&null!==i&&i.code===e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY)throw new e.NetworkError("request adapter is required for attachment download");throw i}if(401===o.status)throw new e.AuthenticationError("attachment download unauthorized",{code:e.ERROR_CODES.AUTH_UNAUTHORIZED,details:{url:r,httpStatus:o.status}});if(403===o.status)throw new e.AuthenticationError("attachment download forbidden",{code:e.ERROR_CODES.AUTH_FORBIDDEN,details:{url:r,httpStatus:o.status}});if(404===o.status){const t=("string"==typeof o.data?o.data:"").includes("expired");throw new e.SDKError(t?"attachment file is expired":"attachment not found",t?e.ERROR_CODES.ATTACHMENT_EXPIRED:e.ERROR_CODES.ATTACHMENT_NOT_FOUND)}if(429===o.status)throw new e.SDKError("attachment download rate limited",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED);if(o.status>=400)throw new e.SDKError("attachment download failed",e.ERROR_CODES.FILE_DOWNLOAD_FAILED,{details:{status:o.status,url:r}});return{filename:si(t),mimeType:ri(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 oi=(t,s,r)=>({Authorization:`Bearer ${t}`,Accept:s,[e.REQUEST_ID_HEADER]:e.createTraceId(),...r??{}}),ii=async t=>{const s=oi(t.token,"application/json",t.headers),r=Date.now(),n="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:n,method:t.method,url:t.url});let i=0;e.logger.debug("Upload request start",{operation:t.operation,method:t.method});try{const n=await t.requestAdapter.request({url:t.url,method:t.method,headers:s,responseType:"json",timeoutMs:e.UPLOAD_TIMEOUT});i=n.status;const c=Date.now()-r;if(n.status<200||n.status>=300)throw e.logger.warn("Upload response error",{operation:t.operation,method:t.method,status:n.status,duration:c}),new e.UploadError("Upload request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:n.status}});e.logger.debug("Upload response success",{operation:t.operation,method:t.method,status:n.status,duration:c});const d="string"==typeof(a=n.data)?JSON.parse(a):a;return o?.finish({code:n.status,success:!0}),d}catch(c){if(o?.finish({code:0!==i?i:c instanceof e.UploadError?c.code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,success:!1,description:c instanceof Error?c.message:String(c)}),c instanceof e.UploadError)throw c;throw e.logger.warn("Upload request failed",{operation:t.operation,method:t.method}),new e.UploadError("Upload request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url}})}var a},ai=async t=>{const s=Date.now(),r=t.dataReportOperation?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:t.url});e.logger.debug("Upload part start",{operation:"upload.multipart.part",partNumber:t.partNumber});try{const n=await t.uploadAdapter.upload({url:t.url,method:"PUT",headers:oi(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:e.UPLOAD_TIMEOUT,onProgress:e=>t.onProgress?.(e.loaded)}),o=Date.now()-s;if(n.status<200||n.status>=300)throw new e.UploadError("Upload part failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:t.url,partNumber:t.partNumber,status:n.status,response:n.body}});e.logger.debug("Upload part success",{operation:"upload.multipart.part",partNumber:t.partNumber,duration:o}),r?.finish({code:n.status,success:!0})}catch(n){const s=a.mapUploadAdapterError(n),o=s.details&&"object"==typeof s.details?s.details:void 0;throw r?.finish({code:s.code,success:!1,description:s.message}),e.logger.warn("Upload part failed",{operation:"upload.multipart.part",partNumber:t.partNumber}),new e.UploadError(s.message,{code:s.code,details:{...o,url:t.url,partNumber:t.partNumber}})}},ci=async t=>{if(t.fileSize<=e.MULTIPART_THRESHOLD)throw new e.UploadError("Multipart not required",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:s,file:r,conversationId:n,conversationType:o,fileName:i,fileType:a,fileSize:c,messageType:d,imageType:l,md5:u,width:h,height:p}=t,m=(t=>e.resolveRequestAdapter(t))(s.requestAdapter),g=(t=>{if(t)return t;const s=os();if(s)return s;throw new e.UploadError("Upload adapter is required for multipart upload",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:f,appName:y}=e.parseAppKey(s.appKey),E=`${s.restBaseUrl}/${f}/${y}/sdk/chatfiles/part-upload`;let R;try{R=await ii({url:E,method:"POST",token:s.token,operation:"upload.multipart.init",requestAdapter:m,dataReportOperation:t.dataReportOperation})}catch(D){throw new e.UploadError("Multipart init failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:D,url:E}})}const I=(t=>{const s=t.entities?.[0],r="number"==typeof s?.file_upper_limit?s.file_upper_limit:0,n="number"==typeof s?.part_lower_limit?s.part_lower_limit:e.DEFAULT_PART_SIZE,o="string"==typeof s?.uuid?s.uuid:"";if(!o)throw new e.UploadError("Multipart init failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{response:t}});return{fileMaxSize:r,partMinSize:n,uuid:o}})(R);if(I.fileMaxSize&&c>I.fileMaxSize)throw new e.UploadError("File size exceeds limit",{code:e.ERROR_CODES.UPLOAD_SIZE_EXCEEDED,details:{fileSize:c,maxSize:I.fileMaxSize}});const v=I.partMinSize||e.DEFAULT_PART_SIZE,C=Math.ceil(c/v),S=Array.from({length:C},()=>0),T=`${s.restBaseUrl}/${f}/${y}/sdk/chatfiles/part-upload/${I.uuid}`,A=[],O=(e,s)=>{S[e]=s;const r=S.reduce((e,t)=>e+t,0),n=c?r/c*100:void 0;t.callbacks?.onFileUploadProgress?.({loaded:r,total:c,percent:n})};for(let w=0;w<C;w+=1){const n=w*v,o=Math.min(c,n+v),d=r.slice(n,o),l=String(w+1),u=ai({url:T,token:s.token,partNumber:l,part:d,fileName:i,fileType:a,uploadAdapter:g,onProgress:e=>O(w,e),dataReportOperation:t.dataReportOperation}).finally(()=>{const e=A.indexOf(u);e>=0&&A.splice(e,1)});A.push(u),A.length>=e.MAX_POOL&&await Promise.race(A)}await Promise.all(A);const b=e.toUploadChatType(o),_=e.appendUrlQueryParams(`${s.restBaseUrl}/${f}/${y}/sdk/chatfiles/part-upload/${I.uuid}`,{"restrict-access":"true","chat-type":b,"chat-target":n,"thumbnail-width":t.thumbnailWidth,"thumbnail-height":t.thumbnailHeight,md5:u??"",..."image"===d?{imageType:e.toUploadImageType(l),width:h,height:p}:{}}),M=await ii({url:_,method:"POST",token:s.token,operation:"upload.multipart.complete",requestAdapter:m,dataReportOperation:t.dataReportOperation}),N=e.buildUploadResult({response:M,restBaseUrl:s.restBaseUrl,orgName:f,appName:y,fileType:a,fileName:i,fallbackSize:c,messageType:d,imageType:l,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(N),N},di=async t=>{const{config:s,file:r,conversationId:n,conversationType:o,messageType:i,imageType:c,md5:d,width:l,height:u,fileName:h,fileType:p,fileSize:m}=t,g=(t=>{if(t)return t;const s=os();if(s)return s;throw new e.UploadError("Upload adapter is required for simple upload",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(s.uploadAdapter),{orgName:f,appName:y}=e.parseAppKey(s.appKey),E=e.toUploadChatType(o),R=e.appendUrlQueryParams(`${s.restBaseUrl}/${f}/${y}/chatfiles`,{"chat-type":E,"chat-target":n,md5:d??"",..."image"===i?{imageType:e.toUploadImageType(c),width:l,height:u}:{}}),I=Date.now(),v=t.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:R});e.logger.debug("Upload request start",{operation:"upload.simple",method:"POST",fileSize:m,messageType:i});const C={};let S;void 0!==t.thumbnailWidth&&(C["thumbnail-width"]=String(t.thumbnailWidth)),void 0!==t.thumbnailHeight&&(C["thumbnail-height"]=String(t.thumbnailHeight));try{S=await g.upload({url:R,method:"POST",headers:{"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${s.token}`,[e.REQUEST_ID_HEADER]:e.createTraceId()},source:{sourceType:"web-file",file:r,name:h,mimeType:p,size:m},fields:C,fileFieldName:"file",timeoutMs:e.UPLOAD_TIMEOUT,onProgress:e=>t.callbacks?.onFileUploadProgress?.(e)})}catch(T){const s=a.mapUploadAdapterError(T),r=s.details&&"object"==typeof s.details?s.details:void 0,n=new e.UploadError(s.message,{code:s.code,details:{...r,url:R,...s.code===e.ERROR_CODES.UPLOAD_TIMEOUT?{timeout:e.UPLOAD_TIMEOUT}:{}}});throw v?.finish({code:n.code,success:!1,description:n.message}),n.code===e.ERROR_CODES.UPLOAD_ABORTED?(e.logger.warn("Upload request aborted",{operation:"upload.simple"}),t.callbacks?.onFileUploadCanceled?.()):n.code===e.ERROR_CODES.UPLOAD_TIMEOUT?e.logger.warn("Upload request timeout",{operation:"upload.simple",timeout:e.UPLOAD_TIMEOUT}):e.logger.warn("Upload request failed",{operation:"upload.simple"}),n}try{const r=JSON.parse(S.body),n=Date.now()-I;if(S.status>=400)throw e.logger.warn("Upload response error",{operation:"upload.simple",status:S.status,duration:n}),new e.UploadError("Upload failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{status:S.status,response:r}});e.logger.debug("Upload response success",{operation:"upload.simple",status:S.status,duration:n});const o=e.buildUploadResult({response:r,restBaseUrl:s.restBaseUrl,orgName:f,appName:y,fileType:p,fileName:h,fallbackSize:m,messageType:i,imageType:c,useCustomAttachmentUpload:s.useCustomAttachmentUpload});return t.callbacks?.onFileUploadComplete?.(o),v?.finish({code:S.status||200,success:!0}),o}catch(T){throw v?.finish({code:T instanceof e.UploadError?T.code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,success:!1,description:T instanceof Error?T.message:String(T)}),T instanceof Error?T:new Error(String(T))}},li=Is(),ui=e=>Object.prototype.toString.call(e),hi=e=>{const t=e&&"object"==typeof e?e:null,s="string"==typeof t?.path?t.path:void 0,r="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,o="string"==typeof t?.type?t.type:void 0,i="number"==typeof t?.size?t.size:void 0;return{kind:ui(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 r&&r.length>0,uriPrefix:r?r.slice(0,48):void 0,name:n,type:o,size:i}},pi=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}),mi=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,gi=e=>"object"==typeof e&&null!==e,fi=(t,s)=>{const r=gi(s)?s:void 0,n=r?.code===e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY&&r.stage===e.PLATFORM_ERROR_STAGE.RUNTIME;return"miniapp-path"===t&&(t=>{if(!gi(t))return!1;const s=gi(t.details)?t.details:void 0;return t.code===e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY&&t.stage===e.PLATFORM_ERROR_STAGE.RUNTIME&&"string"==typeof s?.capability&&s.capability.includes("FileSystem")})(s)||"rn-uri"===t&&n};class yi{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(s,r){if(!mi(s.type))return s;const n=s.body;if(this.hasUploadedRemoteResource(s.type,n))return s;const o=this.resolveUploadUrl(s.type,n),i=t.attachmentFileStore.get(s.msgLocalId),c=Boolean(i);if(e.logger.warn("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:s.msgLocalId,messageType:s.type,conversationType:s.conversationType,hasFile:c,uploadUrl:o,cachedFile:hi(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}}),!e.shouldUploadByUrl(o,c))return s;if(!i)throw new e.UploadError("Attachment file is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:s.msgLocalId,url:o}});if(!this.config?.restBaseUrl)throw new e.UploadError("REST base url is required for upload",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let d,l,u;try{d=await this.prepareAttachmentUpload(s,n,i),d.precheck?.hit||(u=e.startDataReportOperation({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:s.msgLocalId,messageType:s.type})),l=d.precheck?.hit?this.buildPrecheckedUploadResult(s,d,r):await this.uploadAttachment(s,d,r,u),u?.finish({code:0,success:!0})}catch(h){const t=a.mapUploadAdapterError(h);throw u?.finish({code:t.code,success:!1,description:t.message}),t.code===e.ERROR_CODES.UPLOAD_ABORTED&&r?.onFileUploadCanceled?.(),r?.onFileUploadError?.(t),t}return this.buildPreparedMessage(s,d,l)}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(t,s){if("image"===t){const t=s;return"string"==typeof t.originalImageUrl&&e.isRemoteUrl(t.originalImageUrl)}return"url"in s&&"string"==typeof s.url&&e.isRemoteUrl(s.url)}async prepareAttachmentUpload(t,s,r){const n=e.normalizeAttachmentFile(r,s);if(e.logger.warn("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:t.type,fileInfo:pi(n)}),"image"!==t.type){return{body:s,fileInfo:n,md5FileInfo:n,precheck:await this.maybePrecheck(t,n,n,void 0)}}const o=s,i=await this.resolveImageCandidate(o,n),a={...o,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===e.IMAGE_TYPE_ORIGINAL},c=await this.maybePrecheck(t,i.fileInfo,n,i.imagePolicy.resolvedImageType);return{body:a,fileInfo:i.fileInfo,md5FileInfo:n,imageType:i.imagePolicy.resolvedImageType,precheck:c,originalWidth:o.width,originalHeight:o.height}}async resolveImageCandidate(t,s){const r=e.resolveImageSendPolicy(t);if(e.logger.warn("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:t.isGif,source:pi(s)}),r.resolvedImageType===e.IMAGE_TYPE_ORIGINAL){let n=t.width,o=t.height;if(!n||!o){const t=this.resolveImageProcessor(s.source.sourceType);e.logger.warn("Image original info resolving",{operation:"upload.image.info",processorSourceType:s.source.sourceType,source:pi(s)});const r=await t.getImageInfo(s.source);n=r.width,o=r.height}return{imagePolicy:r,sourceKind:"origin",fileInfo:s,width:n,height:o}}try{const t=this.resolveImageProcessor(s.source.sourceType);e.logger.warn("Image big generation start",{operation:"upload.image.big.start",processorSourceType:s.source.sourceType,source:pi(s)});const n=await t.generateBigImage(s.source,{maxShortEdge:720,quality:.85});return{imagePolicy:r,sourceKind:"big",fileInfo:{source:n.source,fileName:n.fileName??s.fileName,fileType:n.fileType??s.fileType,fileSize:n.fileSize??s.fileSize,webFile:n.webFile},width:n.width,height:n.height}}catch(n){return e.logger.warn("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:n instanceof Error?n.message:String(n),source:pi(s)}),{imagePolicy:{resolvedImageType:e.IMAGE_TYPE_ORIGINAL,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:s,width:t.width??0,height:t.height??0}}}async maybePrecheck(t,s,r,n){if(!mi(t.type))return;if(!0!==this.config?.enableMd5Check)return void e.logger.debug("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:t.type,imageType:n,fileSize:s.fileSize});const o=e.buildAttachmentPrecheckDecision({messageType:t.type,fileSize:s.fileSize,imageType:n});if(!o.shouldPrecheck)return void e.logger.debug("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:t.type,imageType:n,fileSize:s.fileSize,thresholdBytes:o.thresholdBytes});let i;try{i=await this.computeMd5(r)}catch(c){if(fi(r.source.sourceType,c))return void e.logger.warn("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:t.type,imageType:n,thresholdType:o.thresholdType,source:pi(r),error:c instanceof Error?c.message:String(c)});throw c}const a=await this.requestPrecheck(t,o.thresholdType,i,n);return e.logger.debug(a.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:a.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:t.type,imageType:n,exists:a.exists,existsType:a.existsType,uuid:a.uuid,hasShareSecret:"string"==typeof a.shareSecret&&a.shareSecret.length>0}),{...a,md5:i}}async computeMd5(t){const s=this.resolveImageProcessor(t.source.sourceType);return e.logger.warn("Attachment md5 compute start",{operation:"upload.md5.start",source:pi(t)}),s.computeMd5(t.source)}resolveImageProcessor(t){if(this.config?.imageProcessor)return e.logger.warn("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:t,processor:"platform"}),this.config.imageProcessor;if("web-file"===t)return e.logger.warn("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:t,processor:"web-fallback"}),li;throw e.logger.warn("Image processor missing",{operation:"upload.image.processor-missing",sourceType:t}),e.createPlatformError("Image processor capability is missing for current platform",{code:e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY,stage:e.PLATFORM_ERROR_STAGE.RUNTIME,retryable:!1,details:{capability:"imageProcessor",sourceType:t}})}async requestPrecheck(t,s,r,n){if(!this.config)throw new e.UploadError("Upload config is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:o,appName:i}=e.parseAppKey(this.config.appKey),a=e.appendUrlQueryParams(`${this.config.restBaseUrl}/${o}/${i}/chatfiles/exists`,{md5:r,..."image"===t.type?{imageType:e.toUploadImageType(n)}:{}}),c=await this.requestJson({url:a,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(o=>{e.logger.warn("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:t.type,imageType:n,thresholdType:s,md5:r,error:o instanceof Error?o.message:String(o)})});return c?e.parseAttachmentPrecheckResult(c):{exists:!1,hit:!1}}async requestJson(t){return this.requestByAdapter(e.resolveRequestAdapter(this.config?.requestAdapter),t)}async requestByAdapter(t,s){const r=await t.request({url:s.url,method:s.method,headers:s.headers,responseType:"json",timeoutMs:e.UPLOAD_TIMEOUT});if(r.status>=400)throw new e.UploadError("Upload precheck request failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{url:s.url,status:r.status,operation:s.operation}});return"string"==typeof r.data?JSON.parse(r.data):r.data}buildPrecheckedUploadResult(t,s,r){if(!this.config||!s.precheck)throw new e.UploadError("Precheck result is required",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED});if(!s.precheck.uuid)throw new e.UploadError("Precheck hit missing uuid",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{precheck:s.precheck}});if(!mi(t.type))throw new e.UploadError("Attachment message type is invalid",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const{orgName:n,appName:o}=e.parseAppKey(this.config.appKey),i="image"===t.type?s.precheck.existsType??s.imageType:void 0,a="image"===t.type&&i===e.IMAGE_TYPE_ORIGINAL?s.md5FileInfo:s.fileInfo,c="image"===t.type&&i===e.IMAGE_TYPE_ORIGINAL?s.originalWidth:"image"===t.type?s.body.width:void 0,d="image"===t.type&&i===e.IMAGE_TYPE_ORIGINAL?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=e.buildUploadResult({response:l,restBaseUrl:this.config.restBaseUrl,orgName:n,appName:o,fileType:a.fileType,fileName:a.fileName,fallbackSize:a.fileSize,messageType:t.type,imageType:i,width:c,height:d,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(t,s,r,n){if(!this.config)throw new e.UploadError("Upload config is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING});if(!mi(t.type))throw new e.UploadError("Attachment message type is invalid",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const o=t.type,i=await this.resolveUploadMetadata(o,s);if(!s.fileInfo.webFile){if(this.config.uploadAdapter)return this.uploadByAdapter(this.config.uploadAdapter,t,s,i,r);throw new e.UploadError("Upload adapter is required for non-web file source",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:s.fileInfo.source.sourceType}})}const a={message:t,file:s.fileInfo.webFile,conversationId:t.conversationId,conversationType:t.conversationType,messageType:o,imageType:s.imageType,md5:i.md5,width:i.width,height:i.height,fileName:s.fileInfo.fileName,fileType:s.fileInfo.fileType,fileSize:s.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(o,s.body),thumbnailHeight:this.resolveThumbnailHeight(o,s.body),callbacks:r,config:this.config,dataReportOperation:n},c=!1!==this.config?.enableMultipartUpload,d=c&&s.fileInfo.fileSize>e.MULTIPART_THRESHOLD;if(e.logger.warn("Attachment web upload selected",{operation:"upload.web.selected",messageType:o,source:pi(s.fileInfo),multipartEnabled:c,uploadMode:d?"multipart":"simple"}),d)try{return await ci(a)}catch(l){const t=l instanceof e.UploadError?l.details:void 0;if(t&&"object"==typeof t&&"init"===t.stage)return di(a);throw l}return this.config.uploadAdapter?(e.logger.warn("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:o,source:pi(s.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,t,s,i,r)):di(a)}async uploadByAdapter(t,s,r,n,o){if(!this.config)throw new e.UploadError("Upload config is required",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:a}=e.parseAppKey(this.config.appKey),c=e.toUploadChatType(s.conversationType);if(!mi(s.type))throw new e.UploadError("Attachment message type is invalid",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:s.type}});const d=s.type,l=e.appendUrlQueryParams(`${this.config.restBaseUrl}/${i}/${a}/chatfiles`,{"chat-type":c,"chat-target":s.conversationId,md5:n.md5,..."image"===d?{imageType:e.toUploadImageType(r.imageType),width:n.width,height:n.height}:{}}),u={},h={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[e.REQUEST_ID_HEADER]:e.createTraceId()},p=this.resolveThumbnailWidth(d,r.body),m=this.resolveThumbnailHeight(d,r.body);void 0!==p&&(u["thumbnail-width"]=String(p)),void 0!==m&&(u["thumbnail-height"]=String(m)),e.logger.warn("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:d,source:pi(r.fileInfo),uploadUrl:l,fields:u});const g=await t.upload({url:l,headers:h,source:r.fileInfo.source,fields:u,onProgress:e=>{o?.onFileUploadProgress?.(e)}});if(g.status>=400){const t=g.body??"",s=413===g.status?e.ERROR_CODES.FILE_TOO_LARGE:"string"==typeof t&&t.includes("content improper")?e.ERROR_CODES.FILE_CONTENT_IMPROPER:e.ERROR_CODES.UPLOAD_REQUEST_FAILED;throw new e.UploadError("Upload failed",{code:s,details:{status:g.status,response:g.body}})}let f;try{f=JSON.parse(g.body)}catch(E){throw new e.UploadError("Upload response parse failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{response:g.body,cause:E instanceof Error?E.message:String(E)}})}const y=e.buildUploadResult({response:f,restBaseUrl:this.config.restBaseUrl,orgName:i,appName:a,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:d,imageType:r.imageType,width:n.width,height:n.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return o?.onFileUploadComplete?.(y),y}buildPreparedMessage(e,s,r){if("image"===e.type){const n=s.body,o={...e,body:{...n,isOriginalImage:r.isOriginalImage??n.isOriginalImage,originalImageUrl:r.originalImageUrl??n.originalImageUrl,bigImageUrl:r.bigImageUrl??n.bigImageUrl,secret:r.secret??n.secret,fileLength:r.fileLength??n.fileLength??s.fileInfo.fileSize,filetype:r.filetype??n.filetype,filename:r.filename??n.filename,thumbnailUrl:r.thumbnailUrl??n.thumbnailUrl,width:r.width??n.width,height:r.height??n.height}};return ln(e,o),t.copyCombineCompatibleTextSidecar(e,o),o}if("video"===e.type){const t=s.body,n={...e,body:{...t,url:r.url,secret:r.secret??t.secret,fileLength:r.fileLength??t.fileLength??s.fileInfo.fileSize,filetype:r.filetype??t.filetype,filename:r.filename??t.filename,thumbnailUrl:r.thumbnailUrl??t.thumbnailUrl}};return ln(e,n),n}if("voice"===e.type){const t=s.body,n={...e,body:{...t,url:r.url,secret:r.secret??t.secret,fileLength:r.fileLength??t.fileLength??s.fileInfo.fileSize,filetype:r.filetype??t.filetype,filename:r.filename??t.filename}};return ln(e,n),n}if("combine"===e.type){const t=s.body,n={...e,body:{...t,url:r.url,secret:r.secret??t.secret,fileLength:r.fileLength??t.fileLength??s.fileInfo.fileSize,filetype:r.filetype??t.filetype,filename:r.filename??t.filename}};return ln(e,n),n}const n=s.body,o={...e,body:{...n,url:r.url,secret:r.secret??n.secret,fileLength:r.fileLength??n.fileLength??s.fileInfo.fileSize,filetype:r.filetype??n.filetype,filename:r.filename??n.filename}};return ln(e,o),o}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(t,s){let r=s.precheck?.md5??"";if(!s.precheck)try{r=await this.computeMd5(s.md5FileInfo)}catch(o){if(!fi(s.md5FileInfo.source.sourceType,o))throw o;e.logger.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:t,source:pi(s.md5FileInfo),error:o instanceof Error?o.message:String(o)})}const n=s.body;return{md5:r,width:"image"===t&&"number"==typeof n.width&&n.width>0?n.width:void 0,height:"image"===t&&"number"==typeof n.height&&n.height>0?n.height:void 0}}}class Ei{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 Ri="__internal:core";class Ii{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 Lo({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),r=e.restBaseUrl?new yi({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 Qo(s,null,this.eventHub,r),this.messageReceiver=new Zo(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new ti(e.platformAdapter?.request),this.attachmentDownloader=new ni(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Ri,{[t.ConnectionEventName.CONNECTED]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[t.ConnectionEventName.DISCONNECTED]:e=>{this.messageSender.setWebSocket(null)},[t.ConnectionEventName.RECONNECT_FAILED]:e=>{this.messageSender.setWebSocket(null)},[t.InternalEventName.MESSAGE_SENT]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new Ei(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(Ri),t.attachmentFileStore.clear()}}const vi=e=>{if(e.length>=1048576){const t=[],s=32768;for(let r=0;r<e.length;r+=s)t.push(String.fromCharCode(...e.subarray(r,r+s)));return btoa(t.join(""))}let t="";for(let s=0;s<e.length;s+=1){const r=e[s];void 0!==r&&(t+=String.fromCharCode(r))}return btoa(t)},Ci=e=>{const t=new Uint8Array(r.lightExports.util.base64.length(e));return r.lightExports.util.base64.decode(e,t,0),t};class Si{getCrypto(){return e.getRuntimeGlobal().crypto}constructor(t,s){if(this.enabled=(()=>{const t=e.getRuntimeGlobal();if([t.wx,t.qq,t.tt,t.swan,t.my,t.dd,t.jd,t.ks,t.uni].some(e=>void 0!==e))return!1;const s=_t(t);if("web"!==s.framework&&"worker"!==s.framework&&s.platform!==e.RUNTIME_PLATFORMS.ELECTRON_RENDERER)return!1;const r=t.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const e=`${t}:${s}`;this.keyPromise=this.deriveKey(e)}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,r=this.getCrypto().getRandomValues(new Uint8Array(12)),n=s.encode(e),o=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:r},t,n),i={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:vi(r),ct:vi(new Uint8Array(o))};return JSON.stringify(i)}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=Ci(t.iv),r=Ci(t.ct),n=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:s},e,r);return(new TextDecoder).decode(n)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),s=this.getCrypto(),r=await s.subtle.digest("SHA-256",t);return s.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const Ti="conversationMap",Ai="userInfoMap",Oi="groupNamecardMap",bi="contactRelationMap",_i="contactVersion",Mi="contactMeta",Ni="sessionListMap",Di="sessionListCheckpoint",wi="joinedGroupPreview",Li="metadata",Ui=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Pi{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 ki=()=>{const t="undefined"!=typeof window?window.localStorage:void 0;if(t&&"function"==typeof t.getItem)return t;const s=e.getRuntimeGlobal().localStorage;return s&&"function"==typeof s.getItem?s:null};class xi{constructor(e,t){this.storage=t??xi.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!xi.checkAvailable())return null;const e=ki();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=ki();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(t,s){if(!this.storage)return s;try{const e=await this.storage.getItem(t);if(!e)return s;let r=e;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const t=await this.cryptoAdapter.decrypt(e);if(null===t)return s;r=t}return d.safeJsonParse(r,s)}catch(r){return e.logger.warn("CacheStore read failed",r),s}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(t,s,r){if(!this.storage)return;const n=d.safeJsonStringify(s);if(null!==n)try{const e=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(n):n;await this.storage.setItem(t,e)}catch(o){if(ws(o))throw o;if(r)throw o;e.logger.warn("CacheStore write failed",o)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(t){if(this.storage)try{await this.storage.removeItem(t)}catch(s){e.logger.warn("CacheStore remove failed",s)}}}const Fi={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Bi={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Gi{constructor(){this.items=new Map,this.versionState=Fi,this.meta=Bi}load(e,t,s){this.items.clear();for(const r of e){const e=this.normalizeRecord(r);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 r=this.items.get(e);return!(!r||r.remark===t)&&(this.items.set(e,{...r,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])),r=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}}),n="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:r,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:n}}normalizeRecord(e){if(!d.isRecord(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 d.isRecord(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"}:Fi}normalizeMeta(e){return d.isRecord(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"}:Bi}}const qi=(e,t,s)=>{if(t<=0)return{kept:e,removed:[]};const r=[],n=[];for(const o of e)s-o.lastUpdate>t?n.push(o):r.push(o);return{kept:r,removed:n}},Ki=(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),r=new Set(s);return{kept:e.filter(e=>!r.has(e)),removed:s}},Vi=e=>{if(!Array.isArray(e))return[];const t=new Set,s=[],r=e;for(const n of r){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,r="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(r)||r<0||r>19)continue;const o=r;t.has(o)||(t.add(o),s.push(o))}return s};class zi{constructor(){this.items=[]}load(e,t){const s=[];for(const r of e){const e=this.normalizeItem(r,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 r of e){const e=this.findIndex(r.conversationId,r.type);if(e<0)continue;const n=this.items[e];n&&(n.lastAccess!==t&&(this.items[e]={...n,lastAccess:t},s=!0))}return s}removeExpired(e,t){const s=qi(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=Ki(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),r=t.slice(0,s),n=new Set(r);return this.items=this.items.filter(e=>!n.has(e)),r.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 r="single"===(n=s.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!r)return null;const o=this.normalizeMessage(s.lastMessage);return{conversationId:s.conversationId,type:r,lastMessage:o,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:Vi(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(!d.isRecord(e))return null;const t="string"==typeof e.msgId?e.msgId:"",s="string"==typeof e.type?e.type:"",r="number"==typeof e.timestamp?e.timestamp:0,n=d.isRecord(e.body)?e.body:{},o="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,i="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:s,body:n,timestamp:r,userInfoUpdateTime:o,namecardUpdateTime:i}:null}}const Hi=(e,t)=>`${e}:${t}`;class ji{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const s of e){const e=this.normalizeItem(s,t);e&&this.items.set(Hi(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,r){const n=Hi(e,t),o=this.items.get(n);return o?(r&&this.items.set(n,{...o,lastAccess:s}),o):null}getByGroupId(e,t,s){const r=[];for(const n of this.items.values())n.groupId===e&&(r.push(n),s&&this.items.set(Hi(n.groupId,n.userId),{...n,lastAccess:t}));return r}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const r=Hi(e.groupId,e.userId),n=this.items.get(r);this.items.set(r,{...e,lastAccess:n?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(Hi(t.groupId,t.userId))}removeExpired(e,t,s=new Set){const r=Array.from(this.items.values()),n=r.filter(e=>!s.has(e.userId)),o=qi(n,e,t),i=new Set(o.removed.map(e=>Hi(e.groupId,e.userId)));this.items.clear();for(const a of r)i.has(Hi(a.groupId,a.userId))||this.items.set(Hi(a.groupId,a.userId),a);return o.removed.length>0}evictByLru(e,t=new Set){const s=Array.from(this.items.values()),r=s.filter(e=>!t.has(e.userId)),n=Ki(r,Math.min(e,r.length)),o=new Set(n.removed.map(e=>Hi(e.groupId,e.userId)));this.items.clear();for(const i of s)o.has(Hi(i.groupId,i.userId))||this.items.set(Hi(i.groupId,i.userId),i);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!d.isRecord(e))return null;const s="string"==typeof e.groupId?e.groupId:"",r="string"==typeof e.userId?e.userId:"";if(!s||!r)return null;return{groupId:s,userId:r,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 Wi=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Qi=e=>{const t={...e};return delete t.type,t},$i=e=>{if(!d.isRecord(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!d.isRecord(e.body))return null;const s=((e,t)=>{if(d.isRecord(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 r=Wi(e.conversationType),n=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),o=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),i=(e=>{if(d.isRecord(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:Qi(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...r?{conversationType:r}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...n?{sendStatus:n}:{},...o?{direct:o}:{},...i?{modifiedInfo:i}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Yi=e=>{if(!Array.isArray(e))return[];const t=new Set,s=[],r=e;for(const n of r){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,r="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(r)||r<0||r>19)continue;const o=r;t.has(o)||(t.add(o),s.push(o))}return s},Ji=(e,t)=>{const s="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,r="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(s!==r)return r-s;const n=e.lastMessageAt??e.updatedAt,o=t.lastMessageAt??t.updatedAt;return n!==o?o-n:e.conversationId.localeCompare(t.conversationId)};class Xi{constructor(){this.items=[]}load(e,t){const s=[];for(const r of e){const e=this.normalizeItem(r,t);e&&s.push(e)}this.items=s.sort(Ji)}getAll(){return this.items}setAll(e){const t=Date.now(),s=[];for(const r of e){const e=this.normalizeItem(r,t);e&&s.push(e)}this.items=s.sort(Ji)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!d.isRecord(e))return null;const s=e,r="string"==typeof s.conversationId?s.conversationId:"";if(!r)return null;const n=Wi(s.conversationType);if(!n)return null;const o="string"==typeof s.conversationName&&s.conversationName.length>0?s.conversationName:r,i="string"==typeof s.conversationAvatar?s.conversationAvatar:void 0;return{conversationId:r,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:$i(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:Yi(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:o,conversationAvatar:i,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class Zi{constructor(){this.items=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 r=[];for(const n of e){const e=this.items.get(n);e&&(r.push(e),s&&this.items.set(n,{...e,lastAccess:t}))}return r}setAll(e,t){for(const s of e){const e=this.normalizeItem(s,t);if(!e)continue;const r=this.items.get(e.userId),n=r?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,s=new Set){const r=Array.from(this.items.values()),n=r.filter(e=>!s.has(e.userId)),o=qi(n,e,t),i=new Set(o.removed.map(e=>e.userId));this.items.clear();for(const a of r)i.has(a.userId)||this.items.set(a.userId,a);return o.removed.length>0}evictByLru(e,t=new Set){const s=Array.from(this.items.values()),r=s.filter(e=>!t.has(e.userId)),n=Ki(r,Math.min(e,r.length)),o=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const i of s)o.has(i.userId)||this.items.set(i.userId,i);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const s=Array.from(this.items.values()),r=Math.max(s.length-e,0);return this.evictByLru(r,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!d.isRecord(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 ea=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,ta=e=>e.lastMessageAt??e.updatedAt,sa=e=>[...e].sort((e,t)=>{const s=ea(t)-ea(e);if(0!==s)return s;const r=ta(t)-ta(e);return 0!==r?r:e.conversationId.localeCompare(t.conversationId)}),ra=e=>`${e.conversationType}:${e.conversationId}`,na=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,oa=(e,t)=>((e,t)=>ta(t)>ta(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:na(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,ia=e=>{const t=new Map,s=new Set;for(const o of e.snapshot)s.add(ra(o));for(const o of e.existing)t.set(ra(o),o);const r=e.snapshot.map(e=>{const s=t.get(ra(e));return s?oa(e,s):e}),n=e.existing.filter(t=>!s.has(ra(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return sa([...r,...n])},aa=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],ca=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),da=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 la{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,s=Date.now()){const r=this.records.get(e)??null;if(!r||!t)return r;const n={...r,lastAccess:s};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const s of e){const e=s.lastModified??t,r=this.records.get(s.profile.userId),n=r?.lastAccess??t;this.records.set(s.profile.userId,{profile:s.profile,lastModified:e,lastAccess:n,source:s.source})}}applyPatch(e,t,s=Date.now()){const r=this.records.get(e.userId),n={userId:e.userId,...t??{},...r?.profile??{}};if(r&&e.lastModified<r.lastModified)return{applied:!1,reason:"stale",record:r};const o={...n,...e.attributes,userId:e.userId};if(r&&e.lastModified===r.lastModified&&(i=r.profile,a=o,aa.every(e=>i[e]===a[e])))return{applied:!1,reason:"duplicate",record:r};var i,a;const c={profile:o,lastModified:e.lastModified,lastAccess:r?.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 ua=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class ha{constructor(e){this.conversationDeletionTimestamps=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=new Map,this.pendingDirtyRevisions=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 Si(e.appKey,e.userId);this.store=new xi(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Ui(s,Ti),this.userInfoKey=Ui(s,Ai),this.groupNamecardKey=Ui(s,Oi),this.sessionListKey=Ui(s,Ni),this.sessionListCheckpointKey=Ui(s,Di),this.joinedGroupPreviewKey=Ui(s,wi),this.contactRelationKey=Ui(s,bi),this.contactVersionKey=Ui(s,_i),this.contactMetaKey=Ui(s,Mi),this.metadataKey=Ui(s,Li),this.metadataStore=new Pi(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new zi,this.userInfoCache=new Zi,this.groupNamecardCache=new ji,this.sessionListCache=new Xi,this.joinedGroupPreviewCache=new o.JoinedGroupPreviewCache,this.contactCache=new Gi,this.userInfoRuntimeStore=new la,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 o.JoinedGroupPreviewCache;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 r=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==r&&r<=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,r=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(s=!0,0===n.unreadCount?n:(r=!0,{...n,unreadCount:0,lastUpdate:t})));let o=!1;const i=this.sessionListCache.getAll().map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:(s=!0,0===r.unreadCount&&r.readAt===t?r:(o=!0,{...r,unreadCount:0,readAt:t,updatedAt:t})));return r||o?(r&&this.conversationCache.setAll(n),o&&this.sessionListCache.setAll(i),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(),r=s.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),o=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),i=!this.isConversationListEqual(s,r),a=!this.isSessionListEqual(n,o);return i||a?(i&&this.conversationCache.setAll(r),a&&this.sessionListCache.setAll(o),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(),r=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}),n=this.sessionListCache.getAll(),o=n.map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:{...s,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),i=!this.isConversationListEqual(s,r),a=!this.isSessionListEqual(n,o);return i||a?(i&&this.conversationCache.setAll(r),a&&this.sessionListCache.setAll(o),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 r=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=s.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),o=r.length!==t.length,i=n.length!==s.length;return o||i?(o&&this.conversationCache.setAll(r),i&&this.sessionListCache.setAll(n),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(),r=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),o=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const o=r(e.marks);return this.areConversationMarksEqual(o,e.marks)?e:{...e,marks:o,lastUpdate:s}}),i=this.sessionListCache.getAll(),a=i.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const o=r(e.marks);return this.areConversationMarksEqual(o,e.marks)?e:{...e,marks:o,updatedAt:s}}),c=!this.isConversationListEqual(n,o),d=!this.isSessionListEqual(i,a);return c||d?(c&&this.conversationCache.setAll(o),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 r=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??r})),o=ia({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:s?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(o,r)),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 r=!1;for(;!r;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),s=this.getDomainRevision("sessionList"),s===n&&(r=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=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?ca(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([da(t)])}getUserInfoSummaries(e,t){const s=Date.now(),r=this.userInfoCache.getByIds(e,s,t);return t&&this.scheduleFlush(["userInfo"]),r}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,s){const r=this.groupNamecardCache.get(e,t,Date.now(),s);return s&&r&&this.scheduleFlush(["groupNamecard"]),r}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 r=this.loadContactSnapshot("sync");return{snapshot:r,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(r)}}refreshSessionListDisplayFromUserInfos(e){const t=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(),r=this.loadContactSnapshot("cache").items,n=new Map(r.map(e=>[e.userId,e])),o=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),i=this.sessionListCache.getAll().map(e=>{let r=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,o)){const t=n.get(e.conversationId),i=this.resolveSessionDisplayUserInfo(e.conversationId,o),a=this.buildSingleSessionDisplayFields(e.conversationId,t,i,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(r={...r,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:s})}const i=r.lastMessage;if(i&&!this.shouldSkipSessionUserDisplayRefresh(i.sender.userId,t,o)){const e=n.get(i.sender.userId),t=this.resolveSessionDisplayUserInfo(i.sender.userId,o),a=this.buildSessionMessageSender(i.sender.userId,i.sender,e,t);this.isSenderEqual(i.sender,a)||(r={...r,lastMessage:{...i,sender:a},updatedAt:s})}return r}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,i);return c&&(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const s=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 r=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=s.get(e.conversationId);if(!n)return e;const o=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&o)return e;const i=n.name?.trim(),a=i||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.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:r}:e}),o=this.sessionListCache.getAll(),i=!this.isSessionListEqual(o,n);return i&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:i}}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(),r="add"===e.action?this.contactCache.addByNotice(e.userId,s):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,s);(r||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const o=this.loadContactSnapshot("cache");return{snapshot:o,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(o)}}updateConversationsFromServer(e,t){const s=Date.now(),r=this.conversationCache.getAll(),n=this.mergeConversationLists(r,e,s,t?.syncStartedAt),o=!this.isConversationListEqual(r,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:o}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const s=Date.now(),r=this.conversationCache.getAll(),n=r.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),o=n>=0?r[n]:void 0,i=this.buildConversationFromMessage(e,o,s);if(!i)return{items:r,changed:!1};const a=[i,...r.filter((e,t)=>t!==n)];return this.isConversationListEqual(r,a)?{items:r,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(),r=s.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const o=(e=>{const t=ra(e.nextRecord),s=e.existing.filter(e=>ra(e)!==t);return sa([e.nextRecord,...s])})({existing:s,nextRecord:this.buildSessionListRecordFromConversation(n,e,r,Date.now())});return this.isSessionListEqual(s,o)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(o),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 r=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(r,e);const n=await this.readValue(this.sessionListKey,null),o=n&&d.isRecord(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(o,e);const i=(n&&d.isRecord(n)&&d.isRecord(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(i);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),l=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,l,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&d.isRecord(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&d.isRecord(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=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(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(t){try{const n=6;for(let o=0;o<=n;o+=1)try{return await this.writeDirtyDomains(t),void(await this.metadataStore.touchLastFlush())}catch(s){if(!ws(s))return this.restoreDirtyBatch(t),void e.logger.warn("Cache flush failed",s);const n=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(t,n),"none"===n)return void e.logger.warn("Cache flush failed: no cache entry can be evicted",s);try{await this.writeDomain(n)}catch(r){if(!ws(r))return this.restoreDirtyBatch(t),void e.logger.warn("Cache quota cleanup persistence failed",r)}}e.logger.warn("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of ua)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 r={items:e,checkpoint:t};s?await this.store.writeStrictAsync(this.sessionListKey,r):await this.store.writeAsync(this.sessionListKey,r),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),s=new Map;for(const n of t)s.set(`${n.conversationType}:${n.conversationId}`,n);const r=Date.now();return(e=>{const t=e.incoming.filter(e=>ea(e)>0),s=new Map;for(const n of e.incoming)s.set(ra(n),n);const r=t.length>0?e.existing.filter(e=>!s.has(ra(e))&&0===ea(e)):e.existing.filter(e=>!s.has(ra(e)));return sa([...r,...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??r}})})}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(ia({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,r){const n=e.find(e=>e.conversationId===s&&e.type===r),o=t.find(e=>e.conversationId===s&&e.conversationType===r);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,o?.updatedAt??0,o?.lastMessageAt??0,o?.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 r=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),r}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,r){const n=new Map,o=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),o.set(e,d)}const i=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??s;i.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 r&&e.lastUpdate>r)});return[...i,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],n=t[s];if(!r||!n)return!1;if(this.buildConversationSignature(r)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,s=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",r=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,o=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${r}:${n}:${o}:${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 r=this.resolveConversationFromMessage(e);if(!r)return null;const n=e.msgServerId||e.msgLocalId,o=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,i="SEND"===e.direct?s:t?.lastAccess??s;return{conversationId:r.conversationId,type:r.type,lastMessage:this.buildMessageSnippet(e),unreadCount:o,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:i,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=dn(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,r=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),o=n.get(e.conversationId),i=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],r,!1)[0],c=i??(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,n.get(h),p),g="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,f="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,o,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:g,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:f.conversationName,conversationAvatar:f.conversationAvatar,updatedAt:r}}resolveSessionListUnreadCount(e,t,s){const r=s?.unreadCount,n=t.msgServerId||t.msgLocalId;return s?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof r?Math.max(e.unreadCount,r+1):e.unreadCount:"number"==typeof r?Math.max(e.unreadCount,r):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,r,n){const o=t?.remark?.trim(),i=t?.userInfo.avatarUrl??s?.avatarUrl??n;if(o)return{conversationName:o,conversationAvatar:i};const a=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return a?{conversationName:a,conversationAvatar:i}:r?{conversationName:r,conversationAvatar:i}:{conversationName:e,conversationAvatar:i}}shouldSkipSessionUserDisplayRefresh(e,t,s){if(!t.has(e))return!0;const r=t.get(e),n=s.get(e);return"number"==typeof r&&"number"==typeof n?.lastUpdate&&n.lastUpdate>r}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const s=this.loadContactSnapshot("cache").items,r=new Map(s.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const s=e.lastMessage;if(!s)return e;const o=s.sender.userId,i=r.get(o),a=this.resolveSessionDisplayUserInfo(o,n),c="singleChat"===e.conversationType&&o===e.conversationId?this.buildSingleChatPeerMessageSender(o,s.sender,i,a):this.buildSessionMessageSender(o,s.sender,i,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 r=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return r?ca(r):null}buildSessionMessageSender(e,t,s,r){const n=s?.remark?.trim();return{userId:e,nickname:n||s?.userInfo.nickname?.trim()||r?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:s?.userInfo.avatarUrl??r?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,s,r){const n=this.buildSessionMessageSender(e,void 0,s,r);return{userId:e,nickname:t?.nickname?.trim()||n.nickname,avatarUrl:t?.avatarUrl||n.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 r=e[s],n=t[s];if(!r||!n)return!1;if(this.buildSessionListSignature(r)!==this.buildSessionListSignature(n))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",r=`${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,r,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 pa{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const s=[],r=[];for(const o of this.handlers.entries()){const[e]=o;e.startsWith("__internal")?s.push(o):r.push(o)}const n=this.dispatchToHandlers(e,t,s);n?n.then(()=>{this.dispatchToHandlers(e,t,r)}):this.dispatchToHandlers(e,t,r)}dispatchToHandlers(e,t,s){let r=null;for(const[,n]of s){const s=n[e];s&&(r=r?r.then(async()=>{await this.invokeHandler(e,t,s)}):this.invokeHandler(e,t,s))}return r}invokeHandler(e,t,s){try{const r=s(t);return this.isPromiseLike(r)?Promise.resolve(r).then(()=>{}).catch(t=>{this.reportHandlerError(e,t)}):null}catch(r){return this.reportHandlerError(e,r),null}}reportHandlerError(t,s){t!==n.LogEventName.LOG&&e.logger.error(`Event handler error for ${t}`,s)}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const ma={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function ga(e,t){const s=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),r=Math.min(s,t.maxDelay);if(t.jitter){const e=.2*r,t=(2*Math.random()-1)*e;return Math.max(0,r+t)}return r}function fa(e){return new Promise(t=>setTimeout(t,e))}const ya=e=>{const t={...e};return delete t.type,t},Ea=(e,t)=>{const s=e.lastMessage;if(!s)return null;const r=((e,t)=>{const s=t.getCurrentUserId?.()??"",r="singleChat"===e.type?e.conversationId:"";return{from:r,to:"singleChat"===e.type?s:e.conversationId,sender:{userId:r}}})(e,t);return{msgServerId:s.msgId,from:r.from,to:r.to,sender:r.sender,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof s.type&&s.type.length>0?s.type:"text",timestamp:s.timestamp,body:ya(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},Ra=async(e,t)=>{const s=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!s)return new Map;const r=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===r.length)return new Map;const n=[];for(let a=0;a<r.length;a+=50)n.push(r.slice(a,a+50));const o=new Map;let i=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;i<n.length;){const e=i;i+=1;const t=n[e];if(t)try{const e=await s.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&o.set(t.groupId,t)}catch{}}})())),o},Ia=async(e,t)=>{const s=await Ra(e,t);return e.map(e=>((e,t,s)=>{const r=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),n=((e,t)=>{const s=e.getCacheManager();if(!s)return null;const r=s.getRuntimeUserInfo(t,!1);if(r)return r;const n=s.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),o="singleChat"===e.type?((e,t,s)=>{const r=t?.remark?.trim();if(r)return{conversationName:r,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl};const n=t?.userInfo.nickname?.trim()||s?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??s?.avatarUrl}})(e.conversationId,r,n):"groupChat"===e.type?(i=e.conversationId,a=s.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:i}):(e=>({conversationName:e}))(e.conversationId);var i,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:Ea(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:o.conversationName,conversationAvatar:o.conversationAvatar}})(e,t,s))};class va{constructor(e=`session-list-${t.generateMsgLocalId()}`){this.status="idle",this.seenBatchKeys=new Set,this.itemsByConversation=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 e.SDKError("Session-list sync session cannot re-enter syncing state after completion",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(t){if(t.requestId!==this.requestId)throw new e.SDKError("Session-list sync requestId mismatch",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:t.requestId}});if(this.isTerminal())throw new e.SDKError("Session-list sync batch received after terminal state",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{requestId:t.requestId,status:this.status}});const s=(r=t.requestId,n=t.batchSequence,`${r}:${n}`);var r,n;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 Ca=0,Sa=5,Ta=10,Aa=11,Oa=1,ba=2,_a=1,Ma=2,Na=3,Da=e=>e===Oa?"groupChat":e===ba?"chatRoom":"singleChat",wa=()=>Mr().lookupType("easemob.pb.MessageBody"),La=e=>{const t=wa().toObject(wa().decode(e),{longs:Number,bytes:Uint8Array}),s=Array.isArray(t.contents)?t.contents:[],r=(n=s[0])&&"object"==typeof n&&!Array.isArray(n)?n:{};var n;const o="number"==typeof r.type?r.type:Y,i="string"==typeof r.remotePath&&r.remotePath.length>0||"string"==typeof r.title&&r.title.length>0||"string"==typeof r.summary&&r.summary.length>0||"number"==typeof r.combineLevel&&r.combineLevel>0,a=Object.prototype.hasOwnProperty.call(r,"subType")&&0===r.subType;return o===ne||o===Y&&(a||i)?{type:"combine",title:"string"==typeof r.title?r.title:"",summary:"string"==typeof r.summary?r.summary:"",filename:"string"==typeof r.displayName?r.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof r.remotePath?r.remotePath:void 0,secret:"string"==typeof r.secretKey?r.secretKey:void 0,fileLength:"number"==typeof r.fileLength?r.fileLength:void 0,combineLevel:"number"==typeof r.combineLevel?r.combineLevel:0}:o===Y?{type:"text",content:"string"==typeof r.text?r.text:""}:1===o?{type:"image",filename:"string"==typeof r.displayName?r.displayName:"image",remotePath:"string"==typeof r.remotePath?r.remotePath:""}:2===o?{type:"video",filename:"string"==typeof r.displayName?r.displayName:"video",remotePath:"string"==typeof r.remotePath?r.remotePath:""}:3===o?{type:"location",latitude:"number"==typeof r.latitude?r.latitude:0,longitude:"number"==typeof r.longitude?r.longitude:0,address:"string"==typeof r.address?r.address:void 0}:4===o?{type:"voice",filename:"string"==typeof r.displayName?r.displayName:"voice",remotePath:"string"==typeof r.remotePath?r.remotePath:"",duration:"number"==typeof r.duration?r.duration:0}:5===o?{type:"file",filename:"string"==typeof r.displayName?r.displayName:"file",remotePath:"string"==typeof r.remotePath?r.remotePath:""}:6===o?{type:"cmd",action:"string"==typeof r.action?r.action:""}:7===o?{type:"custom",event:"string"==typeof r.customEvent?r.customEvent:""}:{}},Ua=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),r="string"==typeof s?.nickname?s.nickname:void 0,n="string"==typeof s?.remark?s.remark:void 0,o="string"==typeof s?.avatarurl?s.avatarurl:"string"==typeof s?.avatarUrl?s.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:o}:r?{conversationName:r,conversationAvatar:o}:{conversationName:t,conversationAvatar:o}},Pa=e=>{const t={...e};return delete t.type,t},ka=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,xa=(e,t,s)=>{if(!e)return null;const r=(e=>{if(!e)return"";const t=e.lastIndexOf("_");return t>=0?e.slice(t+1):e})(e.from?.name),n={userId:r};return"singleChat"===s.conversationType&&r===s.conversationId&&s.singleChatPeerDisplay&&(s.singleChatPeerDisplay.conversationName!==r&&(n.nickname=s.singleChatPeerDisplay.conversationName),s.singleChatPeerDisplay.conversationAvatar&&(n.avatarUrl=s.singleChatPeerDisplay.conversationAvatar)),{msgServerId:e.id??"",from:r,to:ka({conversationId:s.conversationId,conversationType:s.conversationType,from:r,currentUserId:s.currentUserId}),sender:n,conversationId:s.conversationId,conversationType:s.conversationType,type:(o=t.type,"text"===o||"image"===o||"file"===o||"voice"===o||"video"===o||"location"===o||"custom"===o||"cmd"===o||"combine"===o?o:"text"),timestamp:e.timestamp??0,body:Pa(t)};var o},Fa=e=>{if(!Array.isArray(e))return[];const t=new Set,s=[],r=e;for(const n of r){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,r="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(r)||r<0||r>19)continue;const o=r;t.has(o)||(t.add(o),s.push(o))}return s},Ba=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return La(e)}catch{return{}}})(e.last_message?.payload),r=e.session_id??"",n=Da(e.session_type),o=(e=>{const t=e.session_id??"",s=Da(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Ua(e)})(e);return{conversationId:r,conversationType:n,unreadCount:e.unread_count??0,lastMessage:xa(e.last_message,s,{conversationId:r,conversationType:n,currentUserId:t,singleChatPeerDisplay:"singleChat"===n?o:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:Fa(e.marks),readAt:e.read_receipt,remindType:(i=e.remind_type,i===_a?"ALL":i===Ma?"AT":i===Na?"NONE":"DEFAULT"),conversationName:o.conversationName,conversationAvatar:o.conversationAvatar};var i}),Ga={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 qa=null,Ka=!1;const Va=()=>qa||(Ka||(r.lightExports.util.Long=s.Long,r.lightExports.configure(),Ka=!0),s.installReflectionRuntime(),qa=r.lightExports.Root.fromJSON(Ga),s.installReflectionCodecInNamespace(qa),qa),za=e=>Va().lookupType(e),Ha=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}},ja=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Ha(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Ha(t.protocol_version)??Ha(t.protocolVersion)??0}},Wa=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}},Qa=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Ha(t.id)?String(Ha(t.id)):void 0,from:Wa(t.from),timestamp:Ha(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 $a{constructor(){this.requestType=za("easemob.sessionlist.GetSessionListRequest"),this.responseType=za("easemob.sessionlist.GetSessionListResponse"),this.errorType=za("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 r=this.tryDecodeRequest(e);return r||{type:Ca}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=Ha(t.type);return s!==Ta?null:{type:s,header:ja(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Ha(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=Ha(t.type);return s!==Aa?null:{type:s,header:ja(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:Ha(t.session_type),last_message:Qa(t.last_message),updated_at:Ha(t.updated_at),pinned_time:Ha(t.pinned_time),unread_count:Ha(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Ha(t.read_receipt),remind_type:Ha(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:Ha(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=Ha(t.type);return s!==Sa?null:{type:s,header:ja(t.header),code:Ha(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Ya=async t=>{const s=t.client.getCacheManager(),r=t.client.getRestContext(),n=t.client.getSessionListSyncWsUrls();if(!s||0===n.length)throw new e.ConnectionError("session-list sync websocket is unavailable",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[o,i]=r.appKey.split("#");if(!o||!i)throw new e.ValidationError("session-list appKey is invalid",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{appKey:r.appKey}});const a=s.loadSessionListCheckpoint(),c=(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:i,username:r.userId,lastSyncTime:(d=a.sessionsLastSyncTs,Math.max(0,d-e.SESSION_LIST_SYNC_OVERLAP_MS)),params:t.params});var d;const l=new $a;let u=0,h=a.sessionsLastSyncTs;return await t.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:t.session.getRequestId(),encode:()=>l.encodeRequest(c),decode:e=>{const t=l.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===(n=s).code?new e.AuthenticationError(n.message,{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:n.code}}):1003===n.code?new e.SDKError(n.message,e.ERROR_CODES.SERVER_BUSY,{details:{protocol:"session-list",responseCode:n.code}}):1501===n.code||1001===n.code?new e.ValidationError(n.message,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:n.code}}):1503===n.code?new e.SDKError(n.message,e.ERROR_CODES.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:n.code}}):(n.code,new e.SDKError(n.message,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:n.code}}));var n;if(11!==s.type)throw new e.SDKError("session-list response type is invalid",e.ERROR_CODES.MESSAGE_DECODE_FAILED,{details:{responseType:s.type}});const o=s,i=o.header?.requestId;if(i&&i!==t.session.getRequestId())return;u+=1,e.logger.debug("Decoded session-list sync raw response",{requestId:t.session.getRequestId(),batchSequence:u,response:o});const a=Ba(o,r.userId),c=t.session.pushBatch({requestId:t.session.getRequestId(),batchSequence:u,sessions:a,isLastBatch:!0===o.isLastBatch,lastSyncFinishedTs:o.lastSyncFinishedTs});if("number"==typeof o.lastSyncFinishedTs&&(h=o.lastSyncFinishedTs),!c.done)return;return{done:!0,result:{items:t.session.getItems(),lastSyncFinishedTs:h}}}})},Ja=()=>Date.now(),Xa={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Za=(e,t)=>({status:e,determinedAt:Ja(),reason:t}),ec=t=>t instanceof e.SDKError&&(t.code===e.ERROR_CODES.SERVER_BUSY||1103===t.code),tc=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:ec(e)});class sc{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.ERROR_CODES.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 va,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 r=this.client.getCacheManager();if(!r)return[];let n=!1;const o=e=>{n||(n=!0,this.client.emitSyncDataFinished(e))};this.activeFinish=o;try{this.client.emitSyncDataStart("conversation");const n=await this.tryDirectFallback(r);if(this.cancelled)return[];if(n)return this.client.emitConversationListUpdate("conversation",!0),o({dataType:"conversation",status:"success"}),n;const a=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let d=0;const l=await async function(e,t,s={}){const r={...ma,...s};let n;for(let i=1;i<=r.maxAttempts;i++)try{return await e()}catch(o){if(n=o,!t(o))throw o;if(i>=r.maxAttempts)throw o;const e=ga(i,r);await fa(e)}throw n}(async()=>{if(this.cancelled)throw new e.SDKError("session-list sync controller is cancelled");d+=1;const r=1===d?t:this.createRetrySession();r.start();try{return await Ya({client:this.client,session:r,params:s})}catch(n){throw this.cancelled||r.fail(),n}},e=>!this.cancelled&&ec(e),Xa);if(this.cancelled)return[];const u={result:l,syncStartedAt:t.getStartedAt()},h=u.result.items;this.capabilityState={status:"available",determinedAt:Ja()};const p={lastSyncTime:u.result.lastSyncFinishedTs,lastSyncFinishedTs:u.result.lastSyncFinishedTs,sessionsLastSyncTs:u.result.lastSyncFinishedTs,lastSuccessfulAt:Ja()};try{if(await r.commitSessionListSync({items:h,mode:a,checkpoint:p,syncStartedAt:u.syncStartedAt}),this.cancelled)return[]}catch(i){if(this.cancelled)return[];t.fail();const s=new e.StorageError("Session-list final persistence failed",{details:{cause:i instanceof Error?i.message:String(i)}});return this.client.emitConversationListUpdate("conversation",!0),o({dataType:"conversation",status:"failed",error:tc(s)}),r.loadSessionList()}const m=r.loadSessionList();return r.updateConversationsFromServer(m.map(c.toConversationSummary),{syncStartedAt:u.syncStartedAt}),await r.flushPending(),this.cancelled?[]:(this.client.emitConversationListUpdate("conversation","full"===a),o({dataType:"conversation",status:"success"}),m)}catch(i){if(this.cancelled)return[];const s=i instanceof e.SDKError?i:new e.SDKError(i instanceof Error?i.message:String(i));t.fail();const n=(t=>t.code===e.ERROR_CODES.OPERATION_UNSUPPORTED||t.code===e.ERROR_CODES.AUTH_UNAUTHORIZED?{capabilityState:Za("unsupported",t.message),shouldUseFallback:!0}:t.code===e.ERROR_CODES.AUTH_TOKEN_EXPIRED||t.code===e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:t.code===e.ERROR_CODES.SERVER_BUSY||1103===t.code?{shouldUseFallback:!0,shouldRetry:!0}:t.code===e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(s);n.capabilityState&&(this.capabilityState=n.capabilityState),n.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const a=await this.buildFallbackSessionList(r);return this.cancelled?[]:(n.shouldUseFallback&&r.replaceSessionList(a),this.client.emitConversationListUpdate("conversation",!0),o({dataType:"conversation",status:"failed",error:tc(s)}),a)}finally{this.activeFinish===o&&(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(),r=this.client.isSessionListDnsProbeAvailable();if(!s&&!r){this.capabilityState=Za("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 va}async buildFallbackSessionList(e){return await(async(e,t)=>await Ia(e,t))(e.loadConversationSummaries(),this.client)}}const rc=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),nc=async t=>{if("string"==typeof t||rc(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):rc(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 e.SDKError("sync websocket frame payload type is invalid",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof t}})},oc=t=>{const s=Math.max(t-1,0),r=e.SYNC_WEBSOCKET_RETRY_INITIAL_DELAY*Math.pow(e.SYNC_WEBSOCKET_RETRY_BACKOFF_MULTIPLIER,s);return Math.min(r,e.SYNC_WEBSOCKET_RETRY_MAX_DELAY)},ic=async e=>{await new Promise(t=>{setTimeout(t,e)})},ac=e=>e instanceof Error?e:new Error(String(e));class cc{constructor(e){this.pending=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 e.SDKError("sync websocket session is cancelled",e.ERROR_CODES.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:t.requestId}});if(this.pending.has(t.requestId))throw new e.SDKError("sync websocket requestId is duplicated",e.ERROR_CODES.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(r){this.rejectPending(t.requestId,ac(r))}return await s}cancel(t="sync-websocket-cancelled"){this.cancelled=!0;const s=new e.SDKError("sync websocket cancelled",e.ERROR_CODES.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!==e.SOCKET_READY_STATE.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&&e.logger.warn("sync websocket retry started",this.buildLogContext({reason:t?.message}));try{return void(await this.openSocket())}catch(s){if(t=ac(s),this.cancelled||0===this.pending.size)throw t;if(this.attempt>=3)throw e.logger.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),t;const r=oc(this.attempt);e.logger.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:t.message})),await ic(r)}}throw new e.ConnectionError("sync websocket retry exhausted",{code:e.ERROR_CODES.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 e.ConnectionError("sync websocket urls are unavailable",{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const s=t[this.urlIndex%t.length];if(this.urlIndex+=1,!s)throw new e.ConnectionError("sync websocket url is invalid",{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=s,this.state="connecting",e.logger.warn("sync websocket connect started",this.buildLogContext());const r=Cr(this.socketAdapter);let n=null;try{const t=await Promise.race([r.connect({url:s}),new Promise((t,s)=>{n=setTimeout(()=>{s(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},e.SYNC_WEBSOCKET_CONNECT_TIMEOUT)})]);n&&clearTimeout(n),this.socket=t,t.onMessage(e=>{this.socket===t&&this.handleMessage(e)}),t.onError(()=>{this.socket===t&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),t.onClose(e=>{if(this.socket===t)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:e.code,closeReason:e.reason}))}),this.state="open",this.resetIdleTimer(),e.logger.warn("sync websocket connected",this.buildLogContext())}catch(o){if(n&&clearTimeout(n),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),o instanceof e.ConnectionError)throw o;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:o instanceof Error?o.message:String(o)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await nc(e);if(!(await this.routeFrame(t)))return}catch(t){const e=ac(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(t){const s=[];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(n){this.pending.delete(e.requestId),e.reject(ac(n)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||r||(r={pending:e,frame:s.frame})}catch(n){s.push(ac(n))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&s.length===this.pending.size)throw new e.SDKError("sync websocket frame decode failed",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:s[0]?.message}});return e.logger.warn("sync websocket frame ignored",this.buildLogContext({reason:s[0]?.message??"requestId not matched"})),!1}handleSocketFailure(t){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(e.logger.warn("sync websocket retry exhausted",this.buildLogContext({reason:t.message})),void this.rejectAll(t)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(ac(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(t){if(t&&this.socket&&this.socket.readyState===e.SOCKET_READY_STATE.OPEN)try{this.socket.send(t.encode()).catch(e=>{this.rejectPending(t.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:e instanceof Error?e.message:String(e)}))}),e.logger.warn("sync websocket request sent",this.buildLogContext({requestId:t.requestId,dataTypes:[t.dataType]})),this.resetIdleTimer()}catch(s){this.rejectPending(t.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:s instanceof Error?s.message:String(s)}))}}rejectPending(e,t){const s=this.pending.get(e);s&&(this.pending.delete(e),s.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(e.logger.warn("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},e.SYNC_WEBSOCKET_COMPLETE_CLOSE_DELAY))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},e.SYNC_WEBSOCKET_IDLE_TIMEOUT))}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(t,s){const r=this.socket;this.socket=null,!r||r.readyState>=e.SOCKET_READY_STATE.CLOSING||(this.state="closing",r.close(t,s))}buildConnectionError(t,s,r={}){return new e.ConnectionError(t,{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:s,url:this.activeUrl,...r}})}buildLogContext(t={}){return{attempt:this.attempt,maxAttempts:3,url:e.sanitizeErrorUrl(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...t}}}const dc=async(t,s,r)=>{const{orgName:n,appName:o}=e.parseAppKey(t.appKey),i=`/${n}/${o}/user/${encodeURIComponent(t.userId)}/roster/metadata/version`,a=new e.RestClient(t.restBaseUrl,{requestAdapter:r,includeRequestId:!0});a.setAuthToken(t.token);try{return((t,s)=>{const r=Date.now(),n=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:r}};if(d.isRecord(t))return d.isRecord(t.data)?n(t.data):n(t);throw new e.ValidationError("Invalid contact metadata response",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{payload:t}})})(await a.get(i),s)}catch(c){if(c instanceof e.ValidationError)throw c;const t=c instanceof e.SDKError&&c.details?c.details:{};throw new e.RestTransportError("Contact metadata request failed",{code:e.ERROR_CODES.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 e.SDKError?c.code:void 0}})}},lc=e=>l.z.string().regex(/^https?:\/\/\S+$/i,e),uc=l.z.object({appKey:l.z.string().min(1,"appKey is required").optional(),appId:l.z.string().min(1,"appId is required").optional(),enableUserInfoSync:l.z.boolean().optional(),enableSyncData:l.z.array(l.z.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:l.z.boolean().optional(),deleteConversationOnGroupDestroyed:l.z.boolean().optional(),syncConversationListConfig:l.z.object({includeEmpty:l.z.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:l.z.boolean().optional(),useFixedDeviceId:l.z.boolean().optional(),deviceId:l.z.string().min(1,"deviceId is required").optional(),serviceConfig:l.z.object({dnsConfigUrls:l.z.array(lc("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:l.z.object({restApiUrl:lc("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(hc="serviceConfig.serverUrls.wsUrl must be a valid URL",l.z.string().regex(/^wss?:\/\/\S+$/i,hc)).optional()}).optional()}).optional(),useReplacedMessageContents:l.z.boolean().optional(),customDeviceName:l.z.string().min(1,"customDeviceName is required").optional(),customOSPlatform:l.z.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:l.z.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:l.z.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:l.z.array(l.z.unknown()).optional(),platformAdapterOptions:l.z.object({prefer:l.z.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:l.z.custom(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:l.z.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:l.z.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:l.z.ZodIssueCode.custom,path:["appKey"],message:"appKey or appId is required"}):s>1&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const r=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=r?.serverUrls&&"object"==typeof r.serverUrls?r.serverUrls:void 0;r?.dnsConfigUrls&&n&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:l.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var hc;const pc=l.z.object({userId:l.z.string().min(1,"userId is required"),token:l.z.string().min(1,"token is required")}),mc=l.z.object({timeoutMs:l.z.number().int("timeoutMs must be an integer").min(e.LOGIN_TIMEOUT_MIN,`timeoutMs must be at least ${e.LOGIN_TIMEOUT_MIN}`).max(e.LOGIN_TIMEOUT_MAX,`timeoutMs must be at most ${e.LOGIN_TIMEOUT_MAX}`).optional()}).strict(),gc=l.z.string().trim().min(1,"token is required"),fc=l.z.object({channelName:l.z.string().trim().min(1,"channelName is required").optional()}).optional(),yc=l.z.array(l.z.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))),Ec=l.z.object({protocol:l.z.string(),domain:l.z.string().optional(),ip:l.z.string().optional(),port:l.z.union([l.z.string(),l.z.number()]).optional()}).passthrough(),Rc=l.z.object({app_key:l.z.string().optional(),rest:l.z.object({hosts:l.z.array(Ec).nonempty()}),"msync-wx":l.z.object({hosts:l.z.array(Ec).nonempty()}),"sync-ws":l.z.object({hosts:l.z.array(Ec).nonempty()}).optional(),enableReportLogs:l.z.enum(["true","false"]).optional(),reportInterval:l.z.number().positive().finite().optional(),enableDataReport:l.z.enum(["true","false"]).optional(),enableMd5Check:l.z.enum(["true","false"]).optional(),uploadinparts_enable:l.z.enum(["true","false"]).optional()}).passthrough(),Ic="5.1.2",vc=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Cc=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function Sc(e){return"object"==typeof e&&null!==e}function Tc(e){return Array.isArray(e)?{hosts:e}:function(e){return Sc(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Ac(s){if(!Sc(s))return t.Validator.validateOrThrow(Rc,s);const r=Tc(s.rest),n=function(e,t,s){for(const r of t){const t=Tc(e[r]);if(t)return{key:r,section:t}}for(const[r,n]of Object.entries(e)){if(!s(r))continue;const e=Tc(n);if(e)return{key:r,section:e}}}(s,Cc,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),o={...s,rest:r??s.rest,"msync-wx":n?.section},i="true"===(a=s.enableReportLogs)||!0===a?"true":"false"===a||!1===a?"false":void 0;var a;i&&(o.enableReportLogs=i);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}(s.reportInterval);void 0!==c?o.reportInterval=c:delete o.reportInterval;const d=function(e){if("true"===e||"false"===e)return e}(s.enableDataReport);d?o.enableDataReport=d:delete o.enableDataReport;const l=function(e){if("true"===e||"false"===e)return e}(s.enableMd5Check);l?o.enableMd5Check=l:delete o.enableMd5Check;const u=function(e){if("true"===e||"false"===e)return e}(s.uploadinparts_enable);return u?o.uploadinparts_enable=u:delete o.uploadinparts_enable,n&&"msync-wx"!==n.key&&e.logger.warn("DNS config websocket section normalized",{sourceKey:n.key}),t.Validator.validateOrThrow(Rc,o)}function Oc(t,s){const r=t.domain||t.ip;if(!r)throw new e.ValidationError("DNS host missing domain/ip",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const n=void 0!==t.port?String(t.port):"";return`${"https"===s?"wss":"ws"}://${n&&"80"!==n&&"443"!==n?`${r}:${n}`:r}/websocket`}function bc(e,t){return"https"===e?"https":"http"===e?"http":t}function _c(t,s){const r=t.domain||t.ip;if(!r)throw new e.ValidationError("DNS rest host missing domain/ip",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const n=void 0!==t.port?String(t.port):"";return`${s}://${n&&"80"!==n&&"443"!==n?`${r}:${n}`:r}`}function Mc(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function Nc(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 Dc(t,s,r,n){const o=new e.RestClient(t,{requestAdapter:r,includeRequestId:!0});let i="/easemob/server.json",a=!0;try{const e=new URL(t),s=""!==e.pathname&&"/"!==e.pathname,r=""!==e.search;(s||r)&&(i="",a=!1)}catch{i="/easemob/server.json",a=!0}if(a){i=`${i}?${(void 0!==s.appId?u.createQueryParams({app_id:s.appId,sdk_version:Ic,file_version:"1"}):u.createQueryParams({app_key:s.appKey,_v:String(Date.now())})).toString()}`}return Ac(await o.get(i,{timeout:n}))}async function wc(t){const s=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:vc;if(0===s.length)throw new e.ValidationError("DNS_CONFIG list is empty",{code:e.ERROR_CODES.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 n;for(const a of s){const s=t.loginDeadline,o=s?.remainingMs();if(s&&void 0!==o&&o<=0)throw s.createTimeoutError();try{const s=void 0!==t.appId?{appId:t.appId}:{appKey:t.appKey},n=void 0===o?void 0:Math.min(e.REQUEST_TIMEOUT,o),i=await Dc(a,s,t.requestAdapter,n),c=void 0!==t.appId?i.app_key:t.appKey;if("string"!=typeof c||0===c.length)throw new e.ValidationError("DNS app_key is required for appId initialization",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const d=Nc(Mc(i["msync-wx"].hosts,r));if(0===d.length)throw new e.ValidationError("DNS msync-wx hosts resolution failed",{code:e.ERROR_CODES.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 e.ValidationError("DNS msync-wx hosts resolution failed",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const u=Mc(i.rest.hosts,r);if(0===u.length)throw new e.ValidationError("DNS rest hosts resolution failed",{code:e.ERROR_CODES.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 e.ValidationError("DNS rest hosts resolution failed",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const p=d.map(e=>Oc(e,bc(e.protocol,r))),m=Oc(l,bc(l.protocol,r));return{appKey:c,websocketUrl:m,websocketUrls:p,baseUrl:a,restBaseUrl:_c(h,bc(h.protocol,r)),dnsConfig:i}}catch(i){if(s&&s.remainingMs()<=0)throw s.createTimeoutError();e.logger.warn("DNS config candidate failed",{baseUrl:a,reason:i instanceof Error?i.message:String(i),error:i instanceof Error&&"function"==typeof i.toJSON?i.toJSON():i}),n=i}}const o={stage:"dns"};throw n&&(o.reason=n.message,"code"in n&&"number"==typeof n.code&&(o.causeCode=n.code)),new e.ConnectionError("DNS_CONFIG exhausted",{code:e.ERROR_CODES.CONNECTION_DNSLIST_FAILED,details:o})}const Lc=t=>{const s=(t=>{const s=t.trim(),r=/^(https?):\/\//i.exec(s);if(!r?.[1])throw new e.ValidationError("REST API URL must use http or https protocol");const n=r[1].toLowerCase(),o=s.slice(r[0].length),i=o.search(/[/?#]/),a=i>=0?o.slice(0,i):o,c=a.lastIndexOf("@"),d=c>=0?a.slice(c+1):a;if(!d)throw new e.ValidationError("REST API URL host is required");let l,u;if(d.startsWith("[")){const t=d.indexOf("]");if(t<=1)throw new e.ValidationError("REST API URL IPv6 host is invalid");l=d.slice(0,t+1);const s=d.slice(t+1);if(s){if(!s.startsWith(":"))throw new e.ValidationError("REST API URL authority is invalid");u=s.slice(1)}}else{const t=d.lastIndexOf(":");if(t>=0){if(d.indexOf(":")!==t)throw new e.ValidationError("REST API URL IPv6 host must use brackets");l=d.slice(0,t),u=d.slice(t+1)}else l=d}if(!l)throw new e.ValidationError("REST API URL host is required");if(void 0!==u){const t=Number(u);if(!/^\d+$/.test(u)||t<1||t>65535)throw new e.ValidationError("REST API URL port is invalid")}return{protocol:n,host:l,port:u}})(t),r="http"===s.protocol&&"80"===s.port||"https"===s.protocol&&"443"===s.port,n="https"===s.protocol?"wss":"ws",o=s.port&&!r?`:${s.port}`:"";return`${n}://${s.host}${o}/ws`},Uc=t=>new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),Pc=e=>{if(!d.isRecord(e))throw Uc("Invalid REST response");return d.isRecord(e.data)?e.data:e},kc=(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}}},xc=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},Fc=t=>{const{orgName:s,appName:r}=e.parseAppKey(t.appKey);return`/${s}/${r}`},Bc=async(e,t)=>{const s=await e.get((e=>`${Fc(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Pc(e),s=kc(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw Uc("Invalid token expires response");return s})(s)},Gc=async(e,t,s)=>{const r=await e.get(((e,t)=>{const s=t?.channelName??"*",r=u.createQueryParams({channelName:s});return`${Fc(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=Pc(e);return{appId:xc(t,["app_id","appId"])??"",rtcToken:xc(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:xc(t,["channel_name","channelName"])??"",rtcUid:kc(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:kc(t,["expires_in","expire","expireAt"])??0}})(r)},qc=async(e,t,s)=>{const r=await e.post((e=>`${Fc(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Pc(e),s={};for(const[r,n]of Object.entries(t)){const e=Number(r);!Number.isSafeInteger(e)||e<0||"string"!=typeof n||(s[e]=n)}return s})(r)},Kc=async(e,t)=>{const s=await e.get((e=>`${Fc(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=d.isRecord(e)&&Array.isArray(e.data)?e.data:[],r=[];for(const n of s){if(!d.isRecord(n))continue;const e=xc(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&r.push(`${t.userId}/${e}`)}return r})(s,t)};class Vc{constructor(e){this.options=e,this.pendingGroups=new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,s){if(!e||!t)return;const r=this.pendingGroups.get(e)??new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,r),this.pendingOrder.push(e));const n=r.get(t);r.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(n?.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()),r=Math.max(1,this.options.maxBatchSize);for(let n=0;n<s.length;n+=r)this.readyGroups.push({groupId:e,targets:s.slice(n,n+r)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const t=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(t<0)return;const s=this.readyGroups.splice(t,1)[0];if(!s)return;this.activeGroupCount+=1,this.activeGroups.add(s.groupId),Promise.resolve(this.options.onFlushGroup(s)).catch(t=>{e.logger.warn("Group namecard hydration queue flush failed",{groupId:s.groupId,userIds:s.targets.map(e=>e.userId),error:t instanceof Error?t.message:String(t)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(s.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),s=t-e;return s<=0?t:e+Math.floor(Math.random()*(s+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class zc{constructor(e){this.options=e,this.pendingTargets=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 t=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<t&&this.readyBatches.length>0;){const t=this.readyBatches.shift();if(!t)return;const r=this.generation;this.activeCount+=1;const n=t.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let o;try{o=Promise.resolve(this.options.onFlush(n))}catch(s){o=Promise.reject(s instanceof Error?s:new Error(String(s)))}o.catch(s=>{const n=t.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(e.logger.warn("User info hydration queue flush failed",{targets:t.map(e=>e.userId),retrying:n.length>0,error:s instanceof Error?s.message:String(s)}),r===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 r=s[t];return void(r&&(s[t]=this.mergeTarget(r,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 Hc{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 e.ConnectionError("Login timeout",{code:e.ERROR_CODES.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 jc=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Wc=class s{constructor(s){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t.ConnectionStatus.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=new Set,this.managerSessionGeneration=0,this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null,this.postLoginTaskContext=null,this.terminalSessionCleanupTask=null,this.config={appKey:s.appKey,appId:s.appId,enableUserInfoSync:s.enableUserInfoSync,enableSyncData:[...s.enableSyncData],enableDeliveryReceipt:s.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:s.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...s.syncConversationListConfig},useCustomAttachmentUpload:s.useCustomAttachmentUpload,enableMd5Check:s.enableMd5Check,serviceConfig:{mode:s.serviceConfig.mode,dnsConfigUrls:[...s.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:s.serviceConfig.hasCustomDnsConfigUrls,serverUrls:s.serviceConfig.serverUrls},useFixedDeviceId:s.useFixedDeviceId,deviceId:s.deviceId,useReplacedMessageContents:s.useReplacedMessageContents,customDeviceName:s.customDeviceName,customOSPlatform:s.customOSPlatform,uiKitVersion:s.uiKitVersion,loginExtensionInfo:s.loginExtensionInfo,cacheEncryptionMode:s.cacheEncryptionMode,profileSync:{...s.profileSync},platformAdapterOptions:s.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=vr(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new pa,e.setLogEntrySink(e=>{this.eventHub.dispatch(n.LogEventName.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 zc({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:e.USER_INFO_HYDRATION_MAX_CONCURRENCY,maxRetries:e.USER_INFO_HYDRATION_MAX_RETRIES,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Vc({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:e.GROUP_NAMECARD_HYDRATION_MIN_WINDOW_MS,maxBatchSize:e.GROUP_NAMECARD_HYDRATION_BATCH_SIZE,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[t.ConnectionEventName.CONNECTING]:e=>{this.updateState(e.state)},[t.ConnectionEventName.CONNECTED]:e=>{this.updateState(e.state)},[t.ConnectionEventName.DISCONNECTED]:e=>{this.updateState(e.state),this.isTerminalManagerSessionDisconnect(e)&&this.startTerminalSessionCleanup(e)},[t.ConnectionEventName.RECONNECT_FAILED]:e=>{this.updateState(e.state)},[n.ChatEventName.MESSAGE]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[n.ChatEventName.STREAM_MESSAGE]:e=>{this.handleIncomingConversationStreamMessage(e)},[t.InternalEventName.MESSAGE_SENT]:e=>{this.handleOutgoingConversationMessage(e)},[n.ChatEventName.MULTI_DEVICE_CONTACT]:e=>{this.handleMultiDeviceContactEvent(e)},[n.ChatEventName.MULTI_DEVICE_CONVERSATION]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[n.ContactEventName.ADDED]:e=>this.handleIncomingContactRosterEvent("add",e),[n.ContactEventName.AGREED]:e=>this.handleIncomingContactRosterEvent("add",e),[n.ContactEventName.INVITED]:e=>this.handleIncomingContactRosterEvent("none",e),[n.ContactEventName.REFUSE]:e=>this.handleIncomingContactRosterEvent("none",e),[n.ContactEventName.DELETED]:e=>this.handleIncomingContactRosterEvent("remove",e),[t.InternalEventName.GROUP_NOTIFY]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===n.GroupEventName.GROUP_DESTROYED&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[t.InternalEventName.CHATROOM_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[t.InternalEventName.CHAT_THREAD_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[t.InternalEventName.USER_INFO_NOTIFY]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(r){const n=t.Validator.validateOrThrow(uc,r),o=n.customOSPlatform,i=s.normalizeServiceConfig(n.serviceConfig),a={appKey:n.appKey,appId:n.appId,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:s.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==o?n.customDeviceName:void 0,customOSPlatform:o,uiKitVersion:n.uiKitVersion,loginExtensionInfo:n.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:e.USER_INFO_HYDRATION_WINDOW_MS,userInfoBatchSize:e.USER_INFO_HYDRATION_BATCH_SIZE,groupNamecardWindowMs:e.GROUP_NAMECARD_HYDRATION_WINDOW_MS,groupNamecardMaxConcurrency:e.GROUP_NAMECARD_HYDRATION_MAX_CONCURRENCY},platformAdapterOptions:n.platformAdapterOptions},c=r.managers??[];if(s.instance){if(!s.isSameConfig(s.instance.config,a))throw new e.ValidationError("ChatClient already initialized with different config",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:s.instance.config,next:a}});return c.length>0&&s.instance.registerManagers(c),s.instance.validateOptionalCapabilityDependencies(),s.instance}return s.instance=new s(a),c.length>0&&s.instance.registerManagers(c),s.instance.validateOptionalCapabilityDependencies(),s.instance}async login(r,n){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const o=t.Validator.validateOrThrow(pc,r),i=t.Validator.validateOrThrow(mc,n??{});if(await this.waitForTerminalSessionCleanup(),this.state===t.ConnectionStatus.CONNECTING||this.state===t.ConnectionStatus.CONNECTED){const t=this.currentUserId&&this.currentUserId!==o.userId;throw new e.ConnectionError(t?"Another user is already logged in":"ChatClient is already connecting or connected",{code:t?e.ERROR_CODES.USER_ALREADY_LOGIN_ANOTHER:e.ERROR_CODES.AUTH_ALREADY_LOGIN,details:{stage:"auth",...t?{currentUserId:this.currentUserId,nextUserId:o.userId}:{}}})}const a=++this.loginAttempt,c=new Hc(a,i.timeoutMs??e.LOGIN_TIMEOUT_DEFAULT);try{let s=this.config.appKey??null;this.activeAppKey=s,e.logger.warn("Login started",{userId:o.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const r=this.platformAdapter??vr(this.config.platformAdapterOptions);this.platformAdapter=r,e.installDataReporter({requestAdapter:r.request,onDiagnostic:(t,s)=>{e.logger.warn(t,s)}});const n=e.startDataReportSession({appKey:s??"default#appkey",uid:o.userId,sdkVersion:Ic,platform:r.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),i=r.runtime.getNetworkType?.();i&&i.then(t=>{e.updateDataReportNetworkType(t)}).catch(()=>{e.updateDataReportNetworkType("unknown")});const l=e.startDataReportOperation({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:o.userId});let u,h,p;this.updateState(t.ConnectionStatus.CONNECTING),this.logReportEnabled=!1,e.setLogReportState("unknown");let m,g=!1,f=!1,y=!0;if("dns"===this.config.serviceConfig.mode){const n=l?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await c.race(wc(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:r.request,loginDeadline:c}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:r.request,loginDeadline:c}));s=t.appKey,this.activeAppKey=s,e.updateDataReportSession({appKey:s}),e.logger.warn("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,restBaseUrl:t.restBaseUrl,syncWebSocketSource:"rest"}),u=t.websocketUrl,h=t.websocketUrls;const o=Lc(t.restBaseUrl);this.contactSyncWsUrls=[o],this.syncConversationListConfigWsUrls=[o],this.contactSyncDnsResolved=!0,p=t.restBaseUrl,g="true"===t.dnsConfig.enableReportLogs,m=t.dnsConfig.reportInterval,f="true"===t.dnsConfig.enableMd5Check,y="false"!==t.dnsConfig.uploadinparts_enable,n?.finish({code:200,success:!0}),e.applyDataReportDnsSwitch(t.dnsConfig.enableDataReport),e.logger.debug("DNS report switch resolved",{enabled:g})}catch(d){const s=d instanceof e.SDKError?d.code:-1,r=d instanceof Error?d.message:String(d);throw n?.finish({code:s,success:!1,description:r}),l?.finish({code:s,success:!1,description:r}),e.applyDataReportDnsSwitch(void 0),e.setLogReportState("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t.ConnectionStatus.DISCONNECTED),c.dispose(),d}}else{const s=this.config.serviceConfig.serverUrls;if(!s?.wsUrl||!s.restApiUrl){const s=new e.ValidationError("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:e.ERROR_CODES.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:s.code,success:!1,description:s.message}),e.applyDataReportDnsSwitch(void 0),this.updateState(t.ConnectionStatus.DISCONNECTED),c.dispose(),s}u=s.wsUrl,p=s.restApiUrl;const r=Lc(p);f=this.config.enableMd5Check,this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!1,e.applyDataReportDnsSwitch(void 0)}if(!s){const s=new e.ValidationError("appKey is unavailable after service discovery",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter(),c.dispose(),s}e.updateLogReportContext({restBaseUrl:p,appKey:s,userId:o.userId,token:o.token,requestAdapter:r.request}),e.setLogReportInterval(m),this.logReportEnabled=g,e.setLogReportState(g?"enabled":"disabled");const E=this.resetCore();if(E?.(),a!==this.loginAttempt){const s=new e.ConnectionError("Login cancelled",{code:e.ERROR_CODES.CONNECTION_CANCELLED,details:{stage:"auth"}});throw l?.finish({code:e.ERROR_CODES.CONNECTION_CANCELLED,success:!1,description:s.message}),this.updateState(t.ConnectionStatus.DISCONNECTED),this.activeAppKey=this.config.appKey??null,e.resetDataReporter(),c.dispose(),s}const R=new Ii({serverUrl:u,serverUrls:h,userId:o.userId,token:o.token,appKey:s,restBaseUrl:p,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:f,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:r,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub);this.core=R,e.updateLogReportContext({resource:R.getClientResource()});const I=l?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:u});try{e.logger.warn("Connecting core websocket",{serverUrl:u,restBaseUrl:p,userId:o.userId});try{await c.race(R.connect(c))}finally{c.dispose()}this.throwIfLoginSessionCancelled(a,R),I?.finish({code:200,success:!0}),l?.finish({code:0,success:!0}),e.logger.warn("Core websocket connected",{userId:o.userId,resource:R.getClientResource()}),this.currentUserId=o.userId,e.updateDataReportSession({uid:o.userId}),this.restBaseUrl=p??null,this.authToken=o.token,this.clientResource=R.getClientResource(),await this.initCacheManager(o.userId),this.throwIfLoginSessionCancelled(a,R),e.logger.warn("Cache initialized after login",{userId:o.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),this.notifyManagersSessionReady(o.userId,this.clientResource),this.startPostLoginTasks(o.userId,a)}catch(d){const s=d instanceof e.SDKError?d.code:-1,r=d instanceof Error?d.message:String(d);if(I?.finish({code:s,success:!1,description:r}),l?.finish({code:s,success:!1,description:r}),this.core===R){const s=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter()}finally{s?.()}}throw d}}finally{c.dispose()}}startPostLoginTasks(t,s){this.cancelPostLoginTasks();const r={attemptId:s,userId:t,cancelled:!1};this.postLoginTaskContext=r,this.runPostLoginTasks(r).catch(t=>{this.isPostLoginTaskActive(r)&&e.logger.warn("Unexpected post-login task failure",{userId:r.userId,reason:t instanceof Error?t.message:String(t)})}).finally(()=>{this.postLoginTaskContext===r&&(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(t){if(!this.isPostLoginTaskActive(t))return;if(await this.runPostLoginTask(t,"self-user-info",async()=>{await this.syncSelfUserInfoAfterLogin()}),!this.isPostLoginTaskActive(t))return;if(this.config.enableSyncData.includes("conversation")&&await this.runPostLoginTask(t,"conversation",async()=>{await this.refreshSessionList(this.config.syncConversationListConfig)}),!this.isPostLoginTaskActive(t))return;const s=this.triggerConfiguredSyncDataAfterLogin(t.userId,t),r=this.logReportEnabled?this.runPostLoginTask(t,"log-report",async()=>{await e.reportLogsNow()}):Promise.resolve();await Promise.all([s,r])}async runPostLoginTask(t,s,r){if(this.isPostLoginTaskActive(t))try{await r()}catch(n){if(!this.isPostLoginTaskActive(t))return;e.logger.warn("Post-login synchronization step failed",{userId:t.userId,task:s,reason:n instanceof Error?n.message:String(n)})}}async logout(){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.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 s=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(),e.setLogReportState("disabled"),e.stopLogReporter(),e.resetDataReporter()}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(t.ConnectionStatus.DISCONNECTED),this.logReportEnabled=!1,s?.()}return}try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await e.reportLogsNow()}catch(r){e.logger.warn("Report logs on logout failed",r)}await this.core.disconnect()}finally{const s=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t.ConnectionStatus.DISCONNECTED),this.logReportEnabled=!1,e.setLogReportState("disabled"),e.stopLogReporter(),e.resetDataReporter()}finally{s?.()}}}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 e.ValidationError("restBaseUrl is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new e.ValidationError("token is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new e.ValidationError("userId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const t=this.clientResource??this.core?.getClientResource();if(!t)throw new e.ValidationError("clientResource is required",{code:e.ERROR_CODES.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(s){const r=t.Validator.validateOrThrow(gc,s);if(!this.core||!this.currentUserId||this.state!==t.ConnectionStatus.CONNECTED)throw new e.ConnectionError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const n=this.getRestContext(),o={...n},i=new e.RestClient(o.restBaseUrl,{errorMap:jc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(r),e.logger.warn("Renew token started",{userId:n.userId});const a=await Bc(i,o);if(a<=Date.now())throw new e.ConnectionError("Token is expired",{code:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const c=this.core.renewToken(r,a);return this.authToken=r,e.updateLogReportContext({token:r}),e.logger.warn("Renew token succeeded",{userId:n.userId,expireAt:a}),c}async getRTCTokenInfo(s){const r=t.Validator.validateOrThrow(fc,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:jc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return o.setAuthToken(n.token),e.logger.warn("Get RTC token info started",{userId:n.userId,hasChannelName:Boolean(r?.channelName)}),Gc(o,n,r)}async getUserIdsWithRTCUids(s){const r=t.Validator.validateOrThrow(yc,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:jc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return o.setAuthToken(n.token),e.logger.warn("Get userIds with RTC UIDs started",{userId:n.userId,count:r.length}),qc(o,n,r)}async getSelfIdsOnOtherPlatform(){const t=this.getRestContext(),s=new e.RestClient(t.restBaseUrl,{errorMap:jc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(t.token),e.logger.warn("Get self ids on other platform started",{userId:t.userId,clientResource:t.clientResource}),Kc(s,t)}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 cc({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===U.START_COMPLETED||e.stream.status===U.FULL||e.stream.status===U.COMPLETED||e.stream.status===U.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:hn(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 r=await h.resolveSingleContactUserInfo(t,{cacheManager:this.cacheManager,fetchUserInfos:s?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=r}async fetchContactEventUserInfos(t){if(0===t.length)return[];const s=this.getUserInfoReadCapability();if(!s)return[];try{return await s.getUserInfoByUserId({userIds:t})}catch(r){return e.logger.warn("Contact roster event user info fetch failed",{userIds:t,error:r}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const t=this.getUserInfoReadCapability();if(t)try{0===(await t.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&e.logger.warn("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(s){e.logger.warn("Self user info sync failed after login",{userId:this.currentUserId,error:s})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=dn(e),s=e.sender.userId;if(!s||!this.cacheManager)return;const r=this.cacheManager.getUserInfoSummaries([s],!1)[0];if(r&&(e.sender={userId:s,nickname:r.nickname??e.sender.nickname,avatarUrl:r.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(r?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(s,t.userInfoUpdateTime):r||this.userInfoHydrationQueue.enqueue(s),"groupChat"!==e.conversationType)return;const n=this.cacheManager.getGroupNamecard(e.conversationId,s,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(n?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,s,t.namecardUpdateTime):n||this.groupNamecardHydrationQueue.enqueue(e.conversationId,s)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{an.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};cn(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(t){const s=this.getUserInfoReadCapability();if(!s||0===t.length)return;const r=t.map(e=>e.userId);let n;try{n=await s.getUserInfoByUserId({userIds:r})}catch(l){throw e.logger.warn("User info hydration failed",{userIds:r,error:l}),l}const o=this.currentUserId,i=o?n.find(e=>e.userId===o):void 0,a=n.filter(e=>e.userId!==o);i&&this.dispatchOwnInfoUpdated(i),a.length>0&&this.dispatchUserInfoUpdated(a),n.length>0&&this.refreshConversationDisplayFromUserInfos(n.map(e=>({userId:e.userId})),"profile");const c=new Set(n.map(e=>e.userId)),d=r.filter(e=>!c.has(e));d.length>0&&e.logger.warn("User info hydration returned partial result",{requestedUserIds:r,missingUserIds:d})}async flushGroupNamecardHydrationBatch(t){const s=this.getGroupNamecardHydrationCapability();if(s&&0!==t.targets.length)try{await s.hydrateMessageProfileGroupNamecards(t.groupId,t.targets)}catch(r){e.logger.warn("Group namecard hydration returned partial result",{groupId:t.groupId,requestedUserIds:t.targets.map(e=>e.userId),error:r})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(t){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(r,n){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!r?.sender?.userId)throw new e.ValidationError("sender.userId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&r.sender.userId!==this.currentUserId)throw new e.ValidationError("sender.userId does not match current user",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(P(r))throw new e.MessageSendError("Stream message send is not supported",{code:e.ERROR_CODES.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:r.msgLocalId,retryable:!1}});if(this.core&&this.state!==t.ConnectionStatus.CONNECTED&&await this.waitForSendConnectionRecovery(this.core),!this.core||this.state!==t.ConnectionStatus.CONNECTED)throw new e.MessageSendError("ChatClient is not connected",{code:e.ERROR_CODES.MESSAGE_NOT_CONNECTED,details:{msgLocalId:r.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(r),this.core.sendMessage(r,n)}async waitForSendConnectionRecovery(t){let s=null;const r=t.recoverConnectionForSend().then(()=>!0).catch(t=>(e.logger.warn("Send connection recovery failed",{error:t instanceof Error?t.message:String(t)}),!1)),n=new Promise(t=>{s=setTimeout(()=>{t(!1)},e.SEND_CONNECTION_RECOVERY_TIMEOUT)}),o=await Promise.race([r,n]);s&&clearTimeout(s),o||e.logger.warn("Send connection recovery wait timed out",{timeoutMs:e.SEND_CONNECTION_RECOVERY_TIMEOUT,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=new Set;for(const n of e){const e="groupChat"===n.conversationType?n.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),r=new Set(s.map(e=>e.userId));for(const n of t)r.has(n)||this.userInfoHydrationQueue.enqueue(n)}dispatchUserGroupNamecardUpdated(e,t,s){e&&t&&this.eventHub.dispatch(n.GroupEventName.USER_GROUP_NAMECARD_UPDATED,{groupId:e,userId:t,namecard:s})}async downloadAndParseCombinePayload(t){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,r){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(s.instance!==this)throw new e.ValidationError("ChatClient is not initialized",{code:e.ERROR_CODES.VALIDATION_REQUIRED});if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.downloadAttachment(t)}decodeServerMessageMeta(t){if(!this.core)throw new e.ValidationError("ChatClient is not connected",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return this.core.decodeServerMessageMeta(t)}registerManagers(t){if(0===t.length)return;const s=new Set;for(const r of t){const t=this.resolveManagerKey(r);if(s.has(t))throw this.buildManagerValidationError(`Manager key duplicated: ${t}`,e.ERROR_CODES.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t});s.add(t)}for(const e of t)this.registerManagerInput(e)}registerManagerInput(e){return s.isManagerConstructor(e)?this.registerManagerConstructor(e):this.registerManagerInstance(e)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),s=this.managerRegistry.get(t);if(s){if(s.constructor===e)return s;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(s),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const r=new e;return r.bind(this,this.managerEventContext),this.managerRegistry.set(t,r),this.registerManagerCapabilities(r),this.attachManager(t,r),this.notifyManagerSessionReady(r),r}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,r){return new e.ValidationError(`${t} requires explicit manager capability: ${s}`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} requires explicit manager capability: ${s}`,rule:"dependency"}],capability:s,requiredManagers:r}})}resolveManagerKey(t){if(s.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",e.ERROR_CODES.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}getManagerKeyFromConstructor(t){const s=t.key;if(!this.isValidManagerKey(s))throw this.buildManagerValidationError("Manager key is required",e.ERROR_CODES.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.ERROR_CODES.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(t,s,r,n,o){return new e.ValidationError(t,{code:s,details:{fields:[{path:r,message:t,rule:n}],...o}})}buildManagerConflictError(t,s,r,n){return this.buildManagerValidationError("Manager key conflict",e.ERROR_CODES.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:t,existingName:s,incomingName:r,reason:n})}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 e.ConnectionError("Login cancelled",{code:e.ERROR_CODES.CONNECTION_CANCELLED,details:{stage:"auth"}})}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new ha({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(c.toConversationItem),r=this.buildConversationListPatch(this.conversationListSnapshot,s,t);(r.reset||0!==r.upserted.length||0!==r.removed.length||r.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=s,this.eventHub.dispatch(n.ChatEventName.CONVERSATION_LIST_UPDATE,{version:this.conversationListVersion,items:s,reason:e,patch:r}))}buildConversationListPatch(e,t,s){const r=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),o=new Set,i=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=r.get(e);t&&this.isConversationListItemEqual(t,d)||(i.push(d),o.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),o.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)o.add(this.buildConversationListKey(d));return{reset:s,upserted:i,removed:a,affectedKeys:[...o],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(t,s){const r=[];this.config.enableSyncData.includes("contact")&&(e.logger.warn("Triggering automatic contact sync after login",{userId:t}),r.push(this.runPostLoginTask(s,"contact",async()=>{await this.triggerContactSync()}))),this.config.enableSyncData.includes("group")&&(e.logger.warn("Triggering automatic group sync after login",{userId:t}),r.push(this.runPostLoginTask(s,"group",async()=>{await this.triggerGroupSync()}))),await Promise.all(r)}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new sc(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const t=this.managerRegistry.get("contactManager");if(!t?.createSyncController)throw new e.ValidationError("ContactManager is required for contact sync",{code:e.ERROR_CODES.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 dc(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 e.ValidationError("GroupManager is required for group sync",{code:e.ERROR_CODES.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(n.ChatEventName.SYNC_DATA_START,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(n.ChatEventName.SYNC_DATA_FINISHED,e)}requireCacheManager(){if(!this.cacheManager)throw new e.ValidationError("cacheManager is required",{code:e.ERROR_CODES.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 e.logger.warn("Derived contact sync websocket is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new e.SDKError("Contact sync websocket urls are unavailable",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw e.logger.warn("Derived contact sync websocket is unavailable for fixed service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new e.SDKError("Contact sync websocket urls are unavailable",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await wc(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=[Lc(e.restBaseUrl)],this.contactSyncDnsResolved=!0}catch(t){throw e.logger.warn("Automatic contact sync REST endpoint DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new e.SDKError("Contact sync websocket dns resolve failed",e.ERROR_CODES.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 e.ValidationError("token is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(t,s){const r=t.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new e.ValidationError("sync websocket URL must use ws or wss protocol");const n=r.indexOf("#"),o=n>=0?r.slice(n):"",i=n>=0?r.slice(0,n):r,a=i.indexOf("?"),c=a>=0?i.slice(0,a):i,d=a>=0?i.slice(a+1):"",l=c.indexOf("://")+3,u=c.indexOf("/",l),h=u<0||"/"===c.slice(u)?`${c}/ws`:c,p=d.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),m=encodeURIComponent(s).replace(/%20/g,"+");return p.push(`token=${m}`),`${h}?${p.join("&")}${o}`}shuffleContactSyncUrls(e){const t=[...e];for(let s=t.length-1;s>0;s-=1){const e=Math.floor(Math.random()*(s+1)),r=t[s],n=t[e];r&&n&&(t[s]=n,t[e]=r)}return t}buildContactRosterRequest(t){const s=this.getRestContext(),{orgName:r,appName:n}=e.parseAppKey(s.appKey);return{type:h.RosterMessageType.REQUEST,header:{resource:s.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:r,app:n,username:s.userId,version:t,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(s){throw this.clearCoreSessionState(),this.updateState(t.ConnectionStatus.DISCONNECTED),e?.(),s}}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 e.ValidationError("appKey is unavailable before DNSConfig resolution",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new e.ValidationError("appKey is unavailable for the current session",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){for(const s of this.managerRegistry.values())try{s.resetSessionRuntime?.()}catch(t){e.logger.warn("Manager session runtime reset failed",{manager:this.getManagerNameFromInstance(s),error:t instanceof Error?t.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 r of this.managerRegistry.values())this.notifyManagerSessionReady(r)}notifyManagerSessionReady(t){const s=this.activeManagerSessionContext;if(s&&t.onSessionReady)try{t.onSessionReady(s)}catch(r){e.logger.warn("Manager session ready hook failed",{manager:this.getManagerNameFromInstance(t),error:r instanceof Error?r.message:"unknown"})}}notifyManagersSessionEnding(t){const s=this.activeManagerSessionContext;if(!s)return Promise.resolve();if(this.managerSessionEndingPromise)return this.managerSessionEndingPromise;const r={...s,reason:t},n=Array.from(this.managerRegistry.values(),t=>{if(!t.onSessionEnding)return Promise.resolve();try{return Promise.resolve(t.onSessionEnding(r)).catch(s=>{e.logger.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(t),error:s instanceof Error?s.message:"unknown"})})}catch(s){return e.logger.warn("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(t),error:s instanceof Error?s.message:"unknown"}),Promise.resolve()}}),o=Promise.all(n).then(()=>{});let i=null;const a=new Promise(s=>{i=setTimeout(()=>{e.logger.warn("Manager session ending hooks timed out",{timeoutMs:e.MANAGER_SESSION_ENDING_TIMEOUT,reason:t}),s()},e.MANAGER_SESSION_ENDING_TIMEOUT)});return this.managerSessionEndingPromise=Promise.race([o,a]).then(()=>{null!==i&&clearTimeout(i),this.activeManagerSessionContext?.generation===s.generation&&(this.activeManagerSessionContext=null)}),this.managerSessionEndingPromise}isTerminalManagerSessionDisconnect(s){return s.reason===t.ConnectionEventReason.TOKEN_EXPIRED||[e.ERROR_CODES.AUTH_TOKEN_EXPIRED,e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE,e.ERROR_CODES.AUTH_LOGIN_TOO_MANY_DEVICES,e.ERROR_CODES.USER_LOGIN_ANOTHER_DEVICE,e.ERROR_CODES.USER_REMOVED,e.ERROR_CODES.USER_KICKED_BY_CHANGE_PASSWORD,e.ERROR_CODES.USER_KICKED_BY_OTHER_DEVICE].includes(s.errorCode??-1)}startTerminalSessionCleanup(t){if(this.terminalSessionCleanupTask)return;e.logger.warn("Terminal session cleanup started",{errorCode:t.errorCode,errorMessage:t.errorMessage,reason:t.reason});const s=this.finishTerminalSessionCleanup().catch(t=>{e.logger.error("Terminal session cleanup failed",t instanceof Error?t:new Error(String(t)))}).finally(()=>{this.terminalSessionCleanupTask===s&&(this.terminalSessionCleanupTask=null)});this.terminalSessionCleanupTask=s}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(s){e.logger.warn("Cache flush on terminal disconnect failed",{error:s instanceof Error?s.message:String(s)})}if(this.logReportEnabled)try{await e.reportLogsNow()}catch(s){e.logger.warn("Report logs on terminal disconnect failed",s)}}finally{const s=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t.ConnectionStatus.DISCONNECTED),this.logReportEnabled=!1,e.setLogReportState("disabled"),e.stopLogReporter(),e.resetDataReporter()}finally{s?.()}}e.logger.warn("Terminal session cleanup finished")}static isSameConfig(e,t){return e.appKey===t.appKey&&(e.appId===t.appId&&(!!s.isSameStringArray(e.enableSyncData,t.enableSyncData)&&(e.useCustomAttachmentUpload===t.useCustomAttachmentUpload&&(e.enableMd5Check===t.enableMd5Check&&(!!s.isSameServiceConfig(e.serviceConfig,t.serviceConfig)&&(e.useFixedDeviceId===t.useFixedDeviceId&&(e.deviceId===t.deviceId&&(e.useReplacedMessageContents===t.useReplacedMessageContents&&(e.customDeviceName===t.customDeviceName&&(e.customOSPlatform===t.customOSPlatform&&(e.platformAdapterOptions?.prefer===t.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===t.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.transportAdapter===t.platformAdapterOptions?.transportAdapter&&(e.platformAdapterOptions?.overrides===t.platformAdapterOptions?.overrides&&(e.uiKitVersion===t.uiKitVersion&&(e.cacheEncryptionMode===t.cacheEncryptionMode&&(e.enableUserInfoSync===t.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===t.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===t.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===t.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===t.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===t.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===t.profileSync.groupNamecardMaxConcurrency))))))))))))))))))))}static normalizeServiceConfig(e){const t=e?.serverUrls;return{mode:t?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??vc,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:t?{restApiUrl:t.restApiUrl,wsUrl:t.wsUrl?s.normalizeFixedWebSocketUrl(t.wsUrl):void 0}:void 0}}static normalizeFixedWebSocketUrl(e){const t=e.search(/[?#]/),s=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t),n=s.indexOf("://")+3,o=s.indexOf("/",n);if(-1===o)return`${s}/websocket${r}`;const i=s.slice(o);return/^\/+$/u.test(i)?`${s.slice(0,o)}/websocket${r}`: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,t){if(e.mode!==t.mode)return!1;if(e.dnsConfigUrls.length!==t.dnsConfigUrls.length)return!1;for(let s=0;s<e.dnsConfigUrls.length;s+=1)if(e.dnsConfigUrls[s]!==t.dnsConfigUrls[s])return!1;return s.isSameServerUrls(e.serverUrls,t.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl)}};Wc.instance=null;let Qc=Wc;exports.AuthenticationError=e.AuthenticationError,exports.ConnectionError=e.ConnectionError,exports.MessageReceiveError=e.MessageReceiveError,exports.MessageSendError=e.MessageSendError,exports.NetworkError=e.NetworkError,exports.RUNTIME_PLATFORMS=e.RUNTIME_PLATFORMS,exports.RestBusinessError=e.RestBusinessError,exports.RestTransportError=e.RestTransportError,exports.SDKError=e.SDKError,exports.StorageError=e.StorageError,exports.UploadError=e.UploadError,exports.ValidationError=e.ValidationError,exports.isSDKError=e.isSDKError,exports.ChatManager=t.ChatManager,exports.LogEventName=n.LogEventName,exports.PushEventName=n.PushEventName,exports.Group=o.Group,exports.GroupManager=o.GroupManager,exports.ContactManager=h.ContactManager,exports.ChatThread=p.ChatThread,exports.ChatThreadManager=p.ChatThreadManager,exports.ChatRoom=m.ChatRoom,exports.ChatRoomManager=m.ChatRoomManager,exports.PresenceManager=g.PresenceManager,exports.PushManager=f.PushManager,exports.UserInfoManager=y.UserInfoManager,exports.CONVERSATION_MARK={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},exports.CacheManager=ha,exports.ChatClient=Qc,exports.ImageType={ORIGINAL:"original",LARGE:"large"},exports.StreamMessageStatus=U,exports.createPlatformAdapter=vr,exports.detectRuntimePlatform=(e,t)=>_t(t,e).platform,exports.setConsoleLogEnabled=function(t){e.setConsoleLogEnabled(t)},exports.setLogLevel=function(t){e.setLogLevel(t)};
|