easemob-websdk 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-manager.d.ts +3 -0
- package/cache/cache-store.d.ts +6 -4
- package/cache/cache-utils.d.ts +1 -1
- package/chunks/cache-utils-B99glc0H.js +1 -0
- package/chunks/cache-utils-gowrxNr8.cjs +1 -0
- package/chunks/chat-manager-5wHx7UeW.cjs +1 -0
- package/chunks/chat-manager-DdAnJpcH.js +2 -0
- package/chunks/common-BIpcR2uQ.cjs +1 -0
- package/chunks/common-BW2KLpvb.js +1 -0
- package/chunks/{group-user-info-resolver-FNRqDg18.js → group-user-info-resolver-Diqjmjyj.js} +1 -1
- package/chunks/{group-user-info-resolver-C5pdiqox.cjs → group-user-info-resolver-Ds35Z1Uf.cjs} +1 -1
- package/chunks/index-BItCF8E7.cjs +1 -0
- package/chunks/{index-uKWbjx-u.js → index-DKksD5YM.js} +1 -1
- package/chunks/{index-BKg4EGcI.cjs → index-DKmdsV1-.cjs} +1 -1
- package/chunks/index-VEUtqiDw.js +1 -0
- package/chunks/query-params-BHyPuD2k.cjs +1 -0
- package/chunks/query-params-Bu3Xq4b6.js +1 -0
- package/chunks/{session-list-query-B6dh-b4Y.cjs → session-list-query-C4OQMvPf.cjs} +1 -1
- package/chunks/{session-list-query-Dnp2HbpW.js → session-list-query-DtoToipt.js} +1 -1
- package/chunks/{user-info-BfRwS4ZA.js → user-info-22jZtcSi.js} +1 -1
- package/chunks/{user-info-icpL0Eaw.cjs → user-info-DsDDTJrw.cjs} +1 -1
- package/index.cjs +1 -1
- package/index.js +2 -2
- 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/index.cjs +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.cjs +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.cjs +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.cjs +1 -1
- package/managers/user-info/index.js +1 -1
- package/package.json +1 -1
- package/platform/env.d.ts +1 -0
- package/utils/query-params.d.ts +16 -0
- package/utils/runtime-global.d.ts +13 -0
- package/utils/storage-error.d.ts +8 -0
- package/chunks/cache-utils-BwRPIZ7n.js +0 -1
- package/chunks/cache-utils-CKbcYPlM.cjs +0 -1
- package/chunks/chat-manager-ChdK26ck.cjs +0 -1
- package/chunks/chat-manager-DH8a6Qj9.js +0 -2
- package/chunks/common-CfAlncj9.cjs +0 -1
- package/chunks/common-DN_g4O3n.js +0 -1
- package/chunks/index-CK3GHdGU.cjs +0 -1
- package/chunks/index-CjofwvEQ.js +0 -1
package/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/common-CfAlncj9.cjs"),t=require("./chunks/chat-manager-ChdK26ck.cjs"),s=require("./chunks/group-user-info-resolver-C5pdiqox.cjs"),r=require("./chunks/reflection-proto-codec-BnQFQdZC.cjs"),n=require("./chunks/event-system-COBJFEIq.cjs"),o=require("./chunks/index-CK3GHdGU.cjs"),i=require("./chunks/profile-version-njNs7R5-.cjs"),a=require("./chunks/session-list-query-B6dh-b4Y.cjs"),c=require("./chunks/cache-utils-CKbcYPlM.cjs"),d=require("zod"),l=require("./chunks/index-BKg4EGcI.cjs"),u=require("./managers/chat-thread/index.cjs"),h=require("./managers/chatroom/index.cjs"),p=require("./managers/presence/index.cjs"),m=require("./managers/push/index.cjs"),g=require("./managers/user-info/index.cjs"),f="onChatRoomDestroyed",y="onMembersJoined",E="onMembersExited",R="onRemovedFromChatRoom",I="onMuteListAdded",v="onMuteListRemoved",S="onAllowListAdded",C="onAllowListRemoved",T="onAllMemberMuteStateChanged",A="onAdminAdded",O="onAdminRemoved",b="onOwnerChanged",_="onAnnouncementChanged",M="onChatRoomInfoChanged",N="onAttributesUpdate",D="onAttributesRemoved",w={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function U(e){return"object"==typeof e.stream&&null!==e.stream}const L=0,P=1,k=2,x=3,F=4,B=0,G=1,q=2,K=3,V=4,z=5,H=6,W=7,j=8,Q=0,$=1,Y=2,J=3,X=4,Z=5,ee=6,te=7,se=8,re=0,ne=1,oe=2,ie=3,ae=4,ce=0,de=1,le=2,ue=3,he=5,pe=0,me=1,ge=2,fe=0,ye=0,Ee=2,Re=0,Ie=1,ve=2,Se=3,Ce=4,Te=5,Ae=6,Oe=7,be=8,_e=9,Me=10,Ne=11,De=12,we=13,Ue=14,Le=15,Pe=16,ke=17,xe=18,Fe=19,Be=20,Ge=1,qe=2,Ke=3,Ve=4,ze=5,He=6,We=7,je=8,Qe="Sorry, user register limit",$e="Sorry, user register rate limit",Ye="Sorry, token expired",Je="Sorry, token or password does not match login info",Xe="Sorry, user not found",Ze="Sorry, the app month live count limit",et="Sorry, the app day live count limit",tt="Sorry, the app online count limit",st={[Ie]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[ve]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Se]:e.ERROR_CODES.VALIDATION_REQUIRED,[Ce]:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,[Te]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[Ae]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[Oe]:e.ERROR_CODES.AUTH_FORBIDDEN,[Fe]:e.ERROR_CODES.AUTH_FORBIDDEN,[be]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[_e]:e.ERROR_CODES.UNKNOWN,[Me]:e.ERROR_CODES.UNKNOWN,[Ne]:e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE,[De]:e.ERROR_CODES.AUTH_FORBIDDEN,[we]:e.ERROR_CODES.AUTH_LOGIN_TOO_MANY_DEVICES,[Ue]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Le]:e.ERROR_CODES.AUTH_USER_MUTED,[Pe]:e.ERROR_CODES.UNKNOWN,[ke]:e.ERROR_CODES.UNKNOWN,[xe]:e.ERROR_CODES.MESSAGE_DECODE_FAILED,[Be]:e.ERROR_CODES.USER_DEVICE_CHANGED},rt=new Set([Ie,ve,Se,Ce,Ae,Oe,Fe,_e,Me,Ne,De,we,Ue,Le,Pe,ke,xe,Be]),nt={[Qe]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[$e]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Ye]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[Je]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Xe]: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},ot=[["limit directed users",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.ERROR_CODES.AUTH_FORBIDDEN]],it={[Ze]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[et]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[tt]: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},at=(t,s)=>{if("number"!=typeof t)return{code:e.ERROR_CODES.UNKNOWN,retryable:!0};const r=((t,s)=>{if(s){if(t===Ie){const t=nt[s];if(void 0!==t)return t;for(const[e,r]of ot)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===Oe?it[s]:t===Fe?e.ERROR_CODES.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===Le?e.ERROR_CODES.AUTH_USER_MUTED:void 0}})(t,s),n=st[t]??e.ERROR_CODES.UNKNOWN;return{code:r??n,retryable:!rt.has(t)}},ct={[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"},dt=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)},lt=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 ut{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 ht={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},pt=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},mt=e=>(e=>pt(e,"canIUse")&&pt(e,"getSystemInfo"))(e)||(e=>pt(e,"request")&&pt(e,"connectSocket"))(e),gt=(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,ft=e=>{const t=e?.miniGlobal;return mt(t)?t:e},yt=e=>void 0!==e.window&&void 0!==e.document,Et=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),Rt=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;try{if(!pt(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},It=e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return ht[r]??s.RUNTIME_PLATFORMS.UNIAPP}catch{return s.RUNTIME_PLATFORMS.UNIAPP}return yt(e)?s.RUNTIME_PLATFORMS.WEB:s.RUNTIME_PLATFORMS.UNIAPP},vt=(e,r)=>{const n=e??t.getRuntimeGlobal();if(r){const e=r===s.RUNTIME_PLATFORMS.UNIAPP||Rt(n);return{platform:r,hostPlatform:e?It(n):r,framework:e?"uniapp":yt(n)?"web":"native",global:e&&n.uni?n.uni:ft(gt(n,r))??n}}return Rt(n)?{platform:s.RUNTIME_PLATFORMS.UNIAPP,hostPlatform:It(n),framework:"uniapp",global:n.uni??n}:mt(n.swan)?{platform:s.RUNTIME_PLATFORMS.BAIDU_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.BAIDU_MINIAPP,framework:"native",global:ft(n.swan)??n.swan}:mt(n.tt)?{platform:s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,framework:"native",global:ft(n.tt)??n.tt}:mt(n.dd)?{platform:s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,framework:"native",global:ft(n.dd)??n.dd}:mt(n.my)?{platform:s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,framework:"native",global:ft(n.my)??n.my}:mt(n.wx)?{platform:s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,framework:"native",global:ft(n.wx)??n.wx}:mt(n.qq)?{platform:s.RUNTIME_PLATFORMS.QQ_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.QQ_MINIAPP,framework:"native",global:ft(n.qq)??n.qq}:mt(n.jd)?{platform:s.RUNTIME_PLATFORMS.JD_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.JD_MINIAPP,framework:"native",global:ft(n.jd)??n.jd}:mt(n.ks)?{platform:s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,framework:"native",global:ft(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:yt(n)?s.RUNTIME_PLATFORMS.ELECTRON_RENDERER:s.RUNTIME_PLATFORMS.ELECTRON_MAIN,hostPlatform:yt(n)?s.RUNTIME_PLATFORMS.ELECTRON_RENDERER:s.RUNTIME_PLATFORMS.ELECTRON_MAIN,framework:"electron",global:n}:Et(n)||yt(n)?{platform:s.RUNTIME_PLATFORMS.WEB,hostPlatform:s.RUNTIME_PLATFORMS.WEB,framework:Et(n)?"worker":"web",global:n}:{platform:s.RUNTIME_PLATFORMS.UNKNOWN,hostPlatform:s.RUNTIME_PLATFORMS.UNKNOWN,framework:"native",global:n}},St=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,Ct=["request","upload","socket","proto"],Tt=(e,t=Ct)=>{const r=((e,t=Ct)=>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}})},At={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}}}}}}}}}},Ot=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 bt{constructor(){this.codecMap=new Map}register(e,t){Ot(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 Ot(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 _t=!1,Mt=null,Nt=null,Dt=null;const wt=e=>e.startsWith(".")?e.slice(1):e,Ut=e=>e instanceof r.lightExports.Namespace,Lt=e=>e instanceof r.lightExports.Type,Pt=e=>{for(const t of e.nestedArray)Lt(t)?r.installReflectionCodecRecursive(t):Ut(t)&&Pt(t)},kt=()=>{_t||(r.lightExports.util.Long=r.Long,r.lightExports.configure(),_t=!0),r.installReflectionRuntime();const e=r.lightExports.Root.fromJSON(At);return Pt(e),e},xt=(e,t)=>{const s=e.nestedArray;for(const n of s){if(Lt(n)){const e=wt(n.fullName);r.installReflectionCodecRecursive(n),t.registerType(e,n);continue}Ut(n)&&xt(n,t)}},Ft=(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}})},Bt=()=>Mt||(Mt=kt(),Mt),Gt=()=>{if(Dt)return Dt;const e=(()=>{if(Nt)return Nt;const e=new bt,t=Bt();return xt(t,e),Nt=e,e})();return Dt={encode(t,s){try{return e.getOrThrow(wt(t)).encode(s)}catch(r){throw Ft(t,r,"encode")}},decode(t,s){try{return e.getOrThrow(wt(t)).decode(s)}catch(r){throw Ft(t,r,"decode")}}},Dt},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},Kt=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)}}}},Vt=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,zt=e=>"function"==typeof e.on&&"function"==typeof e.off,Ht=(e,t,r)=>{if(Vt(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(zt(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}})},Wt=(e,t,r)=>{if(Vt(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(zt(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=Ht(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}})},jt=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?jt(e.data):null;var t},Qt=e=>{const t=new Set,r=new Set,n=new Set,o=new Set;return Ht(e,"open",()=>{t.forEach(e=>{e()})}),Ht(e,"message",(...e)=>{const t=jt(e[0]);null!==t&&r.forEach(e=>{e(t)})}),Ht(e,"error",(...e)=>{const t=e[0];n.forEach(e=>{e(t)})}),Ht(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)})}},$t=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=Wt(o,"open",()=>{d||(d=!0,a(),c(),l(),r(Qt(o)))}),c=Wt(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))})}},Yt=(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}})},Jt=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},Xt=(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{Yt("abort",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{Yt("timeout",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{Yt("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=Jt(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)}}))}}),Zt=(e,t)=>e?"timeout":"abort",es=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 Xt(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=Jt(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?Zt(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}})}}},ts=(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},ss=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=ts(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)}}}},rs=(e,t)=>e+t&4294967295,ns=(e,t,s,r,n,o)=>{return rs((i=rs(rs(t,e),rs(r,o)))<<(a=n)|i>>>32-a,s);var i,a},os=(e,t,s,r,n,o,i)=>ns(t&s|~t&r,e,t,n,o,i),is=(e,t,s,r,n,o,i)=>ns(t&r|s&~r,e,t,n,o,i),as=(e,t,s,r,n,o,i)=>ns(t^s^r,e,t,n,o,i),cs=(e,t,s,r,n,o,i)=>ns(s^(t|~r),e,t,n,o,i),ds=(e,t)=>{let[s,r,n,o]=e;s=os(s,r,n,o,t[0]??0,7,-680876936),o=os(o,s,r,n,t[1]??0,12,-389564586),n=os(n,o,s,r,t[2]??0,17,606105819),r=os(r,n,o,s,t[3]??0,22,-1044525330),s=os(s,r,n,o,t[4]??0,7,-176418897),o=os(o,s,r,n,t[5]??0,12,1200080426),n=os(n,o,s,r,t[6]??0,17,-1473231341),r=os(r,n,o,s,t[7]??0,22,-45705983),s=os(s,r,n,o,t[8]??0,7,1770035416),o=os(o,s,r,n,t[9]??0,12,-1958414417),n=os(n,o,s,r,t[10]??0,17,-42063),r=os(r,n,o,s,t[11]??0,22,-1990404162),s=os(s,r,n,o,t[12]??0,7,1804603682),o=os(o,s,r,n,t[13]??0,12,-40341101),n=os(n,o,s,r,t[14]??0,17,-1502002290),r=os(r,n,o,s,t[15]??0,22,1236535329),s=is(s,r,n,o,t[1]??0,5,-165796510),o=is(o,s,r,n,t[6]??0,9,-1069501632),n=is(n,o,s,r,t[11]??0,14,643717713),r=is(r,n,o,s,t[0]??0,20,-373897302),s=is(s,r,n,o,t[5]??0,5,-701558691),o=is(o,s,r,n,t[10]??0,9,38016083),n=is(n,o,s,r,t[15]??0,14,-660478335),r=is(r,n,o,s,t[4]??0,20,-405537848),s=is(s,r,n,o,t[9]??0,5,568446438),o=is(o,s,r,n,t[14]??0,9,-1019803690),n=is(n,o,s,r,t[3]??0,14,-187363961),r=is(r,n,o,s,t[8]??0,20,1163531501),s=is(s,r,n,o,t[13]??0,5,-1444681467),o=is(o,s,r,n,t[2]??0,9,-51403784),n=is(n,o,s,r,t[7]??0,14,1735328473),r=is(r,n,o,s,t[12]??0,20,-1926607734),s=as(s,r,n,o,t[5]??0,4,-378558),o=as(o,s,r,n,t[8]??0,11,-2022574463),n=as(n,o,s,r,t[11]??0,16,1839030562),r=as(r,n,o,s,t[14]??0,23,-35309556),s=as(s,r,n,o,t[1]??0,4,-1530992060),o=as(o,s,r,n,t[4]??0,11,1272893353),n=as(n,o,s,r,t[7]??0,16,-155497632),r=as(r,n,o,s,t[10]??0,23,-1094730640),s=as(s,r,n,o,t[13]??0,4,681279174),o=as(o,s,r,n,t[0]??0,11,-358537222),n=as(n,o,s,r,t[3]??0,16,-722521979),r=as(r,n,o,s,t[6]??0,23,76029189),s=as(s,r,n,o,t[9]??0,4,-640364487),o=as(o,s,r,n,t[12]??0,11,-421815835),n=as(n,o,s,r,t[15]??0,16,530742520),r=as(r,n,o,s,t[2]??0,23,-995338651),s=cs(s,r,n,o,t[0]??0,6,-198630844),o=cs(o,s,r,n,t[7]??0,10,1126891415),n=cs(n,o,s,r,t[14]??0,15,-1416354905),r=cs(r,n,o,s,t[5]??0,21,-57434055),s=cs(s,r,n,o,t[12]??0,6,1700485571),o=cs(o,s,r,n,t[3]??0,10,-1894986606),n=cs(n,o,s,r,t[10]??0,15,-1051523),r=cs(r,n,o,s,t[1]??0,21,-2054922799),s=cs(s,r,n,o,t[8]??0,6,1873313359),o=cs(o,s,r,n,t[15]??0,10,-30611744),n=cs(n,o,s,r,t[6]??0,15,-1560198380),r=cs(r,n,o,s,t[13]??0,21,1309151649),s=cs(s,r,n,o,t[4]??0,6,-145523070),o=cs(o,s,r,n,t[11]??0,10,-1120210379),n=cs(n,o,s,r,t[2]??0,15,718787259),r=cs(r,n,o,s,t[9]??0,21,-343485551),e[0]=rs(s,e[0]),e[1]=rs(r,e[1]),e[2]=rs(n,e[2]),e[3]=rs(o,e[3])},ls=(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},us=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},hs=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)ds(t,ls(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&&(ds(t,r),r.fill(0));const i=8*e.length;return r[14]=4294967295&i,r[15]=Math.floor(i/4294967296),ds(t,r),t.map(us).join("")},ps=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})},ms=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},gs=()=>({async getImageInfo(e){const t=ms(e),s=await ps(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=ms(e),n=await ps(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=ms(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 hs(new Uint8Array(r))}}),fs=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)},ys=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},Es=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"}})},Rs=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},Is=async(e,t)=>new Promise((s,r)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{r(e instanceof Error?e:new Error(fs(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:fs(e)}})}),vs=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,Ss=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await Is(e,t);return vs(t,s)},Cs=e=>({async getImageInfo(t){const s=ys(t),r=await Is(e,s),n=Rs(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=ys(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 Is(e,n),i=vs(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(fs(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:fs(e)}})}),d=await Ss(e,c),l=await Is(e,d),u=Rs(l.type)??t.mimeType,h=await(async(e,t,r)=>{const n=Es(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(fs(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:fs(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=ys(t),n=await Ss(e,r),o=await(async(e,t)=>{const r=Es(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(fs(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:fs(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 hs(o)}}),Ts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",As=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Os=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=Ts.indexOf(t[i]??""),s=Ts.indexOf(t[i+1]??""),a=t[i+2]??"=",c=t[i+3]??"=",d="="===a?0:Ts.indexOf(a),l="="===c?0:Ts.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},_s=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Ms=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Ns=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(_s(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?Ns(s.data,t+1):e},Ds=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Ms(e);if(_s(e))try{return Ms(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Ms(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=Ds(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=Ds(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)}},ws=(t,s)=>{if("string"==typeof t)return t;const r=t instanceof Uint8Array?t:new Uint8Array(t);if(Os(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+=Ts[i>>18&63],t+=Ts[i>>12&63],t+=void 0===n?"=":Ts[i>>6&63],t+=void 0===o?"=":Ts[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:As(r.subarray(0,8))}),n}const n=new ArrayBuffer(r.byteLength);return new Uint8Array(n).set(r),n},Us=(t,s)=>{const r=Ns(t.data);if("string"==typeof r){if(!Os(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:As(o.subarray(0,8)),decodedSuffixHex:As(o.subarray(Math.max(0,o.length-8)))}),n}const n=Ds(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(!Os(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:As(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:As(a.subarray(0,8)),decodedSuffixHex:As(a.subarray(Math.max(0,a.length-8)))}),i},Ls=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ps=(e,t)=>Ls(e)&&"function"==typeof e[t],ks=e=>e instanceof Error?e.message:Ls(e)&&"string"==typeof e.errMsg?e.errMsg:Ls(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),xs=e=>e?{...e}:{},Fs=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},Bs=e=>{try{e.close()}catch{}},Gs=(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:ks(t)}})))},d=t.downloadFile?.({url:r.url,header:xs(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=Ds(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=Fs(r.signal,()=>{d?.abort(),c("Mini program file download aborted.","abort",!1)})}),qs=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:xs(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{o(),r({status:e.statusCode,headers:e.header??{},data:e.data})},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:ks(e)}}))}});o=Fs(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"}}))})}):Gs(e,t)}),Ks=(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&&Bs(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:ks(e)}})))},u=e=>{if(!(Ps(r=e,"send")&&Ps(r,"close")&&Ps(r,"onOpen")&&Ps(r,"onMessage")&&Ps(r,"onError")&&Ps(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 Bs(o);i=o;const a=()=>{o.offOpen?.(u),o.offError?.(h)},u=()=>{c?Bs(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=Us(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:ws(r,t),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:ks(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))})}),Vs=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:xs(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i(),r({status:e.statusCode,body:e.data})},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:ks(e)}}))}});a.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=Fs(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"}}))})})}),zs=e=>({async getItem(t){if(Ps(e,"getStorageSync"))try{const s=e.getStorageSync(t);return"string"==typeof s&&s.length>0?s:null}catch{return null}return Ps(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(Ps(e,"setStorageSync"))e.setStorageSync(t,s);else if(Ps(e,"setStorage"))return new Promise((r,n)=>{e.setStorage({key:t,data:s,success:r,fail:e=>{n(e instanceof Error?e:new Error(ks(e)))}})})},async removeItem(t){if(Ps(e,"removeStorageSync"))e.removeStorageSync(t);else if(Ps(e,"removeStorage"))return new Promise((s,r)=>{e.removeStorage({key:t,success:s,fail:e=>{r(e instanceof Error?e:new Error(ks(e)))}})})}}),Hs=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>Ps(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 Ps(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(s),Ps(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{Ps(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(s)}},onAppVisibilityChange(t){const s=()=>{t(!0)},r=()=>{t(!1)};return Ps(e,"onAppShow")&&e.onAppShow(s),Ps(e,"onAppHide")&&e.onAppHide(r),t(!0),()=>{Ps(e,"offAppShow")&&e.offAppShow(s),Ps(e,"offAppHide")&&e.offAppHide(r)}}}),Ws=(e,t=s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,r=t)=>{const n=(e=>{if(Ps(e,"request")&&Ps(e,"connectSocket")&&Ps(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?Cs(n):void 0;return{request:qs(n),socket:Ks(n,r),upload:Vs(n),runtime:Hs(n,t),storage:zs(n),imageProcessor:o}},js=[s.RUNTIME_PLATFORMS.WEB,s.RUNTIME_PLATFORMS.ELECTRON_RENDERER,s.RUNTIME_PLATFORMS.REACT_NATIVE],Qs=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},$s=e=>js.includes(e),Ys=(e,t)=>(e!==s.RUNTIME_PLATFORMS.UNIAPP||!Xs(t))&&($s(e)||e===s.RUNTIME_PLATFORMS.UNIAPP&&yt(t)),Js=e=>Qs(e,"getImageInfo")&&Qs(e,"getFileSystemManager"),Xs=e=>"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),Zs=(e,t)=>{if($s(e)&&e!==s.RUNTIME_PLATFORMS.REACT_NATIVE)return gs();if(St(e)&&Js(t))return Cs(t);if(e===s.RUNTIME_PLATFORMS.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(yt(e))return gs();if(Js(e.uni))return Cs(e.uni);if(Js(e.wx))return Cs(e.wx)}},er=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())}},tr=(e,t,r,n)=>{if(e===s.RUNTIME_PLATFORMS.UNIAPP&&Xs(r)&&void 0!==r.uni&&mt(r.uni))return{...Ws(r.uni,e,t),proto:Gt()};if(((e,t)=>!Ys(e,t)&&St(e))(e,r)&&mt(n))return{...Ws(n,e,t),proto:Gt()};const o=r.XMLHttpRequest,i=Ys(e,r),a=i?Kt({fetchImpl:r.fetch}):void 0,c=i?$t({webSocketCtor:r.WebSocket}):void 0,d=e===s.RUNTIME_PLATFORMS.REACT_NATIVE?ss({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?es({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:Gt(),storage:er(r),imageProcessor:i&&e!==s.RUNTIME_PLATFORMS.REACT_NATIVE?gs():Zs(e,n)}},sr=(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}})},rr=e=>{const s=t.getRuntimeGlobal(e?.runtimeInput),r=vt(s,e?.prefer),n=r.platform,o=tr(n,r.hostPlatform,s,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.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);Tt(c);return{platform:n,platformId:n,capability:c,request:sr(a.request,"request"),upload:sr(a.upload,"upload"),socket:sr(a.socket,"socket"),runtime:sr(a.runtime,"runtime"),proto:sr(a.proto,"proto"),storage:sr(a.storage,"storage"),imageProcessor:a.imageProcessor}},nr={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class or{constructor(e={}){this.attemptCount=0,this.config={...nr,...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 ir={interval:3e4,timeout:6e4},ar="function"==typeof TextDecoder?new TextDecoder:null;class cr{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(!cr.isRecord(r))return;"pong"===cr.readString(r.type)&&(this.markAlive(),e.logger.debug("Pong received"))},this.config={...ir,...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)?ar?.decode(t)??lt(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 dr=null;function lr(){return dr||(dr=Bt()),dr}const ur="websdk2:device-info",hr="webim",pr="web",mr=e=>{const s=Date.now(),r=e.deviceId,n=e.customOSPlatform,o=void 0!==n?e.customDeviceName:void 0,i=t.getRuntimeGlobal().localStorage,a=()=>{if(!i)return null;try{const t=i.getItem(ur);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(ur,JSON.stringify(e))}catch{}},d=e=>void 0===n?e:{deviceId:`custom${n}_${e.deviceUuid}`,deviceName:o??r,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=a();if(e)return d(e);if(r===hr){const e=`${pr}_${s}`,t=d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return c(t),t}if(void 0!==n){const e=d({deviceId:`webim_${pr}_${r}`,deviceName:r,deviceUuid:`${pr}_${s}`});return c(e),e}const t={deviceId:`webim_${pr}_${r}`,deviceName:`webim_${pr}_${r}`,deviceUuid:`webim_${pr}_${r}`};return c(t),t}if(r===hr){const e=`random_${pr}_${s}`;return d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==n){return d({deviceId:`webim_${pr}_${r}`,deviceName:r,deviceUuid:`random_${pr}_${s}`})}return{deviceId:`webim_${pr}_${r}`,deviceName:`webim_${pr}_${r}`,deviceUuid:`webim_${pr}_${r}`}},gr=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),fr=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():""},yr=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:je,stringValue:JSON.stringify(r)})}catch{t.push({key:s,type:We,stringValue:Object.prototype.toString.call(r)})}else t.push({key:s,type:We,stringValue:r});else Number.isInteger(r)?t.push({key:s,type:qe,varintValue:r}):t.push({key:s,type:He,doubleValue:r});else t.push({key:s,type:Ge,varintValue:r?1:0});return t},Er=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:We;if(r!==Ge)if(r!==qe&&r!==Ke&&r!==Ve)if(r!==ze)if(r!==He){if(r!==je)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},Rr=new Set(["mute"]),Ir={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},vr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Sr=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Cr=(e,t)=>{const s=e?.map(e=>vr(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Tr=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=Sr(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},Ar=e=>{const t=Sr(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=Ir[r];if(!e)continue;let t=n;if(Rr.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},Or=e=>{const t=Sr(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:vr(t.operator)??vr(t.username)}},br=(e,t)=>({eventName:e,payload:t}),_r=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=vr(e.from?.name),r=(n=e.to,vr(n?.[0]?.name));var n;switch(e.operation){case 1:return br(f,t);case 10:return br(R,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:r??s});case 17:return br(y,{...t,memberIds:Cr(e.members,s),ext:e.ext??e.eventExt});case 18:return br(E,{...t,memberIds:Cr(e.members,s)});case 20:return br(b,{...t,oldOwnerId:s,newOwnerId:r});case 21:return br(A,{...t,adminId:r??s});case 22:return br(O,{...t,adminId:r??s});case 23:{const s=(e=>{const t=Sr(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):Cr(e.members,r),o=46388736e5;return br(I,{...t,userIds:n,muteMembers:s??Object.fromEntries(n.map(e=>[e,o])),muteExpire:Tr(e.reason,e.eventExt)??o})}case 24:return br(v,{...t,userIds:Cr(e.members,r)});case 25:return br(_,{...t,announcement:e.reason??""});case 26:return br(_,{...t,announcement:""});case 29:return br(S,{...t,userIds:Cr(e.members,r)});case 30:return br(C,{...t,userIds:Cr(e.members,r)});case 31:return br(T,{...t,isMuted:!0});case 32:return br(T,{...t,isMuted:!1});case 14:return br(M,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Ar(e.eventExt)});case 43:{const r=Or(e.eventExt);return br(N,{...t,attributes:r.attributes,from:r.from??s})}case 44:{const r=Or(e.eventExt);return br(D,{...t,keyList:r.keyList,from:r.from??s})}default:return null}},Mr=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Nr={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Dr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},wr=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Ur=(e,t)=>{const s=e?.map(e=>Dr(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Lr=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=wr(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},Pr=e=>{const t=wr(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=Nr[r];if(!e)continue;let t=n;if(Mr.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},kr=(e,t)=>{const s=wr(t)??wr(e);return o.normalizeGroupSharedFile(s??void 0)??void 0},xr=(e,t)=>{const s=wr(t)??wr(e);return Dr(s?.fileId)??Dr(s?.file_id)??Dr(e)??""},Fr=(e,t)=>({eventName:e,payload:t}),Br=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=Dr(e.from?.name),r=(o=e.to,Dr(o?.[0]?.name));var o;switch(e.operation){case 4:return Fr(n.GroupEventName.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return Fr(n.GroupEventName.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return Fr(n.GroupEventName.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:r,reason:e.reason});case 7:return Fr(n.GroupEventName.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return Fr(n.GroupEventName.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return Fr(n.GroupEventName.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return Fr(n.GroupEventName.USER_REMOVED,t);case 1:return Fr(n.GroupEventName.GROUP_DESTROYED,t);case 19:return Fr(n.GroupEventName.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=wr(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=Dr(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):Ur(e.members,r);return Fr(n.GroupEventName.MUTE_LIST_ADDED,{...t,userIds:o,muteExpire:o.map(e=>s?.[e]).find(e=>void 0!==e)??Lr(e.reason,e.eventExt)})}case 24:return Fr(n.GroupEventName.MUTE_LIST_REMOVED,{...t,userIds:Ur(e.members,r)});case 29:return Fr(n.GroupEventName.ALLOW_LIST_ADDED,{...t,userIds:Ur(e.members,r)});case 30:return Fr(n.GroupEventName.ALLOW_LIST_REMOVED,{...t,userIds:Ur(e.members,r)});case 31:return Fr(n.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return Fr(n.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return Fr(n.GroupEventName.ADMIN_ADDED,{...t,administratorId:r??s});case 22:return Fr(n.GroupEventName.ADMIN_REMOVED,{...t,administratorId:r??s});case 20:return Fr(n.GroupEventName.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:r});case 17:{const r=Ur(e.members,s);return Fr(n.GroupEventName.MEMBERS_JOINED,{...t,memberIds:r})}case 18:{const r=Ur(e.members,s);return Fr(n.GroupEventName.MEMBERS_EXITED,{...t,memberIds:r})}case 25:return Fr(n.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return Fr(n.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return Fr(n.GroupEventName.SHARED_FILE_ADDED,{...t,sharedFile:kr(e.reason,e.eventExt)});case 28:return Fr(n.GroupEventName.SHARED_FILE_DELETED,{...t,fileId:xr(e.reason,e.eventExt)});case 14:return Fr(n.GroupEventName.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:Pr(e.eventExt)});case 41:return Fr(n.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Fr(n.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const r=(e=>{const t=wr(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:Dr(t.username),attribute:r}})(e.eventExt);return Fr(n.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:r.userId,attribute:r.attribute,from:s,source:e.source??"direct"})}default:return null}},Gr=new WeakMap,qr=(e,t)=>{Gr.set(e,t)},Kr=e=>Gr.get(e)??null,Vr=(e,t)=>{const s=Kr(e);s&&qr(t,s)},zr=new WeakMap,Hr=e=>zr.get(e),Wr="singleChat",jr="groupChat",Qr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},$r=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}},Yr=e=>{if(!Array.isArray(e))return;const t=e.map(e=>Qr(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},Jr=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Xr=(...e)=>{for(const t of e){const e=Qr(t);if(e)return e}},Zr=(e,t)=>Boolean(e&&t&&e===t),en=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),tn=(e,t,s)=>{const r=Yr(e);if(r&&r.length>0)return r;const n=(t??[]).map(e=>Qr(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const o=Qr(s?.name);return o?[o]:[]},sn=e=>{const t=$r(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}}},rn=(t,s)=>{const r=Xr(t.to?.[0]?.clientResource);if(1!==t.to?.length||Qr(t.to[0]?.name)!==s.userId||!en(s.userId,r,s))return null;const n=(o=t.from,Qr(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}},nn=(t,s)=>{if(!t.groupId)return e.logger.warn("Discarded MultiDevice group event without groupId",{operation:t.operation}),null;const r=Xr(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!en(Qr(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=tn(t.members,t.to,t.from);return{category:"group",operation:n,groupId:t.groupId,userIds:o.length>0?o:void 0,operatorId:Qr(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=Xr(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!en(Qr(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=tn(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:Qr(t.from?.name),threadName:t.threadName,deviceId:r,timestamp:t.timestamp,raw:t.raw}},an=(t,s)=>{if("pin"===t.operation||"pin_delete"===t.operation)return null;const r=Xr(t.res,t.raw?.resource,t.raw?.clientResource);if(Zr(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?Wr:jr;var o;const i=Qr(t.id)??(n===Wr?Qr(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:Qr(t.from),deviceId:r,timestamp:$r(t.ts),raw:t.raw}},cn=(t,s)=>{const r=Xr(t.resource,t.raw?.resource,t.raw?.clientResource);if(Zr(r,s.clientResource))return e.logger.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:t.to}),null;const n=Qr(t.to);if(!n)return e.logger.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const o=Qr(t.lastMsgId),i=Yr(t.msgIdList)??(o?[o]:void 0),a=$r(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?jr:Wr,messageIds:i,beforeTimestamp:a,deviceId:r,raw:t.raw}},dn=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var ln=4096,un=65547,hn=15,pn=2113929216,mn=65536,gn=65536,fn=10485760,yn={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},En={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Rn(e){if(!(e>0))return gn;if(e<=gn)return gn;if(e>1073741823)return e;for(var t=gn;t<e;)t*=2;return t}var In={byU16:0,byU32:1},vn=0,Sn=1,Cn=2,Tn=0,An=1;function On(e,t){return e[t]|e[t+1]<<8}function bn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function _n(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var Mn="fast";function Nn(e){return 2654435761*(e>>>0)>>>20&4095}function Dn(e){return 2654435761*(e>>>0)>>>19&8191}function wn(e,t,s){if("fast"===Mn){var r=bn(e,t);return s===In.byU16?Dn(r):Nn(r)}throw new Error("Unsupported hash strategy: "+Mn)}function Un(e,t,s,r,n){s[t]=e-n}function Ln(e,t,s,r,n){Un(t,wn(e,t,r),s,0,n)}function Pn(e,t,s,r){return t[e]+r}function kn(e,t,s,r,n){return Pn(wn(e,t,r),s,0,n)}function xn(e,t,s,r){for(var n=t;t<r-3;){if(bn(e,t)!==bn(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 Fn(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>pn)return 0;switch(c){case vn:default:l=r,u=r;break;case Sn:l=r-e.currentOffset,u=r-e.dictSize;break;case Cn:l=r-e.currentOffset,u=r}if(a===In.byU16&&n>=un)return 0;if(n<13)return qn(t,s,I,v,T,A,i);Ln(t,m,p,a,l),h=wn(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 qn(t,s,I,v,T,A,i);b=Pn(w,p,0,l),c===Cn&&(b<r?(O=R,u=y):(O=0,u=r)),h=wn(t,M,a),Un(m,w,p,0,l)}while(d===An&&b<g||a!==In.byU16&&b+65535<m||!Bn(t,f,m,b,O,c,r));for(;m>I&&b+O>u;){var U=b+O-1;if(t[m-1]!==(c===Cn&&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>=hn){var P=L-hn;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(_n(s,T,m-b),T+=2,c===Cn&&b<r){var F=m+(E-(b+O));if(F>C&&(F=C),(m+=4+(x=Gn(t,f,m+4,b+O+4-y+e.dictionaryStart,F,E-y)))===F&&F<C){var B=xn(t,m,r,C);x+=B,m+=B}}else m+=4+(x=xn(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(Ln(t,m-2,p,a,l),b=kn(t,m,p,a,l),c===Cn&&(b<r?(O=R,u=y):(O=0,u=r)),Ln(t,m,p,a,l),!((d!==An||b>=g)&&b+65535>=m&&Bn(t,f,m,b,O,c,r)))break t;s[_=T++]=0}h=wn(t,++m,a)}return qn(t,s,I,v,T,A,i)}function Bn(e,t,s,r,n,o,i){var a,c=bn(e,s);o===Cn&&r+n<i?a=bn(t,r+n):a=bn(e,r+n);return c===a}function Gn(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 qn(e,t,s,r,n,o,i){var a=r-s;if(i&&n+a+1+Math.floor((a+255-hn)/255)>o)return 0;if(a>=hn){for(t[n++]=240,a-=hn;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 Kn(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 Vn(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)===hn){var T=Kn(e,b={ip:p},m-hn,!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=On(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=Kn(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===Cn&&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 zn(){return{hashTable:new Uint32Array(ln),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function Hn(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function Wn(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?An:Tn;return e.dictionary&&c===r?(l=Fn(e,t,s,r,n,i||0,a||!1,In.byU32,Sn,h),e.dictSize+=n,e.currentOffset+=n,l):(l=Fn(e,t,s,r,n,i||0,a||!1,In.byU32,Cn,h),e.dictionary=t,e.dictionaryStart=r,e.dictSize=n,e.currentOffset+=n,l)}function jn(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 Qn(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function $n(e,t,s,r){return e.prefixSize=r,e.prefixEnd=s+r,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function Yn(e,t,s,r,n,o,i){var a;if(e.prefixEnd===o){if((a=Vn(t,s,r,n,o,i,!0,0,0,Cn,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=Vn(t,s,r,n,o,i,!0,0,0,Cn,o,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=o+a}return a}function Jn(e){var t=(e=e||{}).minWorkArea||gn,s=e.maxWorkArea||fn,r=e.shrinkThreshold||t;t<gn&&(t=gn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=mn+t,this.maxBufferSize=mn+s,this.shrinkThreshold=mn+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:yn.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=zn()}function Xn(e){var t=(e=e||{}).minWorkArea||gn,s=e.maxWorkArea||fn,r=e.shrinkThreshold||t;t<gn&&(t=gn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=mn+t,this.maxBufferSize=mn+s,this.shrinkThreshold=mn+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:yn.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Jn.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<mn?this.offset:mn,n=this.offset>mn?this.offset-mn:0;t.set(this.ringBuffer.subarray(n,n+r),0),jn(this.stream,t,0,r),s=r}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Jn.prototype.compress=function(e,t){var s=e.length;if(s<=0)return En.PARAM_ERROR;if(s>this.maxBufferSize-mn)return En.PARAM_ERROR;if(s>this.ringBufferSize-mn){var r=Rn(s),n=mn+r;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return En.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(jn(this.stream,this.ringBuffer,0,mn),this.offset=mn);var o=this.offset;this.ringBuffer.set(e,o);var i=Wn(this.stream,this.ringBuffer,t,o,s,0,t.length,!0);return i<=0?En.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),i)},Jn.prototype.reset=function(){this.offset=0,Hn(this.stream)},Jn.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Jn.prototype._tryAutoShrink=function(){this.shrinkMode!==yn.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===yn.AUTO_IMMEDIATE||this.shrinkMode===yn.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Jn.prototype.getWorkArea=function(){return this.ringBufferSize-mn},Jn.prototype.getRingBufferSize=function(){return this.ringBufferSize},Jn.prototype.getBaseBufferSize=function(){return this.minBufferSize},Jn.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Jn.prototype.getCurrentOffset=function(){return this.offset},Jn.prototype.getShrinkMode=function(){return this.shrinkMode},Jn.prototype.setShrinkMode=function(e){this.shrinkMode=e},Jn.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Jn.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-mn,s=this.maxBufferSize-mn;if(e<t||e>s)return En.PARAM_ERROR;this.shrinkThreshold=mn+e},Xn.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<mn?this.offset:mn,n=this.offset>mn?this.offset-mn:0;t.set(this.ringBuffer.subarray(n,n+r),0),s=r,$n(this.streamDecode,0,0,r)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},Xn.prototype.decompress=function(e,t,s){var r=e.length;if(r<=0||s<=0)return En.PARAM_ERROR;if(s>this.maxBufferSize-mn)return En.PARAM_ERROR;if(s>this.ringBufferSize-mn){var n=Rn(s),o=mn+n;if(o>this.maxBufferSize&&(o=this.maxBufferSize),!this._resizeBuffer(o))return En.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var i=this.offset-mn;i>0&&this.ringBuffer.set(this.ringBuffer.subarray(i,i+mn),0),$n(this.streamDecode,this.ringBuffer,0,mn),this.offset=mn}var a=Yn(this.streamDecode,e,this.ringBuffer,0,r,this.offset,s);return a<=0?En.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Xn.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Xn.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Xn.prototype._tryAutoShrink=function(){this.shrinkMode!==yn.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===yn.AUTO_IMMEDIATE||this.shrinkMode===yn.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Xn.prototype.getWorkArea=function(){return this.ringBufferSize-mn},Xn.prototype.getRingBufferSize=function(){return this.ringBufferSize},Xn.prototype.getBaseBufferSize=function(){return this.minBufferSize},Xn.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Xn.prototype.getCurrentOffset=function(){return this.offset},Xn.prototype.getShrinkMode=function(){return this.shrinkMode},Xn.prototype.setShrinkMode=function(e){this.shrinkMode=e},Xn.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Xn.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-mn,s=this.maxBufferSize-mn;if(e<t||e>s)return En.PARAM_ERROR;this.shrinkThreshold=mn+e};const Zn={LZ4_MAX_INPUT_SIZE:pn,BLOCK_MAX_SIZE:65536,DICT_SIZE:mn,DEFAULT_WORK_AREA:gn,DEFAULT_MAX_WORK:fn,SHRINK_MODE:yn,LZ4_ERROR:En,alignToPowerOf2:Rn,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".');Mn=e},getHashStrategy:function(){return Mn},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>pn)return 0;if(0===r)return t.length>n?(t[n]=0,1):0;var o=r<un?In.byU16:In.byU32;return Fn({hashTable:new Uint32Array(o===In.byU16?8192:ln),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,0,!1,o,vn,Tn)},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>pn)return 0;if(o<1)return 0;if(0===r)return t[n]=0,1;var i=r<un?In.byU16:In.byU32;return Fn({hashTable:new Uint32Array(i===In.byU16?8192:ln),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,o,!0,i,vn,Tn)},compressBound:function(e){return e<0||e>pn?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:Vn(e,t,s,r,n,o,!0,0,0,vn,n,null,0))},decompressFast:function(e,t,s,r,n){return Vn(e,t,s=s||0,0,r=r||0,n,!1,0,0,Sn,r-65536,0,65536)},createStream:zn,resetStream:Hn,loadDict:function(e,t,s,r){if(e.initCheck&&Hn(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;)Ln(t,o,e.hashTable,In.byU32,n),o+=3;return r},compressContinue:Wn,saveDict:jn,createStreamDecode:Qn,setStreamDecode:$n,decompressSafeContinue:Yn,RingBufferEncoder:Jn,RingBufferDecoder:Xn,_hashU16:Dn,_hashU32:Nn,_TABLE_TYPE:In},eo=268435455,to=new Uint32Array(256);let so=!1;function ro(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;to[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^(to[255&(t^255&r)]??0)}return(4294967295^t)>>>0}var no=(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))(no||{});const oo=268435455;class io{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Zn.DEFAULT_WORK_AREA,maxWorkArea:Zn.DEFAULT_MAX_WORK,shrinkMode:Zn.SHRINK_MODE.MANUAL};this.encoder=new Zn.RingBufferEncoder(e),this.decoder=new Zn.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=Zn.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=ro(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=ro(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),co=(e,t)=>r.encodeWithReflection(e,t).finish();class lo{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=mr({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:[fe],compressType:[ye],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=lr(),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:[ye],encryptType:[fe],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,auth:`$t$${this.context.token}`,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},o=co(s,n),i={version:0,guid:gr({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),auth:`$t$${this.context.token}`,command:x,deviceId:0,encryptType:[fe],payload:o,traceId:e.createTraceId()};return co(r,i)}encodeHeartbeat(){const t=lr(),s=t.lookupType("easemob.pb.CommUnreadUL"),r=t.lookupType("easemob.pb.MSync"),n=co(s,{}),o={version:0,encryptType:[fe],command:P,payload:n,traceId:e.createTraceId()};return co(r,o)}encodeStatisticRebuild(){const t=lr(),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=co(s,{operation:0}),a=r.decode(new Uint8Array);a.id=Date.now(),a.ns=ce,a.payload=i;const c=n.decode(new Uint8Array);c.meta=a;const d=co(n,c);return co(o,{version:0,encryptType:[fe],command:L,payload:d,traceId:e.createTraceId()})}decodeProvision(e){const t=lr().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},r="number"==typeof s.errorCode?s.errorCode:Ie,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===Re,statusCode:r,reason:n,resource:o,authToken:i,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=lr().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=lr().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=lr().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=lr(),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=fr(o.metaId),d=fr(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)!==de)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)!==de)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:B;if(i!==V&&i!==H&&i!==W&&i!==j&&i!==z)return null;const a=this.readJid(r.to),c=Number(fr(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===W)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===V){e.logger.debug("Received READ_ACK MessageBody",n);const t=(Array.isArray(n.ackMessageIds)?n.ackMessageIds:[]).map(e=>fr(e)).filter(e=>Boolean(e)),s=fr(n.ackMessageId);if(0===t.length&&s&&t.push(s),0===t.length||!h)return null;const r=Er(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===z){const e=fr(n.ackMessageId);return e&&h?{type:"message_delivered",data:{messageId:e,from:l,to:u,conversationId:h,conversationType:"singleChat"}}:null}if(i===H){const e=fr(n.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=fr(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:Er(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!==he&&s!==ue&&s!==le&&s!==ce)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===ue?this.decodeRosterMeta(t,n):s===le?this.decodeMucMeta(t,n):s===ce?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(t,s){try{const r=lr(),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!==ce)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=lr(),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=lr(),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=rn({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=lr(),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=nn({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?_r({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}):Br({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&&zr.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=an({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=cn({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(!Jr(r))continue;const e=Xr(r.operator_resource,r.resource,r.clientResource);if(Zr(e,t.clientResource))continue;const n=Qr(r.group)??Qr(r.user);if(!n||!Jr(r.data))continue;const o=Qr(r.group)?jr:Wr,i=r.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:o,remindType:Qr(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(fr(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:dn(e.category),data:e}}decodeNotice(e){const t=lr().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=lr().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=lr(),r=s.lookupType("easemob.pb.CommSyncUL"),n=s.lookupType("easemob.pb.MSync"),o=co(r,{queue:t}),i={version:0,encryptType:[fe],command:L,payload:o,traceId:e.createTraceId()};return co(n,i)}encodeLastSession(t,s){const r=lr(),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i=co(n,{queue:t,key:s}),a={version:0,encryptType:[fe],command:L,payload:i,traceId:e.createTraceId()};return co(o,a)}encodeChatMessage(t,s){const r=lr(),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:yr(t.ext??{}),...d?{meta:d}:{},...c,...t.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},h=co(n,u),p="singleChat"===t.conversationType?this.context.domain:"conference.easemob.com",m=this.resolveDirectedUsers(t),g=this.resolveMetaExt(t),f={id:s,to:gr({appKey:this.context.appKey,name:l.name,domain:p,clientResource:l.clientResource}),ns:de,payload:h,routetype:this.resolveRouteType(t),directedUsers:m,ext:g,...void 0!==t.webhookEnv?{env:t.webhookEnv}:{}},y=co(o,{meta:f}),E={version:0,encryptType:[fe],command:L,payload:y,traceId:e.createTraceId()};return co(i,E)}encodeActionMessage(t,s){const r=lr(),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:yr(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=co(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:gr({appKey:this.context.appKey,name:c.name,domain:"singleChat"===t.conversationType?this.context.domain:"conference.easemob.com",clientResource:c.clientResource}),ns:de,payload:u,routetype:pe,directedUsers:[],ext:[]},p=co(o,{meta:h}),m={version:0,encryptType:[fe],command:L,payload:p,traceId:e.createTraceId()};return co(i,m)}encodeChatRoomOperation(t,s){const r=lr(),n=r.lookupType("easemob.pb.MUCBody"),o=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),a={mucId:gr({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=co(n,a),d={id:s,from:gr({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:le,payload:c},l=co(o,{meta:d}),u={version:0,encryptType:[fe],command:L,payload:l,traceId:e.createTraceId()};return co(i,u)}decodeServerMessageMeta(e){const t=lr(),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?dt(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=lr().lookupType("easemob.pb.MUCBody");for(const n of t){if(!ao(n)||n.ns!==le)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=fr(e.metaId);if(!t||"0"===t)return;const s=e.status??{},r="number"==typeof s.errorCode?s.errorCode:Ie,n="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:fr(e.serverId),ok:r===Re,statusCode:r,reason:n}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:G;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=Er(t.ext),h=Er(e.ext),p=Number(fr(e.timestamp))||Date.now(),m=fr(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)};qr(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=Kr(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(fr(e))}isPublicMessageType(e){return e===G||e===q||e===K}resolveMessageIsOnline(e,t){if(e===K)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(fr(s.streamSeq));if(!Number.isFinite(r))return;const n="number"==typeof s.streamStatus?s.streamStatus:oe,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?w.ERROR:e===re?w.START:e===ne?w.START_COMPLETED:e===ie?w.COMPLETED:e===ae?w.FULL:w.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:Q,text:e.content}}if("cmd"===s.type){const e=s.body;return{type:ee,action:e.action}}if("custom"===s.type){const e=s.body;return{type:te,customEvent:e.event,customExts:yr(e.params??{})}}if("location"===s.type){const e=s.body;return{type:J,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:$,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:Y,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:X,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:Q,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:Z,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:Q,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===se||s===Q&&(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===Q)return{type:"text",body:{content:"string"==typeof t.text?t.text:""}};if(s===ee)return{type:"cmd",body:{action:"string"==typeof t.action?t.action:""}};if(s===te){const e=Er(t.customExts);return{type:"custom",body:{event:"string"==typeof t.customEvent?t.customEvent:"",params:e}}}if(s===J)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===$){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===Y){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===X){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===Z){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 q;case"chatRoom":return K;default:return G}}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 W;case"sendMessageReadReceipts":return V;case"deliveryAck":return z;case"recall":return H;case"update":return j;default:return G}}resolveConversationType(e){return e===q?"groupChat":e===K?"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?yr({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?ge:this.resolveDeliverOnlineOnly(e)?me:pe}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(lt(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?[]:[Ee]}configureCompression(e,t){if(!e||!e.includes(Ee))return void this.disableCompression();this.compressor||(this.compressor=new io);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===no.UPLINK_ONLY||s===no.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===no.DOWNLINK_ONLY||s===no.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?no.UPLINK_ONLY:1===e?no.DOWNLINK_ONLY:2===e?no.BIDIRECTIONAL:no.NONE}disableCompression(){this.compressor&&(this.compressor.mode=no.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}class uo{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 lo({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 or({maxAttempts:this.config.autoReconnectNumMax,initialDelay:e.RECONNECT_INITIAL_DELAY,maxDelay:e.RECONNECT_MAX_DELAY,backoffMultiplier:e.RECONNECT_BACKOFF_MULTIPLIER}),this.heartbeatManager=new cr({interval:this.config.heartBeatWait,timeout:e.HEARTBEAT_TIMEOUT}),this.connectionEventNormalizer=new ut,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(lt(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 x:this.handleProvisionMessage(a.payload);break;case F:this.handleLogoutMessage(a.payload);break;case k:this.handleNoticeMessage(a.payload);break;case P:this.handleUnreadMessage(a.payload);break;case L: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=at(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=$t({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 ho=new Uint8Array([99,109]),po=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mo=e=>Array.isArray(e)&&e.every(po),go=e=>"string"==typeof e?e:void 0,fo=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,yo=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},Eo=(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},Ro=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},Io=(e,t)=>{const s=lr().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:"",So=(t,s,r)=>{const n=(mo(t.contents)?t.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const o=(t=>{const s=fo(t.type)??Q,r=Boolean(go(t.remotePath))||Boolean(go(t.title))||Boolean(go(t.summary))||(fo(t.combineLevel)??0)>0,n=s===Q&&0===t.subType&&r;if(s===se||n){const e=fo(t.combineLevel)??0;return{type:"combine",body:{title:go(t.title)??"",summary:go(t.summary)??"",filename:go(t.displayName)??"combine",filetype:"application/octet-stream",url:go(t.remotePath),secret:go(t.secretKey),fileLength:fo(t.fileLength),combineLevel:e},combineLevel:e}}if(s===Q)return{type:"text",body:{content:go(t.text)??""}};if(s===ee)return{type:"cmd",body:{action:go(t.action)??""}};if(s===te){const e=Er(mo(t.customExts)?t.customExts:void 0);return{type:"custom",body:{event:go(t.customEvent)??"",params:e}}}if(s===J)return{type:"location",body:{latitude:fo(t.latitude)??0,longitude:fo(t.longitude)??0,address:go(t.address),buildingName:go(t.buildingName)}};if(s===$){const s=po(t.size)?t.size:{},r=go(t.remotePath)??"",n=e.deriveImageUrls(r),o=go(t.thumbnailRemotePath),i=e.fromProtocolImageType(t.imageType)===e.IMAGE_TYPE_ORIGINAL;return{type:"image",body:{localUrl:"",filename:go(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:go(t.secretKey),fileLength:fo(t.fileLength),thumbnailUrl:o??n.thumbnailUrl}}}if(s===Y){const e=po(t.size)?t.size:{};return{type:"video",body:{url:go(t.remotePath)??"",filename:go(t.displayName)??"video",filetype:"application/octet-stream",duration:fo(t.duration)??0,width:fo(e.width),height:fo(e.height),secret:go(t.secretKey),fileLength:fo(t.fileLength),thumbnailUrl:go(t.thumbnailRemotePath)}}}if(s===X)return{type:"voice",body:{url:go(t.remotePath)??"",filename:go(t.displayName)??"voice",filetype:"application/octet-stream",duration:fo(t.duration)??0,secret:go(t.secretKey),fileLength:fo(t.fileLength)}};if(s===Z)return{type:"file",body:{url:go(t.remotePath)??"",filename:go(t.displayName)??"file",filetype:"application/octet-stream",secret:go(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)===q?"groupChat":d===K?"chatRoom":"singleChat";var d;const l=a||i,u=Number(fr(r?.timestamp))||Date.now(),h=Er(mo(t.ext)?t.ext:void 0),p={msgServerId:fr(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},Co=(e,t)=>{const s=[];try{const n=Io("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=Io("easemob.pb.MessageBody",o);return So(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=Io("easemob.pb.MessageBody",e);return So(s,t)}catch(n){s.push(n instanceof Error?n.message:String(n))}try{const s=Io("easemob.pb.MessageBody.Content",e);return So({type:G,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("; "))},To=(t,s)=>{const r=lt(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 Co(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)}})}}},Ao=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Oo{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(U(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"};Vr(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"};Vr(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 Vr(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:Ao(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:Ao(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 dt(r)}),r=ho.length+s.reduce((e,t)=>e+4+t.length,0)+1,n=new Uint8Array(r);let o=0;n.set(ho,o),o+=ho.length;for(const e of s){const t=yo(e.length);n.set(t,o),o+=t.length,n.set(e,o),o+=e.length}const i=Ro(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 Vr(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};Vr(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"};Vr(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 bo{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!==w.START&&t.stream.status!==w.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 _o{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new bo}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===w.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?w.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===w.START_COMPLETED||a===w.COMPLETED||a===w.ERROR){const e=a===w.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?w.ERROR:a?w.START_COMPLETED:w.COMPLETED,d=this.buildDispatchMessage(t,{status:c,fullText:o,deltaText:i});this.eventHub.dispatch(n.ChatEventName.STREAM_MESSAGE,d);const l=c===w.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:w.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 Mo{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 No=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Do{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new _o(s),this.messageContexts=new Map,this.recentMessageIds=new Mo(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=at(t,s),n=r.code===e.ERROR_CODES.UNKNOWN?e.ERROR_CODES.MESSAGE_SEND_FAILED:r.code;return{code:n,message:ct[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(U(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(!No(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(!No(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(!No(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(!No(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(!No(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(!No(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(!No(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(!No(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!No(t.message)||"string"!=typeof t.message.type||!No(t.message.body)||!No(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...No(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)No(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)!No(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 wo=e=>e instanceof Error?e.message:String(e);class Uo{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Kt({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<ho.length+1)throw new e.MessageReceiveError("Combine payload is too short",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const s=t.subarray(0,ho.length);if(s[0]!==ho[0]||s[1]!==ho[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=Ro(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=ho.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=Eo(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=To(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 dt(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:wo(a),url:i}})}}}const Lo=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"}},Po=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 ko{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Kt({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:Lo(t),mimeType:Po(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 xo=(t,s,r)=>({Authorization:`Bearer ${t}`,Accept:s,[e.REQUEST_ID_HEADER]:e.createTraceId(),...r??{}}),Fo=async t=>{const s=xo(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)}},Bo=(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(xo(s,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{d.setRequestHeader(e,t)}),d.send(h)}),Go=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 Fo({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=Bo(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 Fo({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?.(_),_},qo=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)}),Ko=gs(),Vo=e=>Object.prototype.toString.call(e),zo=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:Vo(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}},Ho=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}),Wo=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,jo=e=>"object"==typeof e&&null!==e,Qo=(e,t)=>{const r=jo(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(!jo(e))return!1;const t=jo(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 $o{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(!Wo(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:zo(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:Ho(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:Ho(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:Ho(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:Ho(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:Ho(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(!Wo(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(Qo(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:Ho(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:Ho(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"}),Ko;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(!Wo(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(!Wo(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:Ho(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:Ho(s.fileInfo),multipartEnabled:c,uploadMode:d?"multipart":"simple"}),d)try{return await Go(a)}catch(l){const t=l instanceof e.UploadError?l.details:void 0;if(t&&"object"==typeof t&&"init"===t.stage)return qo(a);throw l}return qo(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(!Wo(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:Ho(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 Vr(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 Vr(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 Vr(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 Vr(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 Vr(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(!Qo(s.md5FileInfo.source.sourceType,o))throw o;e.logger.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:t,source:Ho(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 Yo{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 Jo="__internal:core";class Xo{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 uo({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),r=e.restBaseUrl?new $o({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 Oo(s,null,this.eventHub,r),this.messageReceiver=new Do(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Uo(e.platformAdapter?.request),this.attachmentDownloader=new ko(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Jo,{[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 Yo(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(Jo),t.attachmentFileStore.clear()}}const Zo=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)},ei=e=>{const t=atob(e),s=new Uint8Array(new ArrayBuffer(t.length));for(let r=0;r<t.length;r+=1)s[r]=t.charCodeAt(r);return s};class ti{getCrypto(){return t.getRuntimeGlobal().crypto}constructor(e,r){if(this.enabled=(()=>{const e=t.getRuntimeGlobal();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const r=vt(e);if("web"!==r.framework&&"worker"!==r.framework&&r.platform!==s.RUNTIME_PLATFORMS.ELECTRON_RENDERER)return!1;const n=e.crypto;return void 0!==n&&void 0!==n.subtle&&"function"==typeof n.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const t=`${e}:${r}`;this.keyPromise=this.deriveKey(t)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,s=new TextEncoder,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:Zo(r),ct:Zo(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=ei(t.iv),r=ei(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 si="conversationMap",ri="userInfoMap",ni="groupNamecardMap",oi="contactRelationMap",ii="contactVersion",ai="contactMeta",ci="sessionListMap",di="sessionListCheckpoint",li="joinedGroupPreview",ui="metadata",hi=(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 mi=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const s=t.getRuntimeGlobal().localStorage;return s&&"function"==typeof s.getItem?s:null};class gi{constructor(e){this.available=gi.checkAvailable(),this.cryptoAdapter=e??null}static checkAvailable(){const e=mi();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.available)return s;const r=mi();if(!r)return s;try{const e=r.getItem(t);if(!e)return s;let n=e;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const t=await this.cryptoAdapter.decrypt(e);if(null===t)return s;n=t}return c.safeJsonParse(n,s)}catch(n){return e.logger.warn("CacheStore read failed",n),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.available)return;const n=c.safeJsonStringify(s);if(null===n){if(r)throw new TypeError("CacheStore value cannot be serialized");return}const o=mi();if(o)try{const e=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(n):n;o.setItem(t,e)}catch(i){if(c.isQuotaExceededError(i))throw i;if(r)throw i;e.logger.warn("CacheStore write failed",i)}}remove(t){if(!this.available)return;const s=mi();if(s)try{s.removeItem(t)}catch(r){e.logger.warn("CacheStore remove failed",r)}}}const fi={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},yi={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Ei{constructor(){this.items=new Map,this.versionState=fi,this.meta=yi}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(!c.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 c.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 c.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"}:yi}}const Ri=(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}},Ii=(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 Si{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=Ri(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=Ii(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(!c.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=c.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 Ci=(e,t)=>`${e}:${t}`;class Ti{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(Ci(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,r){const n=Ci(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(Ci(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=Ci(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(Ci(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=Ri(n,e,t),i=new Set(o.removed.map(e=>Ci(e.groupId,e.userId)));this.items.clear();for(const a of r)i.has(Ci(a.groupId,a.userId))||this.items.set(Ci(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=Ii(r,Math.min(e,r.length)),o=new Set(n.removed.map(e=>Ci(e.groupId,e.userId)));this.items.clear();for(const i of s)o.has(Ci(i.groupId,i.userId))||this.items.set(Ci(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||!c.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 Ai=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Oi=e=>{const t={...e};return delete t.type,t},bi=e=>{if(!c.isRecord(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!c.isRecord(e.body))return null;const s=((e,t)=>{if(c.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=Ai(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(c.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,d="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return{msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:s,body:Oi(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!==d?{namecardUpdateTime:d}:{}}},_i=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},Mi=(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 Ni{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(Mi)}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(Mi)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!c.isRecord(e))return null;const s=e,r="string"==typeof s.conversationId?s.conversationId:"";if(!r)return null;const n=Ai(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:bi(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:_i(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 Di{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=Ri(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=Ii(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(!c.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 wi=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Ui=e=>e.lastMessageAt??e.updatedAt,Li=e=>[...e].sort((e,t)=>{const s=wi(t)-wi(e);if(0!==s)return s;const r=Ui(t)-Ui(e);return 0!==r?r:e.conversationId.localeCompare(t.conversationId)}),Pi=e=>`${e.conversationType}:${e.conversationId}`,ki=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,xi=(e,t)=>((e,t)=>Ui(t)>Ui(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:ki(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,Fi=e=>{const t=new Map,s=new Set;for(const o of e.snapshot)s.add(Pi(o));for(const o of e.existing)t.set(Pi(o),o);const r=e.snapshot.map(e=>{const s=t.get(Pi(e));return s?xi(e,s):e}),n=e.existing.filter(t=>!s.has(Pi(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Li([...r,...n])},Bi=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Gi=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),qi=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 Ki{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,Bi.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 Vi=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class zi{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 ti(e.appKey,e.userId);this.store=new gi(t??void 0);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=hi(s,si),this.userInfoKey=hi(s,ri),this.groupNamecardKey=hi(s,ni),this.sessionListKey=hi(s,ci),this.sessionListCheckpointKey=hi(s,di),this.joinedGroupPreviewKey=hi(s,li),this.contactRelationKey=hi(s,oi),this.contactVersionKey=hi(s,ii),this.contactMetaKey=hi(s,ai),this.metadataKey=hi(s,ui),this.metadataStore=new pi(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Si,this.userInfoCache=new Di,this.groupNamecardCache=new Ti,this.sessionListCache=new Ni,this.joinedGroupPreviewCache=new o.JoinedGroupPreviewCache,this.contactCache=new Ei,this.userInfoRuntimeStore=new Ki,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=Fi({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?Gi(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([qi(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=Pi(e.nextRecord),s=e.existing.filter(e=>Pi(e)!==t);return Li([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&&c.isRecord(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(o,e);const i=(n&&c.isRecord(n)&&c.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 d=await this.readDump(this.contactRelationKey),l=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(d,l,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&c.isRecord(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&c.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 r=6;for(let n=0;n<=r;n+=1)try{return await this.writeDirtyDomains(t),void(await this.metadataStore.touchLastFlush())}catch(s){if(!c.isQuotaExceededError(s))return this.restoreDirtyBatch(t),void e.logger.warn("Cache flush failed",s);const r=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(t,r),"none"===r)return this.restoreDirtyBatch(t),void e.logger.warn("Cache flush failed: no cache entry can be evicted",s)}e.logger.warn("Cache flush failed after quota cleanup attempts"),this.restoreDirtyBatch(t)}finally{}}async writeDirtyDomains(e){for(const t of Vi)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),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=>wi(e)>0),s=new Map;for(const n of e.incoming)s.set(Pi(n),n);const r=t.length>0?e.existing.filter(e=>!s.has(Pi(e))&&0===wi(e)):e.existing.filter(e=>!s.has(Pi(e)));return Li([...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(Fi({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=Kr(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?Gi(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 Hi{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 Wi={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function ji(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 Qi(e){return new Promise(t=>setTimeout(t,e))}const $i=e=>{const t={...e};return delete t.type,t},Yi=(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:$i(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},Ji=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},Xi=async(e,t)=>{const s=await Ji(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:Yi(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 Zi{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 ea=0,ta=5,sa=10,ra=11,na=1,oa=2,ia=1,aa=2,ca=3,da=e=>e===na?"groupChat":e===oa?"chatRoom":"singleChat",la=()=>lr().lookupType("easemob.pb.MessageBody"),ua=e=>{const t=la().toObject(la().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:0;return 0===o?{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:""}:8===o?{type:"combine",title:"string"==typeof r.title?r.title:"",summary:"string"==typeof r.summary?r.summary:""}:{}},ha=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},ma=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,ga=(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:ma({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},ya=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return ua(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}:ha(e)})(e);return{conversationId:r,conversationType:n,unreadCount:e.unread_count??0,lastMessage:ga(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===ia?"ALL":i===aa?"AT":i===ca?"NONE":"DEFAULT"),conversationName:o.conversationName,conversationAvatar:o.conversationAvatar};var i}),Ea={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 Ra=null,Ia=!1;const va=()=>Ra||(Ia||(r.lightExports.util.Long=r.Long,r.lightExports.configure(),Ia=!0),r.installReflectionRuntime(),Ra=r.lightExports.Root.fromJSON(Ea),r.installReflectionCodecInNamespace(Ra),Ra),Sa=e=>va().lookupType(e),Ca=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}},Ta=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Ca(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Ca(t.protocol_version)??Ca(t.protocolVersion)??0}},Aa=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}},Oa=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Ca(t.id)?String(Ca(t.id)):void 0,from:Aa(t.from),timestamp:Ca(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 ba{constructor(){this.requestType=Sa("easemob.sessionlist.GetSessionListRequest"),this.responseType=Sa("easemob.sessionlist.GetSessionListResponse"),this.errorType=Sa("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:ea}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=Ca(t.type);return s!==sa?null:{type:s,header:Ta(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Ca(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=Ca(t.type);return s!==ra?null:{type:s,header:Ta(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:Ca(t.session_type),last_message:Oa(t.last_message),updated_at:Ca(t.updated_at),pinned_time:Ca(t.pinned_time),unread_count:Ca(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Ca(t.read_receipt),remind_type:Ca(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:Ca(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=Ca(t.type);return s!==ta?null:{type:s,header:Ta(t.header),code:Ca(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const _a=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 ba;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=ya(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}}}})},Ma=()=>Date.now(),Na={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Da=(e,t)=>({status:e,determinedAt:Ma(),reason:t}),wa=t=>t instanceof e.SDKError&&(t.code===e.ERROR_CODES.SERVER_BUSY||1103===t.code),Ua=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:wa(e)});class La{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 Zi,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 c=await async function(e,t,s={}){const r={...Wi,...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=ji(i,r);await Qi(e)}throw n}(async()=>{i+=1;const e=1===i?t:this.createRetrySession();e.start();try{return await _a({client:this.client,session:e,params:s})}catch(r){throw e.fail(),r}},wa,Na),d={result:c,syncStartedAt:t.getStartedAt()},l=d.result.items;this.capabilityState={status:"available",determinedAt:Ma()};const u={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Ma()};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:Ua(s)}),r.loadSessionList()}const h=r.loadSessionList();return r.updateConversationsFromServer(h.map(a.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:Da("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:Ua(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=Da("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new Zi}async buildFallbackSessionList(e){return await(async(e,t)=>await Xi(e,t))(e.loadConversationSummaries(),this.client)}}const Pa=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),ka=async t=>{if("string"==typeof t||Pa(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Pa(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}})},xa=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)},Fa=async e=>{await new Promise(t=>{setTimeout(t,e)})},Ba=e=>e instanceof Error?e:new Error(String(e));class Ga{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,Ba(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=Ba(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=xa(this.attempt);e.logger.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:t.message})),await Fa(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 s=await this.getUrls();if(0===s.length)throw new e.ConnectionError("sync websocket urls are unavailable",{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const r=s[this.urlIndex%s.length];if(this.urlIndex+=1,!r)throw new e.ConnectionError("sync websocket url is invalid",{code:e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=r,this.state="connecting",e.logger.warn("sync websocket connect started",this.buildLogContext());const n=t.getRuntimeGlobal(),o=this.socketAdapter??$t({webSocketCtor:n.WebSocket});if(!o)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let i=null;try{const t=await Promise.race([o.connect({url:r}),new Promise((t,s)=>{i=setTimeout(()=>{s(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},e.SYNC_WEBSOCKET_CONNECT_TIMEOUT)})]);i&&clearTimeout(i),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(a){if(i&&clearTimeout(i),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),a instanceof e.ConnectionError)throw a;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:a instanceof Error?a.message:String(a)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await ka(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Ba(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(Ba(n)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||r||(r={pending:e,frame:s.frame})}catch(n){s.push(Ba(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(Ba(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 qa=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(c.isRecord(t))return c.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(d){if(d instanceof e.ValidationError)throw d;const t=d instanceof e.SDKError&&d.details?d.details:{};throw new e.RestTransportError("Contact metadata request failed",{code:e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:d instanceof Error?d.message:String(d),httpStatus:"number"==typeof t.httpStatus?t.httpStatus:void 0,sourceCode:d instanceof e.SDKError?d.code:void 0}})}},Ka=e=>d.z.string().regex(/^https?:\/\/\S+$/i,e),Va=e=>d.z.string().regex(/^wss?:\/\/\S+$/i,e),za=d.z.object({appKey:d.z.string().min(1,"appKey is required"),enableUserInfoSync:d.z.boolean().optional(),enableSyncData:d.z.array(d.z.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:d.z.boolean().optional(),deleteConversationOnGroupDestroyed:d.z.boolean().optional(),syncConversationListConfig:d.z.object({includeEmpty:d.z.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:d.z.boolean().optional(),useFixedDeviceId:d.z.boolean().optional(),deviceId:d.z.string().min(1,"deviceId is required").optional(),serviceConfig:d.z.object({dnsConfigUrls:d.z.array(Ka("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:d.z.object({restApiUrl:Ka("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:Va("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:Ka("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:Va("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:d.z.boolean().optional(),customDeviceName:d.z.string().min(1,"customDeviceName is required").optional(),customOSPlatform:d.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:d.z.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:d.z.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:d.z.array(d.z.unknown()).optional(),platformAdapterOptions:d.z.object({prefer:d.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:d.z.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:d.z.custom(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{"enableMd5Check"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,r=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&r&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),r&&(r?.restApiUrl||t.addIssue({code:d.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),r?.wsUrl||t.addIssue({code:d.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),Ha=d.z.object({userId:d.z.string().min(1,"userId is required"),token:d.z.string().min(1,"token is required")}),Wa=d.z.string().trim().min(1,"token is required"),ja=d.z.object({channelName:d.z.string().trim().min(1,"channelName is required").optional()}).optional(),Qa=d.z.array(d.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))),$a=d.z.object({protocol:d.z.string(),domain:d.z.string().optional(),ip:d.z.string().optional(),port:d.z.union([d.z.string(),d.z.number()]).optional()}).passthrough(),Ya=d.z.object({rest:d.z.object({hosts:d.z.array($a).nonempty()}),"msync-wx":d.z.object({hosts:d.z.array($a).nonempty()}),"sync-ws":d.z.object({hosts:d.z.array($a).nonempty()}).optional(),enableReportLogs:d.z.enum(["true","false"]).optional(),reportInterval:d.z.number().positive().finite().optional(),enableDataReport:d.z.enum(["true","false"]).optional(),enableMd5Check:d.z.enum(["true","false"]).optional(),uploadinparts_enable:d.z.enum(["true","false"]).optional()}).passthrough(),Ja=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Xa=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],Za=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function ec(e){return"object"==typeof e&&null!==e}function tc(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 sc(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}}}function rc(s){if(!ec(s))return t.Validator.validateOrThrow(Ya,s);const r=tc(s.rest),n=sc(s,Xa,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),o=sc(s,Za,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&&!tc(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(Ya,i)}function nc(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 oc(e,t){return"https"===e?"https":"http"===e?"http":t}function ic(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 cc(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){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}?${new URLSearchParams({app_key:s,_v:String(Date.now())}).toString()}`}return rc(await n.get(o))}function lc(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,oc(t.protocol,s))).filter(e=>"string"==typeof e&&e.length>0):[]}async function uc(t){const s=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:Ja;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=await dc(a,t.appKey,t.requestAdapter),n=cc(ac(s["msync-wx"].hosts,r));if(0===n.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 o=n[0];if(!o)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 i=ac(s.rest.hosts,r);if(0===i.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 c=i[0];if(!c)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 d=n.map(e=>nc(e,oc(e.protocol,r))),l=nc(o,oc(o.protocol,r)),u=lc(s,r);return{websocketUrl:l,websocketUrls:d,syncWebsocketUrls:u,baseUrl:a,restBaseUrl:ic(c,oc(c.protocol,r)),dnsConfig:s}}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 hc=t=>new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),pc=e=>{if(!c.isRecord(e))throw hc("Invalid REST response");return c.isRecord(e.data)?e.data:e},mc=(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}}},gc=(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}`},yc=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=mc(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw hc("Invalid token expires response");return s})(s)},Ec=async(e,t,s)=>{const r=await e.get(((e,t)=>{const s=new URLSearchParams({channelName:t?.channelName??"*"});return`${fc(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${s.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=pc(e);return{appId:gc(t,["app_id","appId"])??"",rtcToken:gc(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:gc(t,["channel_name","channelName"])??"",rtcUid:mc(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:mc(t,["expires_in","expire","expireAt"])??0}})(r)},Rc=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)},Ic=async(e,t)=>{const s=await e.get((e=>`${fc(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=c.isRecord(e)&&Array.isArray(e.data)?e.data:[],r=[];for(const n of s){if(!c.isRecord(n))continue;const e=gc(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 Sc{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 Cc=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Tc=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.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,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.config.platformAdapterOptions&&(this.platformAdapter=rr(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new Hi,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 Sc({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)},[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(za,r),o=n.customOSPlatform,i=s.normalizeServiceConfig(n.serviceConfig),a={appKey:n.appKey,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:s.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==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(Ha,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;e.logger.warn("Login started",{userId:n.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const i=this.platformAdapter??rr(this.config.platformAdapterOptions);this.platformAdapter=i,e.installDataReporter({requestAdapter:i.request,onDiagnostic:(t,s)=>{e.logger.warn(t,s)}});const a=e.startDataReportSession({appKey:this.config.appKey,uid:n.userId,sdkVersion:"5.0.0",platform:i.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),c=i.runtime.getNetworkType?.();c&&c.then(t=>{e.updateDataReportNetworkType(t)}).catch(()=>{e.updateDataReportNetworkType("unknown")});const d=e.startDataReportOperation({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:n.userId});let l,u,h;this.updateState(t.ConnectionStatus.CONNECTING),this.logReportEnabled=!1,e.setLogReportState("unknown");let p,m=!1,g=!1,f=!0;if("dns"===this.config.serviceConfig.mode){const s=d?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await uc({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:i.request});e.logger.warn("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),l=t.websocketUrl,u=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,h=t.restBaseUrl,m="true"===t.dnsConfig.enableReportLogs,p=t.dnsConfig.reportInterval,g="true"===t.dnsConfig.enableMd5Check,f="false"!==t.dnsConfig.uploadinparts_enable,s?.finish({code:200,success:!0}),e.applyDataReportDnsSwitch(t.dnsConfig.enableDataReport),e.logger.debug("DNS report switch resolved",{enabled:m})}catch(E){const r=E instanceof e.SDKError?E.code:-1,n=E instanceof Error?E.message:String(E);throw s?.finish({code:r,success:!1,description:n}),d?.finish({code:r,success:!1,description:n}),e.applyDataReportDnsSwitch(void 0),e.setLogReportState("disabled"),this.updateState(t.ConnectionStatus.DISCONNECTED),E}}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 d?.finish({code:s.code,success:!1,description:s.message}),e.applyDataReportDnsSwitch(void 0),this.updateState(t.ConnectionStatus.DISCONNECTED),s}l=s.wsUrl,h=s.restApiUrl,g=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=s.syncWsUrl?[s.syncWsUrl]:[],this.contactSyncDnsResolved=!1,e.applyDataReportDnsSwitch(void 0)}if(e.updateLogReportContext({restBaseUrl:h,appKey:this.config.appKey,userId:n.userId,token:n.token,requestAdapter:i.request}),e.setLogReportInterval(p),this.logReportEnabled=m,e.setLogReportState(m?"enabled":"disabled"),this.resetCore(),o!==this.loginAttempt){const s=new e.ConnectionError("Login cancelled",{code:e.ERROR_CODES.CONNECTION_CANCELLED,details:{stage:"auth"}});throw d?.finish({code:e.ERROR_CODES.CONNECTION_CANCELLED,success:!1,description:s.message}),this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter(),s}this.core=new Xo({serverUrl:l,serverUrls:u,userId:n.userId,token:n.token,appKey:this.config.appKey,restBaseUrl:h,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:g,enableMultipartUpload:f,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:a,platformAdapter:i,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),e.updateLogReportContext({resource:this.core.getClientResource()});const y=d?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:l});try{if(e.logger.warn("Connecting core websocket",{serverUrl:l,restBaseUrl:h,userId:n.userId}),await this.core.connect(),y?.finish({code:200,success:!0}),d?.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=h??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(E){e.logger.warn("Report logs on login failed",E)}}catch(E){const s=E instanceof e.SDKError?E.code:-1,r=E instanceof Error?E.message:String(E);throw y?.finish({code:s,success:!1,description:r}),d?.finish({code:s,success:!1,description:r}),this.resetCore(),this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter(),E}}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.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.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.config.appKey,userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(s){const r=t.Validator.validateOrThrow(Wa,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:Cc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(r),e.logger.warn("Renew token started",{userId:n.userId});const a=await yc(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(ja,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:Cc,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)}),Ec(o,n,r)}async getUserIdsWithRTCUids(s){const r=t.Validator.validateOrThrow(Qa,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:Cc,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}),Rc(o,n,r)}async getSelfIdsOnOtherPlatform(){const t=this.getRestContext(),s=new e.RestClient(t.restBaseUrl,{errorMap:Cc,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}),Ic(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 Ga({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===w.START_COMPLETED||e.stream.status===w.FULL||e.stream.status===w.COMPLETED||e.stream.status===w.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:Hr(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 l.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=Kr(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=>{Gr.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};qr(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(U(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(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),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 zi({appKey:this.config.appKey,userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const s=this.cacheManager.loadSessionList().map(a.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()}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 La(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 qa(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(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(){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 uc({appKey:this.config.appKey,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(e,t){const s=new URL(e);return""!==s.pathname&&"/"!==s.pathname||(s.pathname="/ws"),s.searchParams.set("token",t),s.toString()}shuffleContactSyncUrls(e){const t=[...e];for(let s=t.length-1;s>0;s-=1){const e=Math.floor(Math.random()*(s+1)),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:l.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())}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}static isSameConfig(e,t){return e.appKey===t.appKey&&(!!s.isSameStringArray(e.enableSyncData,t.enableSyncData)&&(e.useCustomAttachmentUpload===t.useCustomAttachmentUpload&&(e.enableMd5Check===t.enableMd5Check&&(!!s.isSameServiceConfig(e.serviceConfig,t.serviceConfig)&&(e.useFixedDeviceId===t.useFixedDeviceId&&(e.deviceId===t.deviceId&&(e.useReplacedMessageContents===t.useReplacedMessageContents&&(e.customDeviceName===t.customDeviceName&&(e.customOSPlatform===t.customOSPlatform&&(e.platformAdapterOptions?.prefer===t.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===t.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.overrides===t.platformAdapterOptions?.overrides&&(e.uiKitVersion===t.uiKitVersion&&(e.cacheEncryptionMode===t.cacheEncryptionMode&&(e.enableUserInfoSync===t.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===t.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===t.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===t.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===t.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===t.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===t.profileSync.groupNamecardMaxConcurrency))))))))))))))))))}static normalizeServiceConfig(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??Ja,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)}};Tc.instance=null;let Ac=Tc;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=o.Group,exports.GroupManager=o.GroupManager,exports.ContactManager=l.ContactManager,exports.ChatThread=u.ChatThread,exports.ChatThreadManager=u.ChatThreadManager,exports.ChatRoom=h.ChatRoom,exports.ChatRoomManager=h.ChatRoomManager,exports.PresenceManager=p.PresenceManager,exports.PushManager=m.PushManager,exports.UserInfoManager=g.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=zi,exports.ChatClient=Ac,exports.ImageType={ORIGINAL:"original",LARGE:"large"},exports.StreamMessageStatus=w,exports.createPlatformAdapter=rr,exports.detectRuntimePlatform=(e,t)=>vt(t,e).platform;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/common-BIpcR2uQ.cjs"),t=require("./chunks/chat-manager-5wHx7UeW.cjs"),s=require("./chunks/group-user-info-resolver-Ds35Z1Uf.cjs"),r=require("./chunks/reflection-proto-codec-BnQFQdZC.cjs"),n=require("./chunks/event-system-COBJFEIq.cjs"),o=require("./chunks/index-BItCF8E7.cjs"),i=require("./chunks/profile-version-njNs7R5-.cjs"),a=require("./chunks/session-list-query-C4OQMvPf.cjs"),c=require("./chunks/cache-utils-gowrxNr8.cjs"),d=require("zod"),l=require("./chunks/query-params-BHyPuD2k.cjs"),u=require("./chunks/index-DKmdsV1-.cjs"),h=require("./managers/chat-thread/index.cjs"),p=require("./managers/chatroom/index.cjs"),m=require("./managers/presence/index.cjs"),g=require("./managers/push/index.cjs"),f=require("./managers/user-info/index.cjs"),y="onChatRoomDestroyed",E="onMembersJoined",R="onMembersExited",I="onRemovedFromChatRoom",v="onMuteListAdded",S="onMuteListRemoved",C="onAllowListAdded",T="onAllowListRemoved",A="onAllMemberMuteStateChanged",O="onAdminAdded",b="onAdminRemoved",_="onOwnerChanged",M="onAnnouncementChanged",N="onChatRoomInfoChanged",D="onAttributesUpdate",w="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 L(e){return"object"==typeof e.stream&&null!==e.stream}const P=0,k=1,x=2,F=3,B=4,G=0,q=1,K=2,V=3,z=4,H=5,W=6,j=7,Q=8,$=0,Y=1,J=2,X=3,Z=4,ee=5,te=6,se=7,re=8,ne=0,oe=1,ie=2,ae=3,ce=4,de=0,le=1,ue=2,he=3,pe=5,me=0,ge=1,fe=2,ye=0,Ee=0,Re=2,Ie=0,ve=1,Se=2,Ce=3,Te=4,Ae=5,Oe=6,be=7,_e=8,Me=9,Ne=10,De=11,we=12,Ue=13,Le=14,Pe=15,ke=16,xe=17,Fe=18,Be=19,Ge=20,qe=1,Ke=2,Ve=3,ze=4,He=5,We=6,je=7,Qe=8,$e="Sorry, user register limit",Ye="Sorry, user register rate limit",Je="Sorry, token expired",Xe="Sorry, token or password does not match login info",Ze="Sorry, user not found",et="Sorry, the app month live count limit",tt="Sorry, the app day live count limit",st="Sorry, the app online count limit",rt={[ve]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Se]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Ce]:e.ERROR_CODES.VALIDATION_REQUIRED,[Te]:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,[Ae]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[Oe]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[be]:e.ERROR_CODES.AUTH_FORBIDDEN,[Be]:e.ERROR_CODES.AUTH_FORBIDDEN,[_e]:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR,[Me]:e.ERROR_CODES.UNKNOWN,[Ne]:e.ERROR_CODES.UNKNOWN,[De]:e.ERROR_CODES.AUTH_BIND_ANOTHER_DEVICE,[we]:e.ERROR_CODES.AUTH_FORBIDDEN,[Ue]:e.ERROR_CODES.AUTH_LOGIN_TOO_MANY_DEVICES,[Le]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Pe]:e.ERROR_CODES.AUTH_USER_MUTED,[ke]:e.ERROR_CODES.UNKNOWN,[xe]:e.ERROR_CODES.UNKNOWN,[Fe]:e.ERROR_CODES.MESSAGE_DECODE_FAILED,[Ge]:e.ERROR_CODES.USER_DEVICE_CHANGED},nt=new Set([ve,Se,Ce,Te,Oe,be,Be,Me,Ne,De,we,Ue,Le,Pe,ke,xe,Fe,Ge]),ot={[$e]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Ye]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[Je]:e.ERROR_CODES.AUTH_TOKEN_EXPIRED,[Xe]:e.ERROR_CODES.AUTH_UNAUTHORIZED,[Ze]: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},it=[["limit directed users",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",e.ERROR_CODES.AUTH_FORBIDDEN]],at={[et]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[tt]:e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,[st]: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},ct=(t,s)=>{if("number"!=typeof t)return{code:e.ERROR_CODES.UNKNOWN,retryable:!0};const r=((t,s)=>{if(s){if(t===ve){const t=ot[s];if(void 0!==t)return t;for(const[e,r]of it)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===be?at[s]:t===Be?e.ERROR_CODES.MESSAGE_EXTERNAL_LOGIC_BLOCKED:t===Pe?e.ERROR_CODES.AUTH_USER_MUTED:void 0}})(t,s),n=rt[t]??e.ERROR_CODES.UNKNOWN;return{code:r??n,retryable:!nt.has(t)}},dt={[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"},lt=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)},ut=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 ht{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 pt={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},mt=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},gt=e=>(e=>mt(e,"canIUse")&&mt(e,"getSystemInfo"))(e)||(e=>mt(e,"request")&&mt(e,"connectSocket"))(e),ft=e=>mt(e,"request")&&mt(e,"connectSocket")&&mt(e,"uploadFile"),yt=(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,Et=e=>{const t=e?.miniGlobal;return gt(t)?t:e},Rt=e=>{const t=Et(e);return ft(t)?t:void 0},It=e=>void 0!==e.window&&void 0!==e.document,vt=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(gt(t))return!0;try{if(!mt(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},Ct=e=>ft(e.wx)?s.RUNTIME_PLATFORMS.WECHAT_MINIAPP:ft(e.my)?s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP:ft(e.dd)?s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP:ft(e.swan)?s.RUNTIME_PLATFORMS.BAIDU_MINIAPP:ft(e.tt)?s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP:ft(e.qq)?s.RUNTIME_PLATFORMS.QQ_MINIAPP:ft(e.jd)?s.RUNTIME_PLATFORMS.JD_MINIAPP:ft(e.ks)?s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP:void 0,Tt=e=>void 0!==Ct(e),At=e=>{const t=Ct(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return pt[r]??s.RUNTIME_PLATFORMS.UNIAPP}catch{return s.RUNTIME_PLATFORMS.UNIAPP}return It(e)?s.RUNTIME_PLATFORMS.WEB:s.RUNTIME_PLATFORMS.UNIAPP},Ot=(e,t)=>{const s=Rt(yt(e,t));if(s)return s;const r=Rt(e.uni);return r||(e.uni??e)},bt=(t,r)=>{const n=t??e.getRuntimeGlobal();if(r){const e=r===s.RUNTIME_PLATFORMS.UNIAPP||St(n),t=e?At(n):r;return{platform:r,hostPlatform:t,framework:e?"uniapp":It(n)?"web":"native",global:e?Ot(n,t):Et(yt(n,r))??n}}if(St(n)){const e=At(n);return{platform:s.RUNTIME_PLATFORMS.UNIAPP,hostPlatform:e,framework:"uniapp",global:Ot(n,e)}}return gt(n.swan)?{platform:s.RUNTIME_PLATFORMS.BAIDU_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.BAIDU_MINIAPP,framework:"native",global:Et(n.swan)??n.swan}:gt(n.tt)?{platform:s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.TOUTIAO_MINIAPP,framework:"native",global:Et(n.tt)??n.tt}:gt(n.dd)?{platform:s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,framework:"native",global:Et(n.dd)??n.dd}:gt(n.my)?{platform:s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP,framework:"native",global:Et(n.my)??n.my}:gt(n.wx)?{platform:s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,framework:"native",global:Et(n.wx)??n.wx}:gt(n.qq)?{platform:s.RUNTIME_PLATFORMS.QQ_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.QQ_MINIAPP,framework:"native",global:Et(n.qq)??n.qq}:gt(n.jd)?{platform:s.RUNTIME_PLATFORMS.JD_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.JD_MINIAPP,framework:"native",global:Et(n.jd)??n.jd}:gt(n.ks)?{platform:s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,hostPlatform:s.RUNTIME_PLATFORMS.KUAISHOU_MINIAPP,framework:"native",global:Et(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:It(n)?s.RUNTIME_PLATFORMS.ELECTRON_RENDERER:s.RUNTIME_PLATFORMS.ELECTRON_MAIN,hostPlatform:It(n)?s.RUNTIME_PLATFORMS.ELECTRON_RENDERER:s.RUNTIME_PLATFORMS.ELECTRON_MAIN,framework:"electron",global:n}:vt(n)||It(n)?{platform:s.RUNTIME_PLATFORMS.WEB,hostPlatform:s.RUNTIME_PLATFORMS.WEB,framework:vt(n)?"worker":"web",global:n}:{platform:s.RUNTIME_PLATFORMS.UNKNOWN,hostPlatform:s.RUNTIME_PLATFORMS.UNKNOWN,framework:"native",global:n}},_t=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,Mt=["request","upload","socket","proto"],Nt=(e,t=Mt)=>{const r=((e,t=Mt)=>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}})},Dt={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}}}}}}}}}},wt=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 Ut{constructor(){this.codecMap=new Map}register(e,t){wt(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 wt(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 Lt=!1,Pt=null,kt=null,xt=null;const Ft=e=>e.startsWith(".")?e.slice(1):e,Bt=e=>e instanceof r.lightExports.Namespace,Gt=e=>e instanceof r.lightExports.Type,qt=e=>{for(const t of e.nestedArray)Gt(t)?r.installReflectionCodecRecursive(t):Bt(t)&&qt(t)},Kt=()=>{Lt||(r.lightExports.util.Long=r.Long,r.lightExports.configure(),Lt=!0),r.installReflectionRuntime();const e=r.lightExports.Root.fromJSON(Dt);return qt(e),e},Vt=(e,t)=>{const s=e.nestedArray;for(const n of s){if(Gt(n)){const e=Ft(n.fullName);r.installReflectionCodecRecursive(n),t.registerType(e,n);continue}Bt(n)&&Vt(n,t)}},zt=(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}})},Ht=()=>Pt||(Pt=Kt(),Pt),Wt=()=>{if(xt)return xt;const e=(()=>{if(kt)return kt;const e=new Ut,t=Ht();return Vt(t,e),kt=e,e})();return xt={encode(t,s){try{return e.getOrThrow(Ft(t)).encode(s)}catch(r){throw zt(t,r,"encode")}},decode(t,s){try{return e.getOrThrow(Ft(t)).decode(s)}catch(r){throw zt(t,r,"decode")}}},xt},jt=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},Qt=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:jt(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)}}}},$t=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Yt=e=>"function"==typeof e.on&&"function"==typeof e.off,Jt=(e,t,r)=>{if($t(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(Yt(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}})},Xt=(e,t,r)=>{if($t(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(Yt(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=Jt(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}})},Zt=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?Zt(e.data):null;var t},es=e=>{const t=new Set,r=new Set,n=new Set,o=new Set;return Jt(e,"open",()=>{t.forEach(e=>{e()})}),Jt(e,"message",(...e)=>{const t=Zt(e[0]);null!==t&&r.forEach(e=>{e(t)})}),Jt(e,"error",(...e)=>{const t=e[0];n.forEach(e=>{e(t)})}),Jt(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)})}},ts=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=Xt(o,"open",()=>{d||(d=!0,a(),c(),l(),r(es(o)))}),c=Xt(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))})}},ss=(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}})},rs=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},ns=(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{ss("abort",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{ss("timeout",r)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{ss("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=rs(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)}}))}}),os=(e,t)=>e?"timeout":"abort",is=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 ns(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=rs(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?os(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}})}}},as=(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},cs=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=as(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)}}}},ds=(e,t)=>e+t&4294967295,ls=(e,t,s,r,n,o)=>{return ds((i=ds(ds(t,e),ds(r,o)))<<(a=n)|i>>>32-a,s);var i,a},us=(e,t,s,r,n,o,i)=>ls(t&s|~t&r,e,t,n,o,i),hs=(e,t,s,r,n,o,i)=>ls(t&r|s&~r,e,t,n,o,i),ps=(e,t,s,r,n,o,i)=>ls(t^s^r,e,t,n,o,i),ms=(e,t,s,r,n,o,i)=>ls(s^(t|~r),e,t,n,o,i),gs=(e,t)=>{let[s,r,n,o]=e;s=us(s,r,n,o,t[0]??0,7,-680876936),o=us(o,s,r,n,t[1]??0,12,-389564586),n=us(n,o,s,r,t[2]??0,17,606105819),r=us(r,n,o,s,t[3]??0,22,-1044525330),s=us(s,r,n,o,t[4]??0,7,-176418897),o=us(o,s,r,n,t[5]??0,12,1200080426),n=us(n,o,s,r,t[6]??0,17,-1473231341),r=us(r,n,o,s,t[7]??0,22,-45705983),s=us(s,r,n,o,t[8]??0,7,1770035416),o=us(o,s,r,n,t[9]??0,12,-1958414417),n=us(n,o,s,r,t[10]??0,17,-42063),r=us(r,n,o,s,t[11]??0,22,-1990404162),s=us(s,r,n,o,t[12]??0,7,1804603682),o=us(o,s,r,n,t[13]??0,12,-40341101),n=us(n,o,s,r,t[14]??0,17,-1502002290),r=us(r,n,o,s,t[15]??0,22,1236535329),s=hs(s,r,n,o,t[1]??0,5,-165796510),o=hs(o,s,r,n,t[6]??0,9,-1069501632),n=hs(n,o,s,r,t[11]??0,14,643717713),r=hs(r,n,o,s,t[0]??0,20,-373897302),s=hs(s,r,n,o,t[5]??0,5,-701558691),o=hs(o,s,r,n,t[10]??0,9,38016083),n=hs(n,o,s,r,t[15]??0,14,-660478335),r=hs(r,n,o,s,t[4]??0,20,-405537848),s=hs(s,r,n,o,t[9]??0,5,568446438),o=hs(o,s,r,n,t[14]??0,9,-1019803690),n=hs(n,o,s,r,t[3]??0,14,-187363961),r=hs(r,n,o,s,t[8]??0,20,1163531501),s=hs(s,r,n,o,t[13]??0,5,-1444681467),o=hs(o,s,r,n,t[2]??0,9,-51403784),n=hs(n,o,s,r,t[7]??0,14,1735328473),r=hs(r,n,o,s,t[12]??0,20,-1926607734),s=ps(s,r,n,o,t[5]??0,4,-378558),o=ps(o,s,r,n,t[8]??0,11,-2022574463),n=ps(n,o,s,r,t[11]??0,16,1839030562),r=ps(r,n,o,s,t[14]??0,23,-35309556),s=ps(s,r,n,o,t[1]??0,4,-1530992060),o=ps(o,s,r,n,t[4]??0,11,1272893353),n=ps(n,o,s,r,t[7]??0,16,-155497632),r=ps(r,n,o,s,t[10]??0,23,-1094730640),s=ps(s,r,n,o,t[13]??0,4,681279174),o=ps(o,s,r,n,t[0]??0,11,-358537222),n=ps(n,o,s,r,t[3]??0,16,-722521979),r=ps(r,n,o,s,t[6]??0,23,76029189),s=ps(s,r,n,o,t[9]??0,4,-640364487),o=ps(o,s,r,n,t[12]??0,11,-421815835),n=ps(n,o,s,r,t[15]??0,16,530742520),r=ps(r,n,o,s,t[2]??0,23,-995338651),s=ms(s,r,n,o,t[0]??0,6,-198630844),o=ms(o,s,r,n,t[7]??0,10,1126891415),n=ms(n,o,s,r,t[14]??0,15,-1416354905),r=ms(r,n,o,s,t[5]??0,21,-57434055),s=ms(s,r,n,o,t[12]??0,6,1700485571),o=ms(o,s,r,n,t[3]??0,10,-1894986606),n=ms(n,o,s,r,t[10]??0,15,-1051523),r=ms(r,n,o,s,t[1]??0,21,-2054922799),s=ms(s,r,n,o,t[8]??0,6,1873313359),o=ms(o,s,r,n,t[15]??0,10,-30611744),n=ms(n,o,s,r,t[6]??0,15,-1560198380),r=ms(r,n,o,s,t[13]??0,21,1309151649),s=ms(s,r,n,o,t[4]??0,6,-145523070),o=ms(o,s,r,n,t[11]??0,10,-1120210379),n=ms(n,o,s,r,t[2]??0,15,718787259),r=ms(r,n,o,s,t[9]??0,21,-343485551),e[0]=ds(s,e[0]),e[1]=ds(r,e[1]),e[2]=ds(n,e[2]),e[3]=ds(o,e[3])},fs=(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},ys=e=>{let t="";for(let s=0;s<4;s+=1){t+=(e>>8*s&255).toString(16).padStart(2,"0")}return t},Es=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let s=0;for(;s+64<=e.length;s+=64)gs(t,fs(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&&(gs(t,r),r.fill(0));const i=8*e.length;return r[14]=4294967295&i,r[15]=Math.floor(i/4294967296),gs(t,r),t.map(ys).join("")},Rs=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})},Is=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},vs=()=>({async getImageInfo(e){const t=Is(e),s=await Rs(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=Is(e),n=await Rs(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=Is(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 Es(new Uint8Array(r))}}),Ss=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=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},Ts=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"}})},As=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},Os=async(e,t)=>new Promise((s,r)=>{e.getImageInfo({src:t,success:e=>{s(e)},fail:e=>{r(e instanceof Error?e:new Error(Ss(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:Ss(e)}})}),bs=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,_s=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const s=await Os(e,t);return bs(t,s)},Ms=e=>({async getImageInfo(t){const s=Cs(t),r=await Os(e,s),n=As(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=Cs(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 Os(e,n),i=bs(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(Ss(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:Ss(e)}})}),d=await _s(e,c),l=await Os(e,d),u=As(l.type)??t.mimeType,h=await(async(e,t,r)=>{const n=Ts(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(Ss(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:Ss(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=Cs(t),n=await _s(e,r),o=await(async(e,t)=>{const r=Ts(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(Ss(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:Ss(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 Es(o)}}),Ns=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),Ds=[/\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],ws=(e,t)=>{if("object"!=typeof e||null===e)return null;const s=e[t];return"string"==typeof s?s:null},Us=e=>{if(!e)return!1;const t=ws(e,"name");if(t&&Ns.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,ws(e,"message"),ws(e,"errMsg")].some(e=>null!==e&&Ds.some(t=>t.test(e)))},Ls=e=>{if(e instanceof Error)return e;const t=ws(e,"message")??ws(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Ps="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ks=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),xs=e=>e===s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||e===s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP,Fs=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=Ps.indexOf(t[i]??""),s=Ps.indexOf(t[i+1]??""),a=t[i+2]??"=",c=t[i+3]??"=",d="="===a?0:Ps.indexOf(a),l="="===c?0:Ps.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},Bs=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Gs=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},qs=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Bs(e)||ArrayBuffer.isView(e))return e;const s=e;return"data"in s&&s.data!==e?qs(s.data,t+1):e},Ks=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Gs(e);if(Bs(e))try{return Gs(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Gs(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=Ks(s.data,t+1);if(e)return e}if("buffer"in s&&s.buffer!==e){const e=Ks(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)}},Vs=(t,s)=>{if("string"==typeof t)return t;const r=t instanceof Uint8Array?t:new Uint8Array(t);if(xs(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+=Ps[i>>18&63],t+=Ps[i>>12&63],t+=void 0===n?"=":Ps[i>>6&63],t+=void 0===o?"=":Ps[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:ks(r.subarray(0,8))}),n}const n=new ArrayBuffer(r.byteLength);return new Uint8Array(n).set(r),n},zs=(e,t)=>"string"!=typeof e&&xs(t),Hs=(t,s)=>{const r=qs(t.data);if("string"==typeof r){if(!xs(s))return r;const n=Fs(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:ks(o.subarray(0,8)),decodedSuffixHex:ks(o.subarray(Math.max(0,o.length-8)))}),n}const n=Ks(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(!xs(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:ks(n.subarray(0,8))}),n.buffer;const i=Fs(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:ks(a.subarray(0,8)),decodedSuffixHex:ks(a.subarray(Math.max(0,a.length-8)))}),i},Ws=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),js=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],Qs=e=>e instanceof Error?e.message:Ws(e)&&"string"==typeof e.errMsg?e.errMsg:Ws(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),$s=e=>e?{...e}:{},Ys=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const s=()=>{t()};return e.addEventListener("abort",s,{once:!0}),()=>{e.removeEventListener("abort",s)}},Js=e=>{try{e.close()}catch{}},Xs=(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:Qs(t)}})))},d=t.downloadFile?.({url:r.url,header:$s(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=Ks(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=Ys(r.signal,()=>{d?.abort(),c("Mini program file download aborted.","abort",!1)})}),Zs=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:$s(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{o(),r({status:e.statusCode,headers:e.header??{},data:e.data})},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:Qs(e)}}))}});o=Ys(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"}}))})}):Xs(e,t)}),er=(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&&Js(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:Qs(e)}})))},u=e=>{if(!(js(r=e,"send")&&js(r,"close")&&js(r,"onOpen")&&js(r,"onMessage")&&js(r,"onError")&&js(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 Js(o);i=o;const a=()=>{o.offOpen?.(u),o.offError?.(h)},u=()=>{c?Js(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=Hs(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:Vs(r,t),...zs(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:Qs(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))})}),tr=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:$s(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i(),r({status:e.statusCode,body:e.data})},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:Qs(e)}}))}});a.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=Ys(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"}}))})})}),sr=(e,t)=>{const r=(e=>e===s.RUNTIME_PLATFORMS.ALIPAY_MINIAPP||e===s.RUNTIME_PLATFORMS.DINGTALK_MINIAPP)(t);return{async getItem(t){if(js(e,"getStorageSync"))try{const s=(e=>Ws(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 js(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(js(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(Us(n))throw Ls(n)}else if(js(e,"setStorage"))return new Promise((r,o)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{Us(e)?o(Ls(e)):r()}})}catch(n){if(Us(n))return void o(Ls(n));r()}})},async removeItem(t){if(js(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(js(e,"removeStorage"))return new Promise(s=>{try{e.removeStorage({key:t,success:s,fail:()=>{s()}})}catch{s()}})}}},rr=(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)}}}),nr=(e,t=s.RUNTIME_PLATFORMS.WECHAT_MINIAPP,r=t)=>{const n=(e=>{if(js(e,"request")&&js(e,"connectSocket")&&js(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?Ms(n):void 0;return{request:Zs(n),socket:er(n,r),upload:tr(n),runtime:rr(n,t),storage:sr(n,r),imageProcessor:o}},or=[s.RUNTIME_PLATFORMS.WEB,s.RUNTIME_PLATFORMS.ELECTRON_RENDERER,s.RUNTIME_PLATFORMS.REACT_NATIVE],ir=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},ar=e=>or.includes(e),cr=(e,t)=>e!==s.RUNTIME_PLATFORMS.UNIAPP?ar(e):!Tt(t)&&!lr(t)&&It(t),dr=e=>ir(e,"getImageInfo")&&ir(e,"getFileSystemManager"),lr=e=>!Tt(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),s=t?.uniPlatform;return"string"==typeof s?s:void 0}catch{return}})(e),ur=(e,t)=>{if(ar(e)&&e!==s.RUNTIME_PLATFORMS.REACT_NATIVE)return vs();if(_t(e)&&dr(t))return Ms(t);if(e===s.RUNTIME_PLATFORMS.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(It(e))return vs();if(dr(e.uni))return Ms(e.uni);if(dr(e.wx))return Ms(e.wx)}},hr=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())}},pr=(e,t,r,n)=>{if(e===s.RUNTIME_PLATFORMS.UNIAPP&&lr(r)&&void 0!==r.uni&>(r.uni))return{...nr(r.uni,e,t),proto:Wt()};if(((e,t)=>!cr(e,t)&&_t(e))(e,r)&>(n))return{...nr(n,e,t),proto:Wt()};const o=r.XMLHttpRequest,i=cr(e,r),a=i?Qt({fetchImpl:r.fetch}):void 0,c=i?ts({webSocketCtor:r.WebSocket}):void 0,d=e===s.RUNTIME_PLATFORMS.REACT_NATIVE?cs({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?is({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:Wt(),storage:hr(r),imageProcessor:i&&e!==s.RUNTIME_PLATFORMS.REACT_NATIVE?vs():ur(e,n)}},mr=(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}})},gr=t=>{const s=e.getRuntimeGlobal(t?.runtimeInput),r=bt(s,t?.prefer),n=r.platform,o=pr(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);Nt(c);return{platform:n,platformId:n,capability:c,request:mr(a.request,"request"),upload:mr(a.upload,"upload"),socket:mr(a.socket,"socket"),runtime:mr(a.runtime,"runtime"),proto:mr(a.proto,"proto"),storage:mr(a.storage,"storage"),imageProcessor:a.imageProcessor}},fr={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class yr{constructor(e={}){this.attemptCount=0,this.config={...fr,...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 Er={interval:3e4,timeout:6e4},Rr="function"==typeof TextDecoder?new TextDecoder:null;class Ir{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(!Ir.isRecord(r))return;"pong"===Ir.readString(r.type)&&(this.markAlive(),e.logger.debug("Pong received"))},this.config={...Er,...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)?Rr?.decode(t)??ut(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 vr=null;function Sr(){return vr||(vr=Ht()),vr}const Cr="websdk2:device-info",Tr="webim",Ar="web",Or=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(Cr);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(Cr,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===Tr){const e=`${Ar}_${s}`,t=d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return c(t),t}if(void 0!==n){const e=d({deviceId:`webim_${Ar}_${r}`,deviceName:r,deviceUuid:`${Ar}_${s}`});return c(e),e}const t={deviceId:`webim_${Ar}_${r}`,deviceName:`webim_${Ar}_${r}`,deviceUuid:`webim_${Ar}_${r}`};return c(t),t}if(r===Tr){const e=`random_${Ar}_${s}`;return d({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==n){return d({deviceId:`webim_${Ar}_${r}`,deviceName:r,deviceUuid:`random_${Ar}_${s}`})}return{deviceId:`webim_${Ar}_${r}`,deviceName:`webim_${Ar}_${r}`,deviceUuid:`webim_${Ar}_${r}`}},br=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),_r=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():""},Mr=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:Qe,stringValue:JSON.stringify(r)})}catch{t.push({key:s,type:je,stringValue:Object.prototype.toString.call(r)})}else t.push({key:s,type:je,stringValue:r});else Number.isInteger(r)?t.push({key:s,type:Ke,varintValue:r}):t.push({key:s,type:We,doubleValue:r});else t.push({key:s,type:qe,varintValue:r?1:0});return t},Nr=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:je;if(r!==qe)if(r!==Ke&&r!==Ve&&r!==ze)if(r!==He)if(r!==We){if(r!==Qe)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},Dr=new Set(["mute"]),wr={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},Ur=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Lr=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Pr=(e,t)=>{const s=e?.map(e=>Ur(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},kr=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=Lr(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=Lr(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=wr[r];if(!e)continue;let t=n;if(Dr.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},Fr=e=>{const t=Lr(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:Ur(t.operator)??Ur(t.username)}},Br=(e,t)=>({eventName:e,payload:t}),Gr=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},s=Ur(e.from?.name),r=(n=e.to,Ur(n?.[0]?.name));var n;switch(e.operation){case 1:return Br(y,t);case 10:return Br(I,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:r??s});case 17:return Br(E,{...t,memberIds:Pr(e.members,s),ext:e.ext??e.eventExt});case 18:return Br(R,{...t,memberIds:Pr(e.members,s)});case 20:return Br(_,{...t,oldOwnerId:s,newOwnerId:r});case 21:return Br(O,{...t,adminId:r??s});case 22:return Br(b,{...t,adminId:r??s});case 23:{const s=(e=>{const t=Lr(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):Pr(e.members,r),o=46388736e5;return Br(v,{...t,userIds:n,muteMembers:s??Object.fromEntries(n.map(e=>[e,o])),muteExpire:kr(e.reason,e.eventExt)??o})}case 24:return Br(S,{...t,userIds:Pr(e.members,r)});case 25:return Br(M,{...t,announcement:e.reason??""});case 26:return Br(M,{...t,announcement:""});case 29:return Br(C,{...t,userIds:Pr(e.members,r)});case 30:return Br(T,{...t,userIds:Pr(e.members,r)});case 31:return Br(A,{...t,isMuted:!0});case 32:return Br(A,{...t,isMuted:!1});case 14:return Br(N,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:xr(e.eventExt)});case 43:{const r=Fr(e.eventExt);return Br(D,{...t,attributes:r.attributes,from:r.from??s})}case 44:{const r=Fr(e.eventExt);return Br(w,{...t,keyList:r.keyList,from:r.from??s})}default:return null}},qr=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Kr={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Vr=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},zr=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Hr=(e,t)=>{const s=e?.map(e=>Vr(e)).filter(e=>"string"==typeof e)??[];return s.length>0?s:t?[t]:[]},Wr=(e,t)=>{const s=Number(e);if(!Number.isNaN(s)&&Number.isFinite(s)&&s>0)return s;const r=zr(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},jr=e=>{const t=zr(e);if(!t)return;const s={};for(const[r,n]of Object.entries(t)){const e=Kr[r];if(!e)continue;let t=n;if(qr.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},Qr=(e,t)=>{const s=zr(t)??zr(e);return o.normalizeGroupSharedFile(s??void 0)??void 0},$r=(e,t)=>{const s=zr(t)??zr(e);return Vr(s?.fileId)??Vr(s?.file_id)??Vr(e)??""},Yr=(e,t)=>({eventName:e,payload:t}),Jr=e=>{const t={groupId:e.groupId,groupName:e.groupName},s=Vr(e.from?.name),r=(o=e.to,Vr(o?.[0]?.name));var o;switch(e.operation){case 4:return Yr(n.GroupEventName.REQUEST_TO_JOIN_RECEIVED,{...t,applicantId:s,reason:e.reason});case 5:return Yr(n.GroupEventName.REQUEST_TO_JOIN_ACCEPTED,{...t,accepterId:s});case 6:return Yr(n.GroupEventName.REQUEST_TO_JOIN_DECLINED,{...t,declinerId:s,applicantId:r,reason:e.reason});case 7:return Yr(n.GroupEventName.INVITATION_RECEIVED,{...t,inviterId:s,reason:e.reason});case 8:return Yr(n.GroupEventName.INVITATION_ACCEPTED,{...t,inviteeId:s,reason:e.reason});case 9:return Yr(n.GroupEventName.INVITATION_DECLINED,{...t,inviteeId:s,reason:e.reason});case 10:return Yr(n.GroupEventName.USER_REMOVED,t);case 1:return Yr(n.GroupEventName.GROUP_DESTROYED,t);case 19:return Yr(n.GroupEventName.AUTO_ACCEPT_INVITATION,{...t,inviterId:s,reason:e.reason});case 23:{const s=(e=>{const t=zr(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=Vr(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):Hr(e.members,r);return Yr(n.GroupEventName.MUTE_LIST_ADDED,{...t,userIds:o,muteExpire:o.map(e=>s?.[e]).find(e=>void 0!==e)??Wr(e.reason,e.eventExt)})}case 24:return Yr(n.GroupEventName.MUTE_LIST_REMOVED,{...t,userIds:Hr(e.members,r)});case 29:return Yr(n.GroupEventName.ALLOW_LIST_ADDED,{...t,userIds:Hr(e.members,r)});case 30:return Yr(n.GroupEventName.ALLOW_LIST_REMOVED,{...t,userIds:Hr(e.members,r)});case 31:return Yr(n.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!0});case 32:return Yr(n.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED,{...t,isMuted:!1});case 21:return Yr(n.GroupEventName.ADMIN_ADDED,{...t,administratorId:r??s});case 22:return Yr(n.GroupEventName.ADMIN_REMOVED,{...t,administratorId:r??s});case 20:return Yr(n.GroupEventName.OWNER_CHANGED,{...t,oldOwnerId:s,newOwnerId:r});case 17:{const r=Hr(e.members,s);return Yr(n.GroupEventName.MEMBERS_JOINED,{...t,memberIds:r})}case 18:{const r=Hr(e.members,s);return Yr(n.GroupEventName.MEMBERS_EXITED,{...t,memberIds:r})}case 25:return Yr(n.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:e.reason??""});case 26:return Yr(n.GroupEventName.ANNOUNCEMENT_CHANGED,{...t,announcement:""});case 27:return Yr(n.GroupEventName.SHARED_FILE_ADDED,{...t,sharedFile:Qr(e.reason,e.eventExt)});case 28:return Yr(n.GroupEventName.SHARED_FILE_DELETED,{...t,fileId:$r(e.reason,e.eventExt)});case 14:return Yr(n.GroupEventName.GROUP_INFO_CHANGED,{...t,shouldFetchGroupDetail:!0,groupPatch:jr(e.eventExt)});case 41:return Yr(n.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Yr(n.GroupEventName.GROUP_DISABLED_CHANGED,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const r=(e=>{const t=zr(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:Vr(t.username),attribute:r}})(e.eventExt);return Yr(n.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED,{...t,userId:r.userId,attribute:r.attribute,from:s,source:e.source??"direct"})}default:return null}},Xr=new WeakMap,Zr=(e,t)=>{Xr.set(e,t)},en=e=>Xr.get(e)??null,tn=(e,t)=>{const s=en(e);s&&Zr(t,s)},sn=new WeakMap,rn=e=>sn.get(e),nn="singleChat",on="groupChat",an=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},cn=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}},dn=e=>{if(!Array.isArray(e))return;const t=e.map(e=>an(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},ln=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),un=(...e)=>{for(const t of e){const e=an(t);if(e)return e}},hn=(e,t)=>Boolean(e&&t&&e===t),pn=(e,t,s)=>Boolean(e&&e===s.userId&&t&&s.clientResource&&t!==s.clientResource),mn=(e,t,s)=>{const r=dn(e);if(r&&r.length>0)return r;const n=(t??[]).map(e=>an(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const o=an(s?.name);return o?[o]:[]},gn=e=>{const t=cn(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}}},fn=(t,s)=>{const r=un(t.to?.[0]?.clientResource);if(1!==t.to?.length||an(t.to[0]?.name)!==s.userId||!pn(s.userId,r,s))return null;const n=(o=t.from,an(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}},yn=(t,s)=>{if(!t.groupId)return e.logger.warn("Discarded MultiDevice group event without groupId",{operation:t.operation}),null;const r=un(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!pn(an(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=mn(t.members,t.to,t.from);return{category:"group",operation:n,groupId:t.groupId,userIds:o.length>0?o:void 0,operatorId:an(t.from?.name),groupName:t.groupName,deviceId:r,timestamp:t.timestamp,raw:t.raw}},En=(t,s)=>{if(!t.threadId)return e.logger.warn("Discarded MultiDevice thread event without threadId",{operation:t.operation}),null;const r=un(t.from?.clientResource,t.raw?.resource,t.raw?.clientResource);if(!pn(an(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=mn(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:an(t.from?.name),threadName:t.threadName,deviceId:r,timestamp:t.timestamp,raw:t.raw}},Rn=(t,s)=>{if("pin"===t.operation||"pin_delete"===t.operation)return null;const r=un(t.res,t.raw?.resource,t.raw?.clientResource);if(hn(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?nn:on;var o;const i=an(t.id)??(n===nn?an(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?gn(t.ext):void 0,operatorId:an(t.from),deviceId:r,timestamp:cn(t.ts),raw:t.raw}},In=(t,s)=>{const r=un(t.resource,t.raw?.resource,t.raw?.clientResource);if(hn(r,s.clientResource))return e.logger.debug("Discarded same-device MultiDevice roaming delete echo",{conversationId:t.to}),null;const n=an(t.to);if(!n)return e.logger.warn("Discarded MultiDevice roaming delete event without conversationId",{}),null;const o=an(t.lastMsgId),i=dn(t.msgIdList)??(o?[o]:void 0),a=cn(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?on:nn,messageIds:i,beforeTimestamp:a,deviceId:r,raw:t.raw}},vn=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}};var Sn=4096,Cn=65547,Tn=15,An=2113929216,On=65536,bn=65536,_n=10485760,Mn={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Nn={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Dn(e){if(!(e>0))return bn;if(e<=bn)return bn;if(e>1073741823)return e;for(var t=bn;t<e;)t*=2;return t}var wn={byU16:0,byU32:1},Un=0,Ln=1,Pn=2,kn=0,xn=1;function Fn(e,t){return e[t]|e[t+1]<<8}function Bn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Gn(e,t,s){e[t]=255&s,e[t+1]=s>>>8&255}var qn="fast";function Kn(e){return 2654435761*(e>>>0)>>>20&4095}function Vn(e){return 2654435761*(e>>>0)>>>19&8191}function zn(e,t,s){if("fast"===qn){var r=Bn(e,t);return s===wn.byU16?Vn(r):Kn(r)}throw new Error("Unsupported hash strategy: "+qn)}function Hn(e,t,s,r,n){s[t]=e-n}function Wn(e,t,s,r,n){Hn(t,zn(e,t,r),s,0,n)}function jn(e,t,s,r){return t[e]+r}function Qn(e,t,s,r,n){return jn(zn(e,t,r),s,0,n)}function $n(e,t,s,r){for(var n=t;t<r-3;){if(Bn(e,t)!==Bn(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 Yn(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>An)return 0;switch(c){case Un:default:l=r,u=r;break;case Ln:l=r-e.currentOffset,u=r-e.dictSize;break;case Pn:l=r-e.currentOffset,u=r}if(a===wn.byU16&&n>=Cn)return 0;if(n<13)return Zn(t,s,I,v,T,A,i);Wn(t,m,p,a,l),h=zn(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 Zn(t,s,I,v,T,A,i);b=jn(w,p,0,l),c===Pn&&(b<r?(O=R,u=y):(O=0,u=r)),h=zn(t,M,a),Hn(m,w,p,0,l)}while(d===xn&&b<g||a!==wn.byU16&&b+65535<m||!Jn(t,f,m,b,O,c,r));for(;m>I&&b+O>u;){var U=b+O-1;if(t[m-1]!==(c===Pn&&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>=Tn){var P=L-Tn;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(Gn(s,T,m-b),T+=2,c===Pn&&b<r){var F=m+(E-(b+O));if(F>C&&(F=C),(m+=4+(x=Xn(t,f,m+4,b+O+4-y+e.dictionaryStart,F,E-y)))===F&&F<C){var B=$n(t,m,r,C);x+=B,m+=B}}else m+=4+(x=$n(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(Wn(t,m-2,p,a,l),b=Qn(t,m,p,a,l),c===Pn&&(b<r?(O=R,u=y):(O=0,u=r)),Wn(t,m,p,a,l),!((d!==xn||b>=g)&&b+65535>=m&&Jn(t,f,m,b,O,c,r)))break t;s[_=T++]=0}h=zn(t,++m,a)}return Zn(t,s,I,v,T,A,i)}function Jn(e,t,s,r,n,o,i){var a,c=Bn(e,s);o===Pn&&r+n<i?a=Bn(t,r+n):a=Bn(e,r+n);return c===a}function Xn(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 Zn(e,t,s,r,n,o,i){var a=r-s;if(i&&n+a+1+Math.floor((a+255-Tn)/255)>o)return 0;if(a>=Tn){for(t[n++]=240,a-=Tn;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 eo(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 to(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)===Tn){var T=eo(e,b={ip:p},m-Tn,!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=Fn(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=eo(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===Pn&&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 so(){return{hashTable:new Uint32Array(Sn),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function ro(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function no(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?xn:kn;return e.dictionary&&c===r?(l=Yn(e,t,s,r,n,i||0,a||!1,wn.byU32,Ln,h),e.dictSize+=n,e.currentOffset+=n,l):(l=Yn(e,t,s,r,n,i||0,a||!1,wn.byU32,Pn,h),e.dictionary=t,e.dictionaryStart=r,e.dictSize=n,e.currentOffset+=n,l)}function oo(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 io(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function ao(e,t,s,r){return e.prefixSize=r,e.prefixEnd=s+r,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function co(e,t,s,r,n,o,i){var a;if(e.prefixEnd===o){if((a=to(t,s,r,n,o,i,!0,0,0,Pn,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=to(t,s,r,n,o,i,!0,0,0,Pn,o,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=o+a}return a}function lo(e){var t=(e=e||{}).minWorkArea||bn,s=e.maxWorkArea||_n,r=e.shrinkThreshold||t;t<bn&&(t=bn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=On+t,this.maxBufferSize=On+s,this.shrinkThreshold=On+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Mn.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=so()}function uo(e){var t=(e=e||{}).minWorkArea||bn,s=e.maxWorkArea||_n,r=e.shrinkThreshold||t;t<bn&&(t=bn),s<t&&(s=t),r<t&&(r=t),r>s&&(r=s),this.minBufferSize=On+t,this.maxBufferSize=On+s,this.shrinkThreshold=On+r,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Mn.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}lo.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<On?this.offset:On,n=this.offset>On?this.offset-On:0;t.set(this.ringBuffer.subarray(n,n+r),0),oo(this.stream,t,0,r),s=r}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},lo.prototype.compress=function(e,t){var s=e.length;if(s<=0)return Nn.PARAM_ERROR;if(s>this.maxBufferSize-On)return Nn.PARAM_ERROR;if(s>this.ringBufferSize-On){var r=Dn(s),n=On+r;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Nn.BUFFER_RESIZE_FAILED}this.offset+s>this.ringBufferSize&&(oo(this.stream,this.ringBuffer,0,On),this.offset=On);var o=this.offset;this.ringBuffer.set(e,o);var i=no(this.stream,this.ringBuffer,t,o,s,0,t.length,!0);return i<=0?Nn.COMPRESS_FAILED:(this.offset+=s,this._tryAutoShrink(),i)},lo.prototype.reset=function(){this.offset=0,ro(this.stream)},lo.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},lo.prototype._tryAutoShrink=function(){this.shrinkMode!==Mn.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Mn.AUTO_IMMEDIATE||this.shrinkMode===Mn.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},lo.prototype.getWorkArea=function(){return this.ringBufferSize-On},lo.prototype.getRingBufferSize=function(){return this.ringBufferSize},lo.prototype.getBaseBufferSize=function(){return this.minBufferSize},lo.prototype.getMaxBufferSize=function(){return this.maxBufferSize},lo.prototype.getCurrentOffset=function(){return this.offset},lo.prototype.getShrinkMode=function(){return this.shrinkMode},lo.prototype.setShrinkMode=function(e){this.shrinkMode=e},lo.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},lo.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-On,s=this.maxBufferSize-On;if(e<t||e>s)return Nn.PARAM_ERROR;this.shrinkThreshold=On+e},uo.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),s=0;if(this.offset>0){var r=this.offset<On?this.offset:On,n=this.offset>On?this.offset-On:0;t.set(this.ringBuffer.subarray(n,n+r),0),s=r,ao(this.streamDecode,0,0,r)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=s,!0},uo.prototype.decompress=function(e,t,s){var r=e.length;if(r<=0||s<=0)return Nn.PARAM_ERROR;if(s>this.maxBufferSize-On)return Nn.PARAM_ERROR;if(s>this.ringBufferSize-On){var n=Dn(s),o=On+n;if(o>this.maxBufferSize&&(o=this.maxBufferSize),!this._resizeBuffer(o))return Nn.BUFFER_RESIZE_FAILED}if(this.offset+s>this.ringBufferSize){var i=this.offset-On;i>0&&this.ringBuffer.set(this.ringBuffer.subarray(i,i+On),0),ao(this.streamDecode,this.ringBuffer,0,On),this.offset=On}var a=co(this.streamDecode,e,this.ringBuffer,0,r,this.offset,s);return a<=0?Nn.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},uo.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},uo.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},uo.prototype._tryAutoShrink=function(){this.shrinkMode!==Mn.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Mn.AUTO_IMMEDIATE||this.shrinkMode===Mn.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},uo.prototype.getWorkArea=function(){return this.ringBufferSize-On},uo.prototype.getRingBufferSize=function(){return this.ringBufferSize},uo.prototype.getBaseBufferSize=function(){return this.minBufferSize},uo.prototype.getMaxBufferSize=function(){return this.maxBufferSize},uo.prototype.getCurrentOffset=function(){return this.offset},uo.prototype.getShrinkMode=function(){return this.shrinkMode},uo.prototype.setShrinkMode=function(e){this.shrinkMode=e},uo.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},uo.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-On,s=this.maxBufferSize-On;if(e<t||e>s)return Nn.PARAM_ERROR;this.shrinkThreshold=On+e};const ho={LZ4_MAX_INPUT_SIZE:An,BLOCK_MAX_SIZE:65536,DICT_SIZE:On,DEFAULT_WORK_AREA:bn,DEFAULT_MAX_WORK:_n,SHRINK_MODE:Mn,LZ4_ERROR:Nn,alignToPowerOf2:Dn,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".');qn=e},getHashStrategy:function(){return qn},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>An)return 0;if(0===r)return t.length>n?(t[n]=0,1):0;var o=r<Cn?wn.byU16:wn.byU32;return Yn({hashTable:new Uint32Array(o===wn.byU16?8192:Sn),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,0,!1,o,Un,kn)},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>An)return 0;if(o<1)return 0;if(0===r)return t[n]=0,1;var i=r<Cn?wn.byU16:wn.byU32;return Yn({hashTable:new Uint32Array(i===wn.byU16?8192:Sn),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,s,r,o,!0,i,Un,kn)},compressBound:function(e){return e<0||e>An?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:to(e,t,s,r,n,o,!0,0,0,Un,n,null,0))},decompressFast:function(e,t,s,r,n){return to(e,t,s=s||0,0,r=r||0,n,!1,0,0,Ln,r-65536,0,65536)},createStream:so,resetStream:ro,loadDict:function(e,t,s,r){if(e.initCheck&&ro(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;)Wn(t,o,e.hashTable,wn.byU32,n),o+=3;return r},compressContinue:no,saveDict:oo,createStreamDecode:io,setStreamDecode:ao,decompressSafeContinue:co,RingBufferEncoder:lo,RingBufferDecoder:uo,_hashU16:Vn,_hashU32:Kn,_TABLE_TYPE:wn},po=268435455,mo=new Uint32Array(256);let go=!1;function fo(e){!function(){if(!go){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;mo[e]=t>>>0}go=!0}}();let t=4294967295;for(let s=0;s<e.length;s+=1){const r=e[s]??0;t=t>>>8^(mo[255&(t^255&r)]??0)}return(4294967295^t)>>>0}var yo=(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))(yo||{});const Eo=268435455;class Ro{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:ho.DEFAULT_WORK_AREA,maxWorkArea:ho.DEFAULT_MAX_WORK,shrinkMode:ho.SHRINK_MODE.MANUAL};this.encoder=new ho.RingBufferEncoder(e),this.decoder=new ho.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>Eo)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const s=ho.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>po)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=fo(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>Eo)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=fo(i);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return i}reset(){this.encoder.reset(),this.decoder.reset()}}const Io=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),vo=(e,t)=>r.encodeWithReflection(e,t).finish();class So{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Or({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:[ye],compressType:[Ee],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=Sr(),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:[Ee],encryptType:[ye],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,auth:`$t$${this.context.token}`,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},o=vo(s,n),i={version:0,guid:br({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),auth:`$t$${this.context.token}`,command:F,deviceId:0,encryptType:[ye],payload:o,traceId:e.createTraceId()};return vo(r,i)}encodeHeartbeat(){const t=Sr(),s=t.lookupType("easemob.pb.CommUnreadUL"),r=t.lookupType("easemob.pb.MSync"),n=vo(s,{}),o={version:0,encryptType:[ye],command:k,payload:n,traceId:e.createTraceId()};return vo(r,o)}encodeStatisticRebuild(){const t=Sr(),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=vo(s,{operation:0}),a=r.decode(new Uint8Array);a.id=Date.now(),a.ns=de,a.payload=i;const c=n.decode(new Uint8Array);c.meta=a;const d=vo(n,c);return vo(o,{version:0,encryptType:[ye],command:P,payload:d,traceId:e.createTraceId()})}decodeProvision(e){const t=Sr().lookupType("easemob.pb.Provision").decode(e),s=t.status??{},r="number"==typeof s.errorCode?s.errorCode:ve,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===Ie,statusCode:r,reason:n,resource:o,authToken:i,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Sr().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=Sr().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=Sr().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=Sr(),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=_r(o.metaId),d=_r(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)!==le)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)!==le)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:G;if(i!==z&&i!==W&&i!==j&&i!==Q&&i!==H)return null;const a=this.readJid(r.to),c=Number(_r(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===j)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===z){e.logger.debug("Received READ_ACK MessageBody",n);const t=(Array.isArray(n.ackMessageIds)?n.ackMessageIds:[]).map(e=>_r(e)).filter(e=>Boolean(e)),s=_r(n.ackMessageId);if(0===t.length&&s&&t.push(s),0===t.length||!h)return null;const r=Nr(Array.isArray(n.ext)?n.ext.filter(Io):void 0),o=Io(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===H){const e=_r(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=_r(n.ackMessageId);return e&&h?{type:"message_recalled",data:{messageId:e,conversationId:h,conversationType:d,timestamp:c}}:null}const p=_r(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:Nr(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!==pe&&s!==he&&s!==ue&&s!==de)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===he?this.decodeRosterMeta(t,n):s===ue?this.decodeMucMeta(t,n):s===de?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(t,s){try{const r=Sr(),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(!Io(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(!Io(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!==de)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=Sr(),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=Sr(),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=fn({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=Sr(),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=En({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=yn({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?Gr({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}):Jr({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&&sn.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:Io(n.data)?n.data:n}}]}if("conv"===o){const e=Io(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=Rn({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=Io(n.data)?n.data:n,t=In({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(!ln(r))continue;const e=un(r.operator_resource,r.resource,r.clientResource);if(hn(e,t.clientResource))continue;const n=an(r.group)??an(r.user);if(!n||!ln(r.data))continue;const o=an(r.group)?on:nn,i=r.data;s.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:o,remindType:an(i.type),silentMode:i,deviceId:e,raw:r})}return s})(Io(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(_r(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:vn(e.category),data:e}}decodeNotice(e){const t=Sr().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Sr().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=Sr(),r=s.lookupType("easemob.pb.CommSyncUL"),n=s.lookupType("easemob.pb.MSync"),o=vo(r,{queue:t}),i={version:0,encryptType:[ye],command:P,payload:o,traceId:e.createTraceId()};return vo(n,i)}encodeLastSession(t,s){const r=Sr(),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i=vo(n,{queue:t,key:s}),a={version:0,encryptType:[ye],command:P,payload:i,traceId:e.createTraceId()};return vo(o,a)}encodeChatMessage(t,s){const r=Sr(),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:Mr(t.ext??{}),...d?{meta:d}:{},...c,...t.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},h=vo(n,u),p="singleChat"===t.conversationType?this.context.domain:"conference.easemob.com",m=this.resolveDirectedUsers(t),g=this.resolveMetaExt(t),f={id:s,to:br({appKey:this.context.appKey,name:l.name,domain:p,clientResource:l.clientResource}),ns:le,payload:h,routetype:this.resolveRouteType(t),directedUsers:m,ext:g,...void 0!==t.webhookEnv?{env:t.webhookEnv}:{}},y=vo(o,{meta:f}),E={version:0,encryptType:[ye],command:P,payload:y,traceId:e.createTraceId()};return vo(i,E)}encodeActionMessage(t,s){const r=Sr(),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:Mr(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=vo(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:br({appKey:this.context.appKey,name:c.name,domain:"singleChat"===t.conversationType?this.context.domain:"conference.easemob.com",clientResource:c.clientResource}),ns:le,payload:u,routetype:me,directedUsers:[],ext:[]},p=vo(o,{meta:h}),m={version:0,encryptType:[ye],command:P,payload:p,traceId:e.createTraceId()};return vo(i,m)}encodeChatRoomOperation(t,s){const r=Sr(),n=r.lookupType("easemob.pb.MUCBody"),o=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),a={mucId:br({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=vo(n,a),d={id:s,from:br({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:ue,payload:c},l=vo(o,{meta:d}),u={version:0,encryptType:[ye],command:P,payload:l,traceId:e.createTraceId()};return vo(i,u)}decodeServerMessageMeta(e){const t=Sr(),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?lt(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=Sr().lookupType("easemob.pb.MUCBody");for(const n of t){if(!Io(n)||n.ns!==ue)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(!Io(e)||!Io(e.status))continue;const t=e.status.chatroomInfo;if("string"!=typeof t||""===t)continue;const r=JSON.parse(t);if(!Io(r))continue;const n=r[this.context.userId];if(!Io(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=_r(e.metaId);if(!t||"0"===t)return;const s=e.status??{},r="number"==typeof s.errorCode?s.errorCode:ve,n="string"==typeof s.reason?s.reason:void 0;return{protocolId:t,serverId:_r(e.serverId),ok:r===Ie,statusCode:r,reason:n}}decodeMessage(e,t){const s="number"==typeof t.type?t.type:q;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=Nr(t.ext),h=Nr(e.ext),p=Number(_r(e.timestamp))||Date.now(),m=_r(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)};Zr(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=en(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(_r(e))}isPublicMessageType(e){return e===q||e===K||e===V}resolveMessageIsOnline(e,t){if(e===V)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(_r(s.streamSeq));if(!Number.isFinite(r))return;const n="number"==typeof s.streamStatus?s.streamStatus:ie,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===ne?U.START:e===oe?U.START_COMPLETED:e===ae?U.COMPLETED:e===ce?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:$,text:e.content}}if("cmd"===s.type){const e=s.body;return{type:te,action:e.action}}if("custom"===s.type){const e=s.body;return{type:se,customEvent:e.event,customExts:Mr(e.params??{})}}if("location"===s.type){const e=s.body;return{type:X,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:Y,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:J,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:Z,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:$,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:ee,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:$,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===re||s===$&&(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===$)return{type:"text",body:{content:"string"==typeof t.text?t.text:""}};if(s===te)return{type:"cmd",body:{action:"string"==typeof t.action?t.action:""}};if(s===se){const e=Nr(t.customExts);return{type:"custom",body:{event:"string"==typeof t.customEvent?t.customEvent:"",params:e}}}if(s===X)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===Y){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===J){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===Z){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===ee){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 K;case"chatRoom":return V;default:return q}}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 j;case"sendMessageReadReceipts":return z;case"deliveryAck":return H;case"recall":return W;case"update":return Q;default:return q}}resolveConversationType(e){return e===K?"groupChat":e===V?"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?Mr({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?fe:this.resolveDeliverOnlineOnly(e)?ge:me}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(!Io(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(!Io(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(!Io(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(!Io(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=Io(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:Io(n?.ext)?n.ext:{},timestamp:r,body:u,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(Io(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:Io(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(ut(t));return Io(e)?e:null}catch{return null}}if(Io(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return Io(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(Io).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?[]:[Re]}configureCompression(e,t){if(!e||!e.includes(Re))return void this.disableCompression();this.compressor||(this.compressor=new Ro);const s=this.resolveCompressionMode(t);this.compressor.mode=s,this.compressor.enableUplinkCompression=s===yo.UPLINK_ONLY||s===yo.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=s===yo.DOWNLINK_ONLY||s===yo.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?yo.UPLINK_ONLY:1===e?yo.DOWNLINK_ONLY:2===e?yo.BIDIRECTIONAL:yo.NONE}disableCompression(){this.compressor&&(this.compressor.mode=yo.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}class Co{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 So({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 yr({maxAttempts:this.config.autoReconnectNumMax,initialDelay:e.RECONNECT_INITIAL_DELAY,maxDelay:e.RECONNECT_MAX_DELAY,backoffMultiplier:e.RECONNECT_BACKOFF_MULTIPLIER}),this.heartbeatManager=new Ir({interval:this.config.heartBeatWait,timeout:e.HEARTBEAT_TIMEOUT}),this.connectionEventNormalizer=new ht,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(ut(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 F:this.handleProvisionMessage(a.payload);break;case B:this.handleLogoutMessage(a.payload);break;case x:this.handleNoticeMessage(a.payload);break;case k:this.handleUnreadMessage(a.payload);break;case P: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=ct(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=ts({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 To=new Uint8Array([99,109]),Ao=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Oo=e=>Array.isArray(e)&&e.every(Ao),bo=e=>"string"==typeof e?e:void 0,_o=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Mo=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},No=(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},Do=e=>{let t=0;for(let s=2;s<e.length;s+=1)s%2==1&&(t^=e[s]??0);return t},wo=(e,t)=>{const s=Sr().lookupType(e).decode(t);if(!Ao(s))throw new Error(`${e} decoded result is invalid`);return s},Uo=e=>Ao(e)&&"string"==typeof e.name?e.name:"",Lo=(t,s,r)=>{const n=(Oo(t.contents)?t.contents:[])[0];if(!n)throw new Error("MessageBody contents is empty");const o=(t=>{const s=_o(t.type)??$,r=Boolean(bo(t.remotePath))||Boolean(bo(t.title))||Boolean(bo(t.summary))||(_o(t.combineLevel)??0)>0,n=s===$&&0===t.subType&&r;if(s===re||n){const e=_o(t.combineLevel)??0;return{type:"combine",body:{title:bo(t.title)??"",summary:bo(t.summary)??"",filename:bo(t.displayName)??"combine",filetype:"application/octet-stream",url:bo(t.remotePath),secret:bo(t.secretKey),fileLength:_o(t.fileLength),combineLevel:e},combineLevel:e}}if(s===$)return{type:"text",body:{content:bo(t.text)??""}};if(s===te)return{type:"cmd",body:{action:bo(t.action)??""}};if(s===se){const e=Nr(Oo(t.customExts)?t.customExts:void 0);return{type:"custom",body:{event:bo(t.customEvent)??"",params:e}}}if(s===X)return{type:"location",body:{latitude:_o(t.latitude)??0,longitude:_o(t.longitude)??0,address:bo(t.address),buildingName:bo(t.buildingName)}};if(s===Y){const s=Ao(t.size)?t.size:{},r=bo(t.remotePath)??"",n=e.deriveImageUrls(r),o=bo(t.thumbnailRemotePath),i=e.fromProtocolImageType(t.imageType)===e.IMAGE_TYPE_ORIGINAL;return{type:"image",body:{localUrl:"",filename:bo(t.displayName)??"image",filetype:"application/octet-stream",width:_o(s.width)??0,height:_o(s.height)??0,isGif:1===t.subType,isOriginalImage:i,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:bo(t.secretKey),fileLength:_o(t.fileLength),thumbnailUrl:o??n.thumbnailUrl}}}if(s===J){const e=Ao(t.size)?t.size:{};return{type:"video",body:{url:bo(t.remotePath)??"",filename:bo(t.displayName)??"video",filetype:"application/octet-stream",duration:_o(t.duration)??0,width:_o(e.width),height:_o(e.height),secret:bo(t.secretKey),fileLength:_o(t.fileLength),thumbnailUrl:bo(t.thumbnailRemotePath)}}}if(s===Z)return{type:"voice",body:{url:bo(t.remotePath)??"",filename:bo(t.displayName)??"voice",filetype:"application/octet-stream",duration:_o(t.duration)??0,secret:bo(t.secretKey),fileLength:_o(t.fileLength)}};if(s===ee)return{type:"file",body:{url:bo(t.remotePath)??"",filename:bo(t.displayName)??"file",filetype:"application/octet-stream",secret:bo(t.secretKey),fileLength:_o(t.fileLength)}};return null})(n);if(!o)throw new Error("MessageBody content type is unsupported");const i=Uo(t.from)||Uo(r?.from)||`unknown-${s}`,a=Uo(t.to)||Uo(r?.to)||`unknown-${s}`,c=(d=t.type)===K?"groupChat":d===V?"chatRoom":"singleChat";var d;const l=a||i,u=Number(_r(r?.timestamp))||Date.now(),h=Nr(Oo(t.ext)?t.ext:void 0),p={msgServerId:_r(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},Po=(e,t)=>{const s=[];try{const n=wo("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=wo("easemob.pb.MessageBody",o);return Lo(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=wo("easemob.pb.MessageBody",e);return Lo(s,t)}catch(n){s.push(n instanceof Error?n.message:String(n))}try{const s=wo("easemob.pb.MessageBody.Content",e);return Lo({type:q,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("; "))},ko=(t,s)=>{const r=ut(t);try{const t=JSON.parse(r);if(!Ao(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 Po(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)}})}}},xo=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Fo{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(L(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"};tn(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"};tn(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 tn(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:xo(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:xo(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 lt(r)}),r=To.length+s.reduce((e,t)=>e+4+t.length,0)+1,n=new Uint8Array(r);let o=0;n.set(To,o),o+=To.length;for(const e of s){const t=Mo(e.length);n.set(t,o),o+=t.length,n.set(e,o),o+=e.length}const i=Do(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 tn(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};tn(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"};tn(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 Bo{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 Go{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new Bo}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 qo{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 Ko=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Vo{constructor(e,t,s){this.eventHub=s,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new Go(s),this.messageContexts=new Map,this.recentMessageIds=new qo(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=ct(t,s),n=r.code===e.ERROR_CODES.UNKNOWN?e.ERROR_CODES.MESSAGE_SEND_FAILED:r.code;return{code:n,message:dt[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(L(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(!Ko(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(!Ko(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(!Ko(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(!Ko(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(!Ko(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(!Ko(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(!Ko(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(!Ko(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Ko(t.message)||"string"!=typeof t.message.type||!Ko(t.message.body)||!Ko(t.message.ext))return;const s={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Ko(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)Ko(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)!Ko(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 zo=e=>e instanceof Error?e.message:String(e);class Ho{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Qt({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<To.length+1)throw new e.MessageReceiveError("Combine payload is too short",{code:e.ERROR_CODES.COMBINE_PARSE_FAILED});const s=t.subarray(0,To.length);if(s[0]!==To[0]||s[1]!==To[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=Do(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=To.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=No(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=ko(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 lt(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:zo(a),url:i}})}}}const Wo=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"}},jo=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 Qo{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Qt({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:Wo(t),mimeType:jo(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 $o=(t,s,r)=>({Authorization:`Bearer ${t}`,Accept:s,[e.REQUEST_ID_HEADER]:e.createTraceId(),...r??{}}),Yo=async t=>{const s=$o(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)}},Jo=(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($o(s,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{d.setRequestHeader(e,t)}),d.send(h)}),Xo=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 Yo({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=Jo(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 Yo({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?.(_),_},Zo=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)}),ei=vs(),ti=e=>Object.prototype.toString.call(e),si=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:ti(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}},ri=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}),ni=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,oi=e=>"object"==typeof e&&null!==e,ii=(e,t)=>{const r=oi(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(!oi(e))return!1;const t=oi(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 ai{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(!ni(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:si(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:ri(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:ri(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:ri(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:ri(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:ri(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(!ni(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(ii(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:ri(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:ri(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"}),ei;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(!ni(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(!ni(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:ri(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:ri(s.fileInfo),multipartEnabled:c,uploadMode:d?"multipart":"simple"}),d)try{return await Xo(a)}catch(l){const t=l instanceof e.UploadError?l.details:void 0;if(t&&"object"==typeof t&&"init"===t.stage)return Zo(a);throw l}return Zo(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(!ni(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:ri(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 tn(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 tn(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 tn(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 tn(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 tn(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(!ii(s.md5FileInfo.source.sourceType,o))throw o;e.logger.warn("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:t,source:ri(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 ci{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 di="__internal:core";class li{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 Co({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const s=this.connectionManager.getMsyncCodec(),r=e.restBaseUrl?new ai({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 Fo(s,null,this.eventHub,r),this.messageReceiver=new Vo(s,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Ho(e.platformAdapter?.request),this.attachmentDownloader=new Qo(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(di,{[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 ci(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(di),t.attachmentFileStore.clear()}}const ui=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)},hi=e=>{const t=atob(e),s=new Uint8Array(new ArrayBuffer(t.length));for(let r=0;r<t.length;r+=1)s[r]=t.charCodeAt(r);return s};class pi{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=bt(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:ui(r),ct:ui(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=hi(t.iv),r=hi(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 mi="conversationMap",gi="userInfoMap",fi="groupNamecardMap",yi="contactRelationMap",Ei="contactVersion",Ri="contactMeta",Ii="sessionListMap",vi="sessionListCheckpoint",Si="joinedGroupPreview",Ci="metadata",Ti=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Ai{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 Oi=()=>{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 bi{constructor(e,t){this.storage=t??bi.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!bi.checkAvailable())return null;const e=Oi();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=Oi();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 c.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=c.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(Us(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 _i={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Mi={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Ni{constructor(){this.items=new Map,this.versionState=_i,this.meta=Mi}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(!c.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 c.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"}:_i}normalizeMeta(e){return c.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"}:Mi}}const Di=(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}},wi=(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}},Ui=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 Li{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=Di(this.items,e,t);return this.items=[...s.kept],s.removed.length>0}evictByLru(e){const t=wi(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:Ui(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(!c.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=c.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 Pi=(e,t)=>`${e}:${t}`;class ki{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(Pi(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,s,r){const n=Pi(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(Pi(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=Pi(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(Pi(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=Di(n,e,t),i=new Set(o.removed.map(e=>Pi(e.groupId,e.userId)));this.items.clear();for(const a of r)i.has(Pi(a.groupId,a.userId))||this.items.set(Pi(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=wi(r,Math.min(e,r.length)),o=new Set(n.removed.map(e=>Pi(e.groupId,e.userId)));this.items.clear();for(const i of s)o.has(Pi(i.groupId,i.userId))||this.items.set(Pi(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||!c.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 xi=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Fi=e=>{const t={...e};return delete t.type,t},Bi=e=>{if(!c.isRecord(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!c.isRecord(e.body))return null;const s=((e,t)=>{if(c.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=xi(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(c.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,d="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return{msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:s,body:Fi(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!==d?{namecardUpdateTime:d}:{}}},Gi=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},qi=(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 Ki{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(qi)}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(qi)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!c.isRecord(e))return null;const s=e,r="string"==typeof s.conversationId?s.conversationId:"";if(!r)return null;const n=xi(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:Bi(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:Gi(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 Vi{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=Di(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=wi(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(!c.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 zi=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Hi=e=>e.lastMessageAt??e.updatedAt,Wi=e=>[...e].sort((e,t)=>{const s=zi(t)-zi(e);if(0!==s)return s;const r=Hi(t)-Hi(e);return 0!==r?r:e.conversationId.localeCompare(t.conversationId)}),ji=e=>`${e.conversationType}:${e.conversationId}`,Qi=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,$i=(e,t)=>((e,t)=>Hi(t)>Hi(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Qi(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,Yi=e=>{const t=new Map,s=new Set;for(const o of e.snapshot)s.add(ji(o));for(const o of e.existing)t.set(ji(o),o);const r=e.snapshot.map(e=>{const s=t.get(ji(e));return s?$i(e,s):e}),n=e.existing.filter(t=>!s.has(ji(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Wi([...r,...n])},Ji=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Xi=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Zi=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 ea{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,Ji.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 ta=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class sa{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 pi(e.appKey,e.userId);this.store=new bi(t??void 0,e.storageAdapter);const s={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Ti(s,mi),this.userInfoKey=Ti(s,gi),this.groupNamecardKey=Ti(s,fi),this.sessionListKey=Ti(s,Ii),this.sessionListCheckpointKey=Ti(s,vi),this.joinedGroupPreviewKey=Ti(s,Si),this.contactRelationKey=Ti(s,yi),this.contactVersionKey=Ti(s,Ei),this.contactMetaKey=Ti(s,Ri),this.metadataKey=Ti(s,Ci),this.metadataStore=new Ai(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Li,this.userInfoCache=new Vi,this.groupNamecardCache=new ki,this.sessionListCache=new Ki,this.joinedGroupPreviewCache=new o.JoinedGroupPreviewCache,this.contactCache=new Ni,this.userInfoRuntimeStore=new ea,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=Yi({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?Xi(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,s)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Zi(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=ji(e.nextRecord),s=e.existing.filter(e=>ji(e)!==t);return Wi([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&&c.isRecord(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(o,e);const i=(n&&c.isRecord(n)&&c.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 d=await this.readDump(this.contactRelationKey),l=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(d,l,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&c.isRecord(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&c.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(!Us(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(!Us(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 ta)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=>zi(e)>0),s=new Map;for(const n of e.incoming)s.set(ji(n),n);const r=t.length>0?e.existing.filter(e=>!s.has(ji(e))&&0===zi(e)):e.existing.filter(e=>!s.has(ji(e)));return Wi([...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(Yi({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=en(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?Xi(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 ra{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 na={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function oa(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 ia(e){return new Promise(t=>setTimeout(t,e))}const aa=e=>{const t={...e};return delete t.type,t},ca=(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:aa(s.body),modifiedInfo:s.modifiedInfo,userInfoUpdateTime:s.userInfoUpdateTime,namecardUpdateTime:s.namecardUpdateTime}},da=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},la=async(e,t)=>{const s=await da(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:ca(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 ua{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 ha=0,pa=5,ma=10,ga=11,fa=1,ya=2,Ea=1,Ra=2,Ia=3,va=e=>e===fa?"groupChat":e===ya?"chatRoom":"singleChat",Sa=()=>Sr().lookupType("easemob.pb.MessageBody"),Ca=e=>{const t=Sa().toObject(Sa().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:0;return 0===o?{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:""}:8===o?{type:"combine",title:"string"==typeof r.title?r.title:"",summary:"string"==typeof r.summary?r.summary:""}:{}},Ta=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}},Aa=e=>{const t={...e};return delete t.type,t},Oa=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,ba=(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:Oa({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:Aa(t)};var o},_a=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},Ma=(e,t)=>e.sessions.map(e=>{const s=(e=>{if(!e||0===e.byteLength)return{};try{return Ca(e)}catch{return{}}})(e.last_message?.payload),r=e.session_id??"",n=va(e.session_type),o=(e=>{const t=e.session_id??"",s=va(e.session_type);return"groupChat"===s||"chatRoom"===s?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Ta(e)})(e);return{conversationId:r,conversationType:n,unreadCount:e.unread_count??0,lastMessage:ba(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:_a(e.marks),readAt:e.read_receipt,remindType:(i=e.remind_type,i===Ea?"ALL":i===Ra?"AT":i===Ia?"NONE":"DEFAULT"),conversationName:o.conversationName,conversationAvatar:o.conversationAvatar};var i}),Na={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 Da=null,wa=!1;const Ua=()=>Da||(wa||(r.lightExports.util.Long=r.Long,r.lightExports.configure(),wa=!0),r.installReflectionRuntime(),Da=r.lightExports.Root.fromJSON(Na),r.installReflectionCodecInNamespace(Da),Da),La=e=>Ua().lookupType(e),Pa=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}},ka=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Pa(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Pa(t.protocol_version)??Pa(t.protocolVersion)??0}},xa=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}},Fa=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Pa(t.id)?String(Pa(t.id)):void 0,from:xa(t.from),timestamp:Pa(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 Ba{constructor(){this.requestType=La("easemob.sessionlist.GetSessionListRequest"),this.responseType=La("easemob.sessionlist.GetSessionListResponse"),this.errorType=La("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:ha}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),s=Pa(t.type);return s!==ma?null:{type:s,header:ka(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Pa(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=Pa(t.type);return s!==ga?null:{type:s,header:ka(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:Pa(t.session_type),last_message:Fa(t.last_message),updated_at:Pa(t.updated_at),pinned_time:Pa(t.pinned_time),unread_count:Pa(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Pa(t.read_receipt),remind_type:Pa(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:Pa(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=Pa(t.type);return s!==pa?null:{type:s,header:ka(t.header),code:Pa(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Ga=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 Ba;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=Ma(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}}}})},qa=()=>Date.now(),Ka={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Va=(e,t)=>({status:e,determinedAt:qa(),reason:t}),za=t=>t instanceof e.SDKError&&(t.code===e.ERROR_CODES.SERVER_BUSY||1103===t.code),Ha=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:za(e)});class Wa{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 ua,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 c=await async function(e,t,s={}){const r={...na,...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=oa(i,r);await ia(e)}throw n}(async()=>{i+=1;const e=1===i?t:this.createRetrySession();e.start();try{return await Ga({client:this.client,session:e,params:s})}catch(r){throw e.fail(),r}},za,Ka),d={result:c,syncStartedAt:t.getStartedAt()},l=d.result.items;this.capabilityState={status:"available",determinedAt:qa()};const u={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:qa()};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:Ha(s)}),r.loadSessionList()}const h=r.loadSessionList();return r.updateConversationsFromServer(h.map(a.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:Va("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:Ha(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=Va("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new ua}async buildFallbackSessionList(e){return await(async(e,t)=>await la(e,t))(e.loadConversationSummaries(),this.client)}}const ja=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Qa=async t=>{if("string"==typeof t||ja(t)||ArrayBuffer.isView(t))return(e=>"string"==typeof e?(new TextEncoder).encode(e):ja(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}})},$a=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)},Ya=async e=>{await new Promise(t=>{setTimeout(t,e)})},Ja=e=>e instanceof Error?e:new Error(String(e));class Xa{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,Ja(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=Ja(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=$a(this.attempt);e.logger.warn("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:t.message})),await Ya(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??ts({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 Qa(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Ja(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(Ja(n)),this.closeIfComplete()}return!0}s.requestId||1!==s.type||r||(r={pending:e,frame:s.frame})}catch(n){s.push(Ja(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(Ja(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 Za=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(c.isRecord(t))return c.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(d){if(d instanceof e.ValidationError)throw d;const t=d instanceof e.SDKError&&d.details?d.details:{};throw new e.RestTransportError("Contact metadata request failed",{code:e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:d instanceof Error?d.message:String(d),httpStatus:"number"==typeof t.httpStatus?t.httpStatus:void 0,sourceCode:d instanceof e.SDKError?d.code:void 0}})}},ec=e=>d.z.string().regex(/^https?:\/\/\S+$/i,e),tc=e=>d.z.string().regex(/^wss?:\/\/\S+$/i,e),sc=d.z.object({appKey:d.z.string().min(1,"appKey is required"),enableUserInfoSync:d.z.boolean().optional(),enableSyncData:d.z.array(d.z.enum(["conversation","contact","group"])).optional(),enableDeliveryReceipt:d.z.boolean().optional(),deleteConversationOnGroupDestroyed:d.z.boolean().optional(),syncConversationListConfig:d.z.object({includeEmpty:d.z.boolean().optional()}).strict().optional(),useCustomAttachmentUpload:d.z.boolean().optional(),useFixedDeviceId:d.z.boolean().optional(),deviceId:d.z.string().min(1,"deviceId is required").optional(),serviceConfig:d.z.object({dnsConfigUrls:d.z.array(ec("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:d.z.object({restApiUrl:ec("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:tc("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:ec("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:tc("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:d.z.boolean().optional(),customDeviceName:d.z.string().min(1,"customDeviceName is required").optional(),customOSPlatform:d.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:d.z.string().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:d.z.string().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:d.z.array(d.z.unknown()).optional(),platformAdapterOptions:d.z.object({prefer:d.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:d.z.custom(e=>"object"==typeof e&&null!==e).optional(),overrides:d.z.custom(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{"enableMd5Check"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,r=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&r&&t.addIssue({code:d.z.ZodIssueCode.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),r&&(r?.restApiUrl||t.addIssue({code:d.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),r?.wsUrl||t.addIssue({code:d.z.ZodIssueCode.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),rc=d.z.object({userId:d.z.string().min(1,"userId is required"),token:d.z.string().min(1,"token is required")}),nc=d.z.string().trim().min(1,"token is required"),oc=d.z.object({channelName:d.z.string().trim().min(1,"channelName is required").optional()}).optional(),ic=d.z.array(d.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))),ac=d.z.object({protocol:d.z.string(),domain:d.z.string().optional(),ip:d.z.string().optional(),port:d.z.union([d.z.string(),d.z.number()]).optional()}).passthrough(),cc=d.z.object({rest:d.z.object({hosts:d.z.array(ac).nonempty()}),"msync-wx":d.z.object({hosts:d.z.array(ac).nonempty()}),"sync-ws":d.z.object({hosts:d.z.array(ac).nonempty()}).optional(),enableReportLogs:d.z.enum(["true","false"]).optional(),reportInterval:d.z.number().positive().finite().optional(),enableDataReport:d.z.enum(["true","false"]).optional(),enableMd5Check:d.z.enum(["true","false"]).optional(),uploadinparts_enable:d.z.enum(["true","false"]).optional()}).passthrough(),dc=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],lc=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],uc=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function hc(e){return"object"==typeof e&&null!==e}function pc(e){return Array.isArray(e)?{hosts:e}:function(e){return hc(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function mc(e,t,s){for(const r of t){const t=pc(e[r]);if(t)return{key:r,section:t}}for(const[r,n]of Object.entries(e)){if(!s(r))continue;const e=pc(n);if(e)return{key:r,section:e}}}function gc(s){if(!hc(s))return t.Validator.validateOrThrow(cc,s);const r=pc(s.rest),n=mc(s,lc,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),o=mc(s,uc,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&&!pc(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(cc,i)}function fc(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 yc(e,t){return"https"===e?"https":"http"===e?"http":t}function Ec(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 Rc(e,t){const s=e.filter(e=>e.protocol===t);return s.length>0?s:"http"===t?e.filter(e=>"https"===e.protocol):[]}function Ic(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 vc(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}?${l.createQueryParams({app_key:s,_v:String(Date.now())}).toString()}`}return gc(await n.get(o))}function Sc(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,yc(t.protocol,s))).filter(e=>"string"==typeof e&&e.length>0):[]}async function Cc(t){const s=t.baseUrls&&t.baseUrls.length>0?t.baseUrls:dc;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=await vc(a,t.appKey,t.requestAdapter),n=Ic(Rc(s["msync-wx"].hosts,r));if(0===n.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 o=n[0];if(!o)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 i=Rc(s.rest.hosts,r);if(0===i.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 c=i[0];if(!c)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 d=n.map(e=>fc(e,yc(e.protocol,r))),l=fc(o,yc(o.protocol,r)),u=Sc(s,r);return{websocketUrl:l,websocketUrls:d,syncWebsocketUrls:u,baseUrl:a,restBaseUrl:Ec(c,yc(c.protocol,r)),dnsConfig:s}}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 Tc=t=>new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),Ac=e=>{if(!c.isRecord(e))throw Tc("Invalid REST response");return c.isRecord(e.data)?e.data:e},Oc=(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}}},bc=(e,t)=>{for(const s of t){const t=e[s];if("string"==typeof t)return t}},_c=t=>{const{orgName:s,appName:r}=e.parseAppKey(t.appKey);return`/${s}/${r}`},Mc=async(e,t)=>{const s=await e.get((e=>`${_c(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Ac(e),s=Oc(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===s)throw Tc("Invalid token expires response");return s})(s)},Nc=async(e,t,s)=>{const r=await e.get(((e,t)=>{const s=t?.channelName??"*",r=l.createQueryParams({channelName:s});return`${_c(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,s),{operation:"getRtcTokenInfo"});return(e=>{const t=Ac(e);return{appId:bc(t,["app_id","appId"])??"",rtcToken:bc(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:bc(t,["channel_name","channelName"])??"",rtcUid:Oc(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:Oc(t,["expires_in","expire","expireAt"])??0}})(r)},Dc=async(e,t,s)=>{const r=await e.post((e=>`${_c(e)}/rtc_mapper/batch/get`)(t),{data:s},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Ac(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)},wc=async(e,t)=>{const s=await e.get((e=>`${_c(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const s=c.isRecord(e)&&Array.isArray(e.data)?e.data:[],r=[];for(const n of s){if(!c.isRecord(n))continue;const e=bc(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&r.push(`${t.userId}/${e}`)}return r})(s,t)};class Uc{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 Lc{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 Pc=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.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,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.config.platformAdapterOptions&&(this.platformAdapter=gr(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new ra,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 Lc({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 Uc({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)},[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(sc,r),o=n.customOSPlatform,i=s.normalizeServiceConfig(n.serviceConfig),a={appKey:n.appKey,enableUserInfoSync:n.enableUserInfoSync??!1,enableSyncData:s.normalizeSyncDataTypes(n.enableSyncData??["conversation"]),enableDeliveryReceipt:n.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:n.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:n.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:n.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:i,useFixedDeviceId:n.useFixedDeviceId??!0,deviceId:n.deviceId??"webim",useReplacedMessageContents:n.useReplacedMessageContents??!1,customDeviceName:void 0!==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(rc,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;e.logger.warn("Login started",{userId:n.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const i=this.platformAdapter??gr(this.config.platformAdapterOptions);this.platformAdapter=i,e.installDataReporter({requestAdapter:i.request,onDiagnostic:(t,s)=>{e.logger.warn(t,s)}});const a=e.startDataReportSession({appKey:this.config.appKey,uid:n.userId,sdkVersion:"5.0.1",platform:i.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),c=i.runtime.getNetworkType?.();c&&c.then(t=>{e.updateDataReportNetworkType(t)}).catch(()=>{e.updateDataReportNetworkType("unknown")});const d=e.startDataReportOperation({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:n.userId});let l,u,h;this.updateState(t.ConnectionStatus.CONNECTING),this.logReportEnabled=!1,e.setLogReportState("unknown");let p,m=!1,g=!1,f=!0;if("dns"===this.config.serviceConfig.mode){const s=d?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await Cc({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:i.request});e.logger.warn("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),l=t.websocketUrl,u=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,h=t.restBaseUrl,m="true"===t.dnsConfig.enableReportLogs,p=t.dnsConfig.reportInterval,g="true"===t.dnsConfig.enableMd5Check,f="false"!==t.dnsConfig.uploadinparts_enable,s?.finish({code:200,success:!0}),e.applyDataReportDnsSwitch(t.dnsConfig.enableDataReport),e.logger.debug("DNS report switch resolved",{enabled:m})}catch(E){const r=E instanceof e.SDKError?E.code:-1,n=E instanceof Error?E.message:String(E);throw s?.finish({code:r,success:!1,description:n}),d?.finish({code:r,success:!1,description:n}),e.applyDataReportDnsSwitch(void 0),e.setLogReportState("disabled"),this.updateState(t.ConnectionStatus.DISCONNECTED),E}}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 d?.finish({code:s.code,success:!1,description:s.message}),e.applyDataReportDnsSwitch(void 0),this.updateState(t.ConnectionStatus.DISCONNECTED),s}l=s.wsUrl,h=s.restApiUrl,g=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=s.syncWsUrl?[s.syncWsUrl]:[],this.contactSyncDnsResolved=!1,e.applyDataReportDnsSwitch(void 0)}if(e.updateLogReportContext({restBaseUrl:h,appKey:this.config.appKey,userId:n.userId,token:n.token,requestAdapter:i.request}),e.setLogReportInterval(p),this.logReportEnabled=m,e.setLogReportState(m?"enabled":"disabled"),this.resetCore(),o!==this.loginAttempt){const s=new e.ConnectionError("Login cancelled",{code:e.ERROR_CODES.CONNECTION_CANCELLED,details:{stage:"auth"}});throw d?.finish({code:e.ERROR_CODES.CONNECTION_CANCELLED,success:!1,description:s.message}),this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter(),s}this.core=new li({serverUrl:l,serverUrls:u,userId:n.userId,token:n.token,appKey:this.config.appKey,restBaseUrl:h,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:g,enableMultipartUpload:f,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:a,platformAdapter:i,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),e.updateLogReportContext({resource:this.core.getClientResource()});const y=d?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:l});try{if(e.logger.warn("Connecting core websocket",{serverUrl:l,restBaseUrl:h,userId:n.userId}),await this.core.connect(),y?.finish({code:200,success:!0}),d?.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=h??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(E){e.logger.warn("Report logs on login failed",E)}}catch(E){const s=E instanceof e.SDKError?E.code:-1,r=E instanceof Error?E.message:String(E);throw y?.finish({code:s,success:!1,description:r}),d?.finish({code:s,success:!1,description:r}),this.resetCore(),this.updateState(t.ConnectionStatus.DISCONNECTED),e.resetDataReporter(),E}}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.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.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.config.appKey,userId:this.currentUserId,token:this.authToken,clientResource:t}}async renewToken(s){const r=t.Validator.validateOrThrow(nc,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:Pc,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(r),e.logger.warn("Renew token started",{userId:n.userId});const a=await Mc(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(oc,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:Pc,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)}),Nc(o,n,r)}async getUserIdsWithRTCUids(s){const r=t.Validator.validateOrThrow(ic,s),n=this.getRestContext(),o=new e.RestClient(n.restBaseUrl,{errorMap:Pc,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}),Dc(o,n,r)}async getSelfIdsOnOtherPlatform(){const t=this.getRestContext(),s=new e.RestClient(t.restBaseUrl,{errorMap:Pc,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}),wc(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 Xa({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:rn(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 u.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=en(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=>{Xr.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Zr(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(L(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(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),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 sa({appKey:this.config.appKey,userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const s=this.cacheManager.loadSessionList().map(a.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()}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 Wa(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 Za(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(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(){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 Cc({appKey:this.config.appKey,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:u.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())}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}static isSameConfig(e,t){return e.appKey===t.appKey&&(!!s.isSameStringArray(e.enableSyncData,t.enableSyncData)&&(e.useCustomAttachmentUpload===t.useCustomAttachmentUpload&&(e.enableMd5Check===t.enableMd5Check&&(!!s.isSameServiceConfig(e.serviceConfig,t.serviceConfig)&&(e.useFixedDeviceId===t.useFixedDeviceId&&(e.deviceId===t.deviceId&&(e.useReplacedMessageContents===t.useReplacedMessageContents&&(e.customDeviceName===t.customDeviceName&&(e.customOSPlatform===t.customOSPlatform&&(e.platformAdapterOptions?.prefer===t.platformAdapterOptions?.prefer&&(e.platformAdapterOptions?.runtimeInput===t.platformAdapterOptions?.runtimeInput&&(e.platformAdapterOptions?.overrides===t.platformAdapterOptions?.overrides&&(e.uiKitVersion===t.uiKitVersion&&(e.cacheEncryptionMode===t.cacheEncryptionMode&&(e.enableUserInfoSync===t.enableUserInfoSync&&(e.deleteConversationOnGroupDestroyed===t.deleteConversationOnGroupDestroyed&&(e.syncConversationListConfig.includeEmpty===t.syncConversationListConfig.includeEmpty&&(e.profileSync.userInfoWindowMs===t.profileSync.userInfoWindowMs&&e.profileSync.userInfoBatchSize===t.profileSync.userInfoBatchSize&&e.profileSync.groupNamecardWindowMs===t.profileSync.groupNamecardWindowMs&&e.profileSync.groupNamecardMaxConcurrency===t.profileSync.groupNamecardMaxConcurrency))))))))))))))))))}static normalizeServiceConfig(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??dc,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 xc=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=o.Group,exports.GroupManager=o.GroupManager,exports.ContactManager=u.ContactManager,exports.ChatThread=h.ChatThread,exports.ChatThreadManager=h.ChatThreadManager,exports.ChatRoom=p.ChatRoom,exports.ChatRoomManager=p.ChatRoomManager,exports.PresenceManager=m.PresenceManager,exports.PushManager=g.PushManager,exports.UserInfoManager=f.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=sa,exports.ChatClient=xc,exports.ImageType={ORIGINAL:"original",LARGE:"large"},exports.StreamMessageStatus=U,exports.createPlatformAdapter=gr,exports.detectRuntimePlatform=(e,t)=>bt(t,e).platform;
|