sim-sdk-web 1.2.6 → 1.2.8

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.
@@ -180,17 +180,21 @@ declare class SIMSDK extends Emitter {
180
180
  * @param pongMessage pong 消息数据
181
181
  */
182
182
  private handlePongMessage;
183
+ /** 文档约定:首字节 0x01=Protobuf,0x7D=PING,0x7E=PONG */
184
+ private static readonly BINARY_MSG_TYPE;
183
185
  /**
184
- * 处理SSE消息 - 支持 protobuf
185
- * @param response SSE响应数据
186
+ * 处理SSE消息 - 支持 protobuf(与 FRONTEND_PROTOBUF_PARSING_GUIDE_WEB.md 一致)
187
+ * @param response SSE/WebSocket 响应:JSON 对象 或 二进制(Uint8Array/ArrayBuffer/Base64)
186
188
  */
187
189
  private handleMessage;
188
190
  /**
189
- * 判断是否是 protobuf 格式
190
- * @param response 响应数据
191
- * @returns 是否是 protobuf 格式
191
+ * 是否为二进制消息(仅按数据类型判断,不依赖 useProtobuf 把对象当 protobuf
192
192
  */
193
- private isProtobufFormat;
193
+ private isBinaryMessage;
194
+ /**
195
+ * 将二进制入参统一为 Uint8Array(用于首字节分发与解析)
196
+ */
197
+ private normalizeToBinaryBuffer;
194
198
  /**
195
199
  * 判断是否是 Base64 字符串
196
200
  * @param str 字符串
@@ -198,8 +202,12 @@ declare class SIMSDK extends Emitter {
198
202
  */
199
203
  private isBase64String;
200
204
  /**
201
- * 处理 protobuf 格式的消息
202
- * @param response protobuf 响应数据
205
+ * proto GroupChat 转为 MessageItem,与 JSON 路径共用缓存与 emit
206
+ */
207
+ private protoGroupChatToMessageItem;
208
+ /**
209
+ * 处理 protobuf 格式的消息:解析后与 JSON 分支触发相同的 emit(OnReceiveMessages / OnReceiveSystemMessage / OnReceiveSubscribeMessage 等)
210
+ * @param response protobuf 响应(Uint8Array 或 Base64 字符串,首字节 0x01 为 BYTE_MESSAGE)
203
211
  */
204
212
  private handleProtobufMessage;
205
213
  /**
@@ -255,7 +263,7 @@ declare class SIMSDK extends Emitter {
255
263
  */
256
264
  getConversations: (params: ReqPageParam) => Promise<ServerResponse<PageParam<ConversationItem>>>;
257
265
  /**
258
- * 内部上传文件方法
266
+ * 内部上传文件方法(两步:先拉取阿里云 OSS 上传地址,再 PUT 到 OSS)
259
267
  * @param file 要上传的文件
260
268
  * @param groupId 所属群组 ID,用于标识上传的文件归属
261
269
  * @returns 上传结果,包括原图地址和缩略图地址,或错误信息
@@ -46,6 +46,8 @@ export declare enum RequestApi {
46
46
  GetAnonymousLiveMessageList = "/chat/message/anonymousLiveGroupPull",
47
47
  PrePushCustomerMessage = "/chat/message/prePushCustomerMessage",
48
48
  UploadFile = "/chat/img/upload",
49
+ /** 获取阿里云 OSS 上传凭证(uploadUrl + accessUrl) */
50
+ UploadCredential = "/chat/img/uploadCredential",
49
51
  GetContactByType = "/chat/contact/contactByType",
50
52
  EditContactTag = "/chat/contact/editeContactTag",
51
53
  GetContactTag = "/chat/contact/getContactTag",
package/lib/index.es.js CHANGED
@@ -1 +1 @@
1
- import{EventSourcePolyfill as e}from"event-source-polyfill";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function n(e,n){var o="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(o)return(o=o.call(e)).next.bind(o);if(Array.isArray(e)||(o=function(e,n){if(e){if("string"==typeof e)return t(e,n);var o={}.toString.call(e).slice(8,-1);return"Object"===o&&e.constructor&&(o=e.constructor.name),"Map"===o||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){o&&(e=o);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},o.apply(null,arguments)}function r(e,t){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},r(e,t)}function i(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var s,a,c,u,d;!function(e){e.MESSAGE="message",e.CONVERSATION="conversation",e.GROUP="group",e.USER="user",e.CONTACT="contact"}(s||(s={})),function(e){e[e.MEMBER=0]="MEMBER",e[e.COLLEAGUE=1]="COLLEAGUE",e[e.GROUP=2]="GROUP"}(a||(a={})),function(e){e[e.UnknownError=10005]="UnknownError"}(c||(c={})),function(e){e.Login="/chat/member/login",e.Logout="/chat/member/logout",e.GetChatMember="/chat/member/getChatMember",e.GetGroupInfo="/chat/group/groupInfo",e.GetGroupMembers="/chat/group/groupMembers",e.JoinGroup="/chat/group/joinGroup",e.LeftGroup="/chat/group/leftGroup",e.AnonymousJoinGroup="/chat/group/anonymousJoinGroup",e.AnonymousLeftGroup="/chat/group/anonymousLeftGroup",e.CheckGroupBlock="/chat/group/checkBlock",e.GetMyGroupPermission="/chat/group/permission/getPermission",e.GetGroupPermission="/chat/group/permission/groupPermission",e.GetGroupMember="/chat/group/groupMember",e.GetGroupMemberPermission="/chat/group/permission/groupMemberPermission",e.UpdateGroupPermission="/chat/group/permission/updateGroupPermission",e.UpdateGroupMemberPermission="/chat/group/permission/updateGroupMemberPermission",e.editeGroupName="/chat/group/operation/editeGroupName",e.editeNotification="/chat/group/operation/editeNotification",e.editeGroupCustomer="/chat/group/operation/editeGroupCustomer",e.addAdmin="/chat/group/operation/addAdmin",e.deleteAdmin="/chat/group/operation/deleteAdmin",e.pin="/chat/group/operation/pin",e.muteGroup="/chat/group/operation/muteGroup",e.muteMember="/chat/group/operation/muteMember",e.kickGroupMember="/chat/group/operation/kickGroupMember",e.muteMembers="/chat/group/operation/muteMembers",e.DissolveGroup="/chat/group/dissolve",e.GetAllConversationList="/chat/conversation/conversationList",e.GetChannels="/chat/conversation/getChannels",e.MarkConversationMessageAsRead="/chat/conversation/lastRead",e.PinConversation="/chat/conversation/pinChat",e.MuteConversation="/chat/conversation/mute",e.UpdateLatestMessage="/chat/group/updateLatestMessage",e.GetLatestGroupChats="/chat/group/latestGroupChats",e.CheckLatestMessages="/chat/group/checkLatestMessages",e.CreateTextMessage="/chat/message/push",e.PushMessageToMember="/chat/message/push2Member",e.PushPrivateMessage="/chat/message/pushPrivateMessage",e.PushLiveMessage="/chat/message/liveGroupPush",e.GetHistoryMessageList="/chat/message/pull",e.GetLiveMessageList="/chat/message/liveGroupPull",e.GetAnonymousLiveMessageList="/chat/message/anonymousLiveGroupPull",e.PrePushCustomerMessage="/chat/message/prePushCustomerMessage",e.UploadFile="/chat/img/upload",e.GetContactByType="/chat/contact/contactByType",e.EditContactTag="/chat/contact/editeContactTag",e.GetContactTag="/chat/contact/getContactTag",e.AllocationContactTag="/chat/contact/allocationContactTag",e.AddGroupMembers="/chat/group/operation/addGroupMembers",e.GetFileByType="/chat/message/getFileByType",e.PinChat="/chat/member/pinChat"}(u||(u={})),function(e){e.OnConnected="OnConnected",e.OnDisconnected="OnDisconnected",e.onMaxRetriesReached="onMaxRetriesReached",e.OnReconnecting="OnReconnecting",e.OnReconnected="OnReconnected",e.OnReconnectFailed="OnReconnectFailed",e.OnNetworkChange="OnNetworkChange",e.OnReceiveMessage="OnReceiveMessage",e.OnReceiveProtoMessage="OnReceiveProtoMessage",e.OnReceiveMessages="OnReceiveMessages",e.OnReceiveSubscribeMessage="OnReceiveSubscribeMessage",e.OnReceiveSystemMessage="OnReceiveSystemMessage",e.OnReceivePreMessage="OnReceivePreMessage",e.OnMessagesListLoaded="OnMessagesListLoaded",e.OnActiveConversationSync="OnActiveConversationSync",e.OnMessageSent="OnMessageSent",e.OnMessageFailed="OnMessageFailed",e.OnMessageRevoked="OnMessageRevoked",e.OnMessageDeleted="OnMessageDeleted",e.OnMessageRead="OnMessageRead",e.OnTypingStatusUpdate="OnTypingStatusUpdate",e.OnUserStatusChange="OnUserStatusChange",e.OnKickedOffline="OnKickedOffline",e.OnUserTokenInvalid="OnUserTokenInvalid",e.OnUserTokenExpired="OnUserTokenExpired",e.OnForceOffline="OnForceOffline",e.OnUserInfoUpdated="OnUserInfoUpdated",e.OnGroupCreated="OnGroupCreated",e.OnGroupInfoUpdated="OnGroupInfoUpdated",e.OnGroupDissolved="OnGroupDissolved",e.OnJoinGroup="OnJoinGroup",e.OnLeaveGroup="OnLeaveGroup",e.OnGroupMemberJoined="OnGroupMemberJoined",e.OnGroupMemberLeft="OnGroupMemberLeft",e.OnGroupMemberKicked="OnGroupMemberKicked",e.OnGroupOwnerChanged="OnGroupOwnerChanged",e.OnGroupAdminAdded="OnGroupAdminAdded",e.OnGroupAdminRemoved="OnGroupAdminRemoved",e.OnGroupMemberMuted="OnGroupMemberMuted",e.OnGroupMemberUnmuted="OnGroupMemberUnmuted",e.OnGroupAllMemberMuted="OnGroupAllMemberMuted",e.OnGroupAllMemberUnmuted="OnGroupAllMemberUnmuted",e.OnConversationCreated="OnConversationCreated",e.OnConversationDeleted="OnConversationDeleted",e.OnConversationListUpdated="OnConversationListUpdated",e.OnConversationUpdated="OnConversationUpdated",e.OnUnreadCountChanged="OnUnreadCountChanged",e.OnConversationPinned="OnConversationPinned",e.OnConversationUnpinned="OnConversationUnpinned",e.OnConversationMuted="OnConversationMuted",e.OnConversationUnmuted="OnConversationUnmuted",e.OnPongConn="OnPongConn",e.OnPongReConn="OnPongReConn",e.OnPongIdle="OnPongIdle",e.OnError="OnError",e.OnWarning="OnWarning",e.OnLog="OnLog"}(d||(d={}));var l,g,h,m,p,f,v=/*#__PURE__*/function(){function e(){var e;this.events=((e={})[d.OnReceiveMessage]=[],e[d.OnReceiveSystemMessage]=[],e[d.OnReceiveMessages]=[],e[d.OnConversationListUpdated]=[],e[d.OnMessagesListLoaded]=[],e[d.OnActiveConversationSync]=[],e[d.OnConnected]=[],e[d.OnDisconnected]=[],e[d.OnReconnected]=[],e)}var t=e.prototype;return t.emit=function(e,t){var n=this.events[e];return n&&n.forEach(function(e){return e(t)}),this},t.on=function(e,t){var n;return this.events[e]||(this.events[e]=[]),null==(n=this.events[e])||n.push(t),this},t.off=function(e,t){var n=this.events[e];if(n){var o=n.indexOf(t);o>-1&&(n.splice(o,1),0===n.length&&delete this.events[e])}return this},e}();!function(e){e[e.PrivateChat=0]="PrivateChat",e[e.PrivateGroup=1]="PrivateGroup",e[e.PublicGroup=2]="PublicGroup",e[e.CustomerService=3]="CustomerService",e[e.LiveGroup=4]="LiveGroup",e[e.ChanneRoom=5]="ChanneRoom"}(l||(l={})),function(e){e[e.TEXT=0]="TEXT",e[e.IMAGE=1]="IMAGE",e[e.FILE=2]="FILE",e[e.AUDIO=3]="AUDIO",e[e.VIDEO=4]="VIDEO",e[e.LINK=5]="LINK",e[e.GIF=6]="GIF",e[e.OPTION=7]="OPTION",e[e.EMOJI=8]="EMOJI",e[e.CUSTOM=100]="CUSTOM"}(g||(g={})),function(e){e[e.EVENT_PONG_CONN=0]="EVENT_PONG_CONN",e[e.EVENT_PONG_RE_CONN=1]="EVENT_PONG_RE_CONN",e[e.EVENT_PONG_IDLE=2]="EVENT_PONG_IDLE",e[e.EVENT_MESSAGE_PUSH=3]="EVENT_MESSAGE_PUSH",e[e.EVENT_SYSTEM_MESSAGE_PUSH=4]="EVENT_SYSTEM_MESSAGE_PUSH",e[e.EVENT_LIVE_SYSTEM_MESSAGE_PUSH=5]="EVENT_LIVE_SYSTEM_MESSAGE_PUSH",e[e.EVENT_PRE_MESSAGE_PUSH=6]="EVENT_PRE_MESSAGE_PUSH",e[e.EVENT_SUBSCRIBE_MESSAGE_PUSH=7]="EVENT_SUBSCRIBE_MESSAGE_PUSH"}(h||(h={})),function(e){e[e.JOIN=0]="JOIN",e[e.LEFT=1]="LEFT",e[e.LAST_READ_UPDATE=2]="LAST_READ_UPDATE",e[e.PERMISSION_UPDATE=3]="PERMISSION_UPDATE",e[e.IDENTITY_UPDATE=4]="IDENTITY_UPDATE",e[e.PING_UPDATE=5]="PING_UPDATE"}(m||(m={})),function(e){e[e.GroupMemberPermissionChange=3]="GroupMemberPermissionChange",e[e.GroupPermissionChange=4]="GroupPermissionChange"}(p||(p={})),function(e){e.SSE="sse",e.WEBSOCKET="websocket"}(f||(f={}));var C="undefined"!=typeof uni,b="undefined"!=typeof window,S="simsdk_",M={CONVERSATIONS:S+"conversations",GROUP_MESSAGES:S+"group_messages",USER_INFO:S+"user_info",META_INFO:S+"meta"},T={MAX_CONVERSATIONS:100,MAX_GROUP_MESSAGES:200,STORAGE_CHUNK_SIZE:512e3,CACHE_TTL:6048e5,EXPIRY_CHECK_INTERVAL:18e5},E=/*#__PURE__*/function(){function e(e){var t=void 0===e?{}:e,n=t.persistEnabled,r=void 0===n||n,i=t.debug,s=void 0!==i&&i,a=t.config,c=void 0===a?{}:a;this.conversationCache=[],this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder=new Map,this.userInfo={},this.currentUsername=void 0,this.activeConversation=void 0,this.metaInfo={},this.persistEnabled=void 0,this.debug=void 0,this.config=void 0,this.cleanupTimer=void 0,this.persistEnabled=r,this.debug=s,this.config=o({},T,c)}var t=e.prototype;return t.initialize=function(e){this.currentUsername&&this.currentUsername!==e&&(this.debug&&console.log("User switched from "+this.currentUsername+" to "+e+", clearing cache"),this.clear()),this.currentUsername=e,this.userInfo.username=e,this.persistEnabled&&this.loadFromStorage(),this.setupCleanupInterval(),this.debug&&(console.log("Cache initialized for user:",e),console.log("Loaded conversations:",this.conversationCache.length),console.log("Loaded group messages for groups:",Object.keys(this.groupMessageCache).length))},t.clear=function(){this.conversationCache=[],this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder.clear(),this.persistEnabled&&this.clearCurrentUserStorage(),this.debug&&console.log("Cache cleared")},t.clearCurrentUserStorage=function(){try{if(!this.currentUsername)return void this.clearStorage();var e=this.getUserStorageKey(M.CONVERSATIONS);localStorage.removeItem(e);var t=this.getUserStorageKey(M.USER_INFO);localStorage.removeItem(t);for(var o,r=n(Object.keys(localStorage).filter(function(e){return e.startsWith(M.GROUP_MESSAGES+".")}));!(o=r()).done;)localStorage.removeItem(o.value)}catch(e){console.error("Failed to clear current user storage:",e)}},t.getConversations=function(){return[].concat(this.conversationCache)},t.clearConversationUnread=function(e){var t=this.conversationCache.find(function(t){return t.id===e});t&&(t.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.updateConversationLastRead=function(e,t){var n=this.conversationCache.find(function(t){return t.id===e});n&&(n.lastRead=t,n.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.clearAllConversationUnread=function(){this.conversationCache.forEach(function(e){e.unreadCount>0&&(e.unreadCount=0)}),this.persistEnabled&&this.saveConversationsToStorage()},t.getActiveConversation=function(){return this.activeConversation},t.setConversations=function(e,t){var n=this;if(void 0===t&&(t=!1),this.conversationCache=e.length>this.config.MAX_CONVERSATIONS?e.slice(0,this.config.MAX_CONVERSATIONS):[].concat(e),t)this.pinnedConversationOrder.clear(),this.conversationCache.forEach(function(e,t){e.pin&&n.pinnedConversationOrder.set(e.id,t)});else{var o=-1;this.pinnedConversationOrder.forEach(function(e){e>o&&(o=e)}),this.conversationCache.forEach(function(e,t){e.pin&&!n.pinnedConversationOrder.has(e.id)&&n.pinnedConversationOrder.set(e.id,o+t+1)})}this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversation=function(e){var t=this.conversationCache.findIndex(function(t){return t.id===e.id});t>=0?this.conversationCache[t]=o({},e):(this.conversationCache.push(o({},e)),this.conversationCache.length>this.config.MAX_CONVERSATIONS&&this.enforceConversationLimit()),this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversationPinStatus=function(e,t){var n=this.conversationCache.findIndex(function(t){return t.id===e});if(-1!==n){var o=this.conversationCache[n],r=!0===o.pin;if(o.pin=t,t&&!r){var i=-1;this.pinnedConversationOrder.forEach(function(e){e>i&&(i=e)}),this.pinnedConversationOrder.set(e,i+1)}else!t&&r&&this.pinnedConversationOrder.delete(e);this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()}},t.updateConversationWithMessage=function(e,t){var n,o=e.groupId;if(!o)return!1;var r=this.conversationCache.findIndex(function(e){return e.id===o});if(-1===r)return!1;var i=this.conversationCache[r],s=(null==(n=i.latest)?void 0:n.msgId)||0;return this.activeConversation&&this.activeConversation.id===o?(i.unreadCount=0,i.lastRead=e.msgId):t!==e.username&&(i.unreadCount+=e.msgId>s?e.msgId-s:1),i.latest=e,this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage(),!0},t.getGroupMessages=function(e){return this.recordAccess(e),!this.groupMessageCache[e]&&this.persistEnabled&&this.loadGroupMessagesFromStorage(e),this.groupMessageCache[e]||[]},t.addGroupMessage=function(e){if(e.groupId){this.recordAccess(e.groupId),this.groupMessageCache[e.groupId]||(this.groupMessageCache[e.groupId]=[]);var t=this.groupMessageCache[e.groupId].findIndex(function(t){return t.msgId===e.msgId});t>=0?this.groupMessageCache[e.groupId][t]=e:this.groupMessageCache[e.groupId].push(e),this.sortGroupMessages(e.groupId),this.limitGroupMessageCache(e.groupId),this.enforceMemoryLimits(),this.persistEnabled&&this.saveGroupMessagesToStorage(e.groupId)}},t.addGroupMessages=function(e){for(var t,o=this,r={},i=n(e);!(t=i()).done;){var s=t.value;s.groupId&&(r[s.groupId]||(r[s.groupId]=[]),r[s.groupId].push(s))}for(var a=0,c=Object.entries(r);a<c.length;a++){var u=c[a],d=u[0],l=u[1];this.recordAccess(Number(d)),this.groupMessageCache[d]||(this.groupMessageCache[d]=[]);for(var g,h=function(){var e=g.value,t=o.groupMessageCache[d].findIndex(function(t){return t.msgId===e.msgId});t>=0?o.groupMessageCache[d][t]=e:o.groupMessageCache[d].push(e)},m=n(l);!(g=m()).done;)h();this.sortGroupMessages(Number(d)),this.limitGroupMessageCache(Number(d)),this.persistEnabled&&this.saveGroupMessagesToStorage(Number(d))}this.enforceMemoryLimits()},t.sortConversations=function(){var e=this;this.conversationCache.sort(function(t,n){var o,r,i,s,a=!0===t.pin,c=!0===n.pin;if(a&&!c)return-1;if(!a&&c)return 1;if(a&&c)return(null!=(i=e.pinnedConversationOrder.get(t.id))?i:0)-(null!=(s=e.pinnedConversationOrder.get(n.id))?s:0);var u=(null==(o=t.latest)?void 0:o.createTime)||0;return((null==(r=n.latest)?void 0:r.createTime)||0)-u})},t.sortGroupMessages=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].sort(function(e,t){return(t.createTime||0)-(e.createTime||0)})},t.limitGroupMessageCache=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].length>this.config.MAX_GROUP_MESSAGES&&(this.groupMessageCache[e]=this.groupMessageCache[e].slice(0,this.config.MAX_GROUP_MESSAGES))},t.recordAccess=function(e){this.accessTimeRecord[e]=Date.now()},t.enforceConversationLimit=function(){this.conversationCache.length<=this.config.MAX_CONVERSATIONS||(this.sortConversations(),this.conversationCache=this.conversationCache.slice(0,this.config.MAX_CONVERSATIONS))},t.enforceMemoryLimits=function(){var e=this,t=Object.keys(this.groupMessageCache).length;if(t>10){var n=Object.keys(this.groupMessageCache).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}});n.sort(function(e,t){return e.lastAccess-t.lastAccess});for(var o=Math.ceil(.3*t),r=0;r<o&&r<n.length;r++){var i=n[r].groupId;this.persistEnabled&&(delete this.groupMessageCache[i],this.debug&&console.log("Released memory for inactive group: "+i))}}},t.setupCleanupInterval=function(){var e=this;this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=window.setInterval(function(){e.cleanupExpiredData()},this.config.EXPIRY_CHECK_INTERVAL)},t.cleanupExpiredData=function(){var e=Date.now();this.metaInfo.lastCleanup=e,this.debug&&console.log("Running cache cleanup");for(var t=0,n=Object.entries(this.accessTimeRecord);t<n.length;t++){var o=n[t],r=o[0];e-o[1]>this.config.CACHE_TTL&&(delete this.accessTimeRecord[r],this.groupMessageCache[r]&&delete this.groupMessageCache[r])}this.persistEnabled&&this.saveMetaInfoToStorage()},t.getUserStorageKey=function(e){return this.currentUsername?e+"_"+this.currentUsername:e},t.loadFromStorage=function(){var e=this;try{var t=localStorage.getItem(M.META_INFO);t&&(this.metaInfo=JSON.parse(t));var n=this.getUserStorageKey(M.CONVERSATIONS),o=localStorage.getItem(n);this.conversationCache=o?JSON.parse(o):[],Object.keys(localStorage).filter(function(e){return e.startsWith(M.GROUP_MESSAGES+".")}).forEach(function(t){var n=t.split(".")[1];n&&!isNaN(Number(n))&&(e.accessTimeRecord[n]=0)});var r=this.getUserStorageKey(M.USER_INFO),i=localStorage.getItem(r);this.userInfo=i?JSON.parse(i):{username:this.currentUsername}}catch(e){console.error("Failed to load cache from storage:",e),this.clearStorage()}},t.loadGroupMessagesFromStorage=function(e){try{for(var t=[],n=0,o=!0;o;){var r=localStorage.getItem(M.GROUP_MESSAGES+"."+e+(n>0?"."+n:""));if(r){var i=JSON.parse(r);t=t.concat(i),n++}else o=!1}t.length>0&&(this.groupMessageCache[e]=t,this.sortGroupMessages(e),this.limitGroupMessageCache(e),this.debug&&console.log("Loaded "+t.length+" messages for group "+e+" from storage"))}catch(t){console.error("Failed to load group messages for "+e+" from storage:",t)}},t.saveConversationsToStorage=function(){try{var e=this.getUserStorageKey(M.CONVERSATIONS);localStorage.setItem(e,JSON.stringify(this.conversationCache))}catch(e){console.error("Failed to save conversations to storage:",e),this.handleStorageError()}},t.saveGroupMessagesToStorage=function(e){try{if(void 0!==e){var t=this.groupMessageCache[e];if(!t||0===t.length)return;var n=JSON.stringify(t);if(n.length>this.config.STORAGE_CHUNK_SIZE){this.clearGroupMessageStorage(e);for(var o=t.length,r=Math.max(1,Math.floor(this.config.STORAGE_CHUNK_SIZE/(n.length/o))),i=0;i<o;i+=r){var s=t.slice(i,i+r),a=Math.floor(i/r);localStorage.setItem(M.GROUP_MESSAGES+"."+e+(a>0?"."+a:""),JSON.stringify(s))}}else localStorage.setItem(M.GROUP_MESSAGES+"."+e,n)}else for(var c=0,u=Object.keys(this.groupMessageCache);c<u.length;c++)this.saveGroupMessagesToStorage(Number(u[c]))}catch(e){console.error("Failed to save group messages to storage:",e),this.handleStorageError()}},t.saveMetaInfoToStorage=function(){try{localStorage.setItem(M.META_INFO,JSON.stringify(this.metaInfo))}catch(e){console.error("Failed to save meta info to storage:",e)}},t.handleStorageError=function(){for(var e=this,t=Object.keys(this.accessTimeRecord).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}}).sort(function(e,t){return e.lastAccess-t.lastAccess}),n=Math.max(1,Math.floor(.2*t.length)),o=0;o<n&&o<t.length;o++)this.clearGroupMessageStorage(Number(t[o].groupId)),this.debug&&console.log("Cleared storage for group "+t[o].groupId+" due to quota exceeded")},t.clearGroupMessageStorage=function(e){for(var t=0,n=!0;n;){var o=M.GROUP_MESSAGES+"."+e+(t>0?"."+t:"");null!==localStorage.getItem(o)?(localStorage.removeItem(o),t++):n=!1}},t.saveUserInfoToStorage=function(){try{var e=this.getUserStorageKey(M.USER_INFO);localStorage.setItem(e,JSON.stringify(this.userInfo))}catch(e){console.error("Failed to save user info to storage:",e)}},t.clearStorage=function(){try{for(var e,t=n(Object.keys(localStorage).filter(function(e){return e.startsWith(S)}));!(e=t()).done;)localStorage.removeItem(e.value)}catch(e){console.error("Failed to clear storage:",e)}},t.destroy=function(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.debug&&console.log("Cache manager destroyed")},t.markConversationAsActive=function(e,t){void 0===t&&(t=!0),this.accessTimeRecord[e]=Date.now();var n,r=this.conversationCache.find(function(t){return t.id===e});return!!r&&(this.activeConversation=o({},r),t&&r.unreadCount>0&&(r.unreadCount=0,null!=(n=r.latest)&&n.msgId&&(r.lastRead=r.latest.msgId),this.persistEnabled&&this.saveConversationsToStorage()),!0)},t.resetActiveConversation=function(){var e,t=!(null==(e=this.activeConversation)||!e.id);return this.activeConversation=void 0,this.debug&&t&&console.log("Active conversation reset"),t},e}(),P=/*#__PURE__*/function(){function t(e){this.url=void 0,this.token=void 0,this.eventSource=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.isDestroyed=!1,this.debug=!1,this._openHandler=null,this._errorHandler=null,this._messageHandler=null,this._customHandlers=new Map,this.connectTimeoutRef=null,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange}var n=t.prototype;return n.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.removeAllEventListeners=function(){var e=this;this.eventSource&&(this._openHandler&&this.eventSource.removeEventListener("open",this._openHandler),this._errorHandler&&this.eventSource.removeEventListener("error",this._errorHandler),this._messageHandler&&this.eventSource.removeEventListener("message",this._messageHandler),this.handlers.forEach(function(t,n){var o=e._customHandlers.get(n);o&&e.eventSource&&e.eventSource.removeEventListener(n,o)}))},n.subscribe=function(e,t){var n=this;this.handlers.set(e,t);var o=function(e){try{var o=JSON.parse(e.data);t(o)}catch(e){n.debugError("Error parsing message data:",e)}};this._customHandlers.set(e,o),this.eventSource?this.eventSource.addEventListener(e,o):this.connect()},n.connect=function(){var t=this;return this.connected&&this.eventSource?Promise.reject(new Error("SSE is already connected!")):new Promise(function(n,o){try{t.eventSource=new e(t.url,{heartbeatTimeout:36e5,withCredentials:!1,headers:{Authorization:"Bearer "+t.token}}),t._openHandler=function(e){t.debugLog("SSE connection established"),t.connected=!0,t.onConnectionChangeCallback&&t.onConnectionChangeCallback(!0),t.reconnectAttempts>0&&t.onReconnectSuccessCallback&&t.onReconnectSuccessCallback(),t.reconnectAttempts=0,t.reconnectTimeout=5e3,n("SSE connect successful!")},t._errorHandler=function(e){t.debugError("SSE connection error:",e),t.connected=!1,t.onConnectionChangeCallback&&t.onConnectionChangeCallback(!1),401===e.status||e.statusText&&e.statusText.includes("Unauthorized")?(t.cleanup(),t.connectTimeoutRef&&(clearTimeout(t.connectTimeoutRef),t.connectTimeoutRef=null),t.notifyConnectionClosed(!0)):t.handleReconnect(),t.connected||o(new Error("SSE connect error"))},t._messageHandler=function(e){try{t.debugLog("SSE received message:",e.data);var n=JSON.parse(e.data);t.onMessageCallback&&t.onMessageCallback(n)}catch(e){t.debugError("Error parsing message:",e)}},t.eventSource.addEventListener("open",t._openHandler),t.eventSource.addEventListener("error",t._errorHandler),t.eventSource.addEventListener("message",t._messageHandler),t.handlers.forEach(function(e,n){var o=t._customHandlers.get(n);o&&t.eventSource&&t.eventSource.addEventListener(n,o)}),t.connectTimeoutRef=setTimeout(function(){t.connected||(o(new Error("Connection timeout")),t.handleReconnect())},t.connectTimeout);var r=t._openHandler;t._openHandler=function(e){clearTimeout(t.connectTimeoutRef),r(e)}}catch(e){t.debugError("Failed to create EventSource:",e),t.handleReconnect(),o(e)}})},n.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("SSE connection closed due to authentication error"):this.debugLog("SSE connection closed")},n.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("SSE is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroySse(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},n.cleanup=function(){this.eventSource&&(this.removeAllEventListeners(),this.eventSource.close(),this.eventSource=null),this.connected=!1},n.unsubscribe=function(){this.cleanup(),this.handlers.clear(),this._customHandlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)},n.destroySse=function(){this.unsubscribe(),this.isDestroyed=!0,this.notifyConnectionClosed()},n.close=function(){this.destroySse(),this.debugLog("SSE 连接已关闭")},n.isConnected=function(){return this.connected},n.send=function(e){var t="当前协议不可用:SSE 是单向通信协议,不支持客户端向服务器发送消息";throw this.debugError(t),new Error(t)},t}(),y=/*#__PURE__*/function(){function e(e){this.url=void 0,this.token=void 0,this.websocket=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.connectTimeoutRef=null,this.isDestroyed=!1,this.debug=!1,this.lastPingTime=0,this.pingCheckTimer=null,this.pageVisibilityHandler=null,this.isPageVisible=!0,this.lastVisibleTime=Date.now(),this.PING_TIMEOUT=12e4,this.PING_CHECK_INTERVAL=5e3,this.RECONNECT_DELAY=3e3,this.PAGE_HIDDEN_TOLERANCE=6e4,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange,this.initPageVisibilityDetection()}var t=e.prototype;return t.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.subscribe=function(e,t){this.handlers.set(e,t),this.websocket?this.addMessageHandler(e,t):this.connect()},t.addMessageHandler=function(e,t){var n=this;this.websocket&&this.websocket.addEventListener("message",function(o){try{var r=JSON.parse(o.data);r.type===e&&t(r)}catch(e){n.debugError("Error parsing WebSocket message data:",e)}})},t.connect=function(){var e=this;return this.connected&&this.websocket?Promise.reject(new Error("WebSocket is already connected!")):new Promise(function(t,n){try{var o=new URL(e.url);o.searchParams.set("token",e.token),e.websocket=new WebSocket(o.toString()),e.websocket.binaryType="arraybuffer",e.connectTimeoutRef=setTimeout(function(){e.connected||(n(new Error("WebSocket connection timeout")),e.handleReconnect())},e.connectTimeout),e.websocket.onopen=function(n){e.debugLog("WebSocket connection established"),e.connected=!0,clearTimeout(e.connectTimeoutRef),e.lastPingTime=Date.now(),e.startPingTimeoutCheck(),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!0),e.reconnectAttempts>0&&e.onReconnectSuccessCallback&&e.onReconnectSuccessCallback(),e.reconnectAttempts=0,e.reconnectTimeout=5e3,t("WebSocket connect successful!")},e.websocket.onerror=function(t){e.debugError("WebSocket connection error:",t),e.connected=!1,clearTimeout(e.connectTimeoutRef),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!1),e.handleReconnect(),e.connected||n(new Error("WebSocket connect error"))},e.websocket.onclose=function(t){e.debugLog("WebSocket connection closed:",t.code,t.reason),e.connected=!1,1002===t.code||1003===t.code||t.reason&&t.reason.includes("Unauthorized")?(e.cleanup(),e.notifyConnectionClosed(!0)):(e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.handleReconnect())},e.websocket.onmessage=function(t){try{t.data instanceof ArrayBuffer?e.handleBinaryMessage(t.data):e.handleTextMessage(t.data),e.lastPingTime=Date.now()}catch(t){e.debugError("Error handling WebSocket message:",t)}},e.handlers.forEach(function(t,n){e.addMessageHandler(n,t)})}catch(t){e.debugError("Failed to create WebSocket:",t),e.handleReconnect(),n(t)}})},t.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("WebSocket connection closed due to authentication error"):this.debugLog("WebSocket connection closed")},t.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("WebSocket is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroyWebSocket(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds... (attempt "+(this.reconnectAttempts+1)+"/"+this.maxReconnectAttempts+")"),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},t.handleBinaryMessage=function(e){var t=new DataView(e);if(!(e.byteLength<1)){var n=t.getUint8(0);if(125===n&&e.byteLength>=9){var o=t.getBigInt64(1,!1);return this.debugLog("收到服务端心跳 ping:",o.toString()),this.lastPingTime=Date.now(),void this.sendPong(o)}this.debugLog("收到二进制消息,类型:",n,"长度:",e.byteLength)}},t.handleTextMessage=function(e){try{this.debugLog("WebSocket received text message:",e);var t=JSON.parse(e);if("pong"===t.type||2===t.ev)return this.connected=!0,void(this.lastPingTime=Date.now());this.onMessageCallback&&this.onMessageCallback(t)}catch(e){this.debugError("Error parsing WebSocket text message:",e)}},t.sendPong=function(e){if(this.websocket&&this.websocket.readyState===WebSocket.OPEN)try{var t=new ArrayBuffer(9),n=new DataView(t);n.setUint8(0,126),n.setBigInt64(1,e,!1),this.websocket.send(t),this.debugLog("已回复心跳 pong, timestamp:",e.toString())}catch(e){this.debugError("Failed to send pong:",e)}else this.debugWarn("WebSocket is not open, cannot send pong")},t.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.lastVisibleTime=Date.now(),this.pageVisibilityHandler=function(){var t=e.isPageVisible;if(e.isPageVisible=!document.hidden,t&&!e.isPageVisible)e.lastVisibleTime=Date.now(),e.debugLog("Page became hidden, pausing ping timeout check");else if(!t&&e.isPageVisible){var n=Date.now()-e.lastVisibleTime;e.debugLog("Page became visible after "+n+"ms"),e.websocket&&e.websocket.readyState===WebSocket.OPEN&&n>e.PAGE_HIDDEN_TOLERANCE&&(e.debugLog("Page was hidden for a long time, adjusting ping time"),e.lastPingTime=Date.now()-(e.PING_TIMEOUT-e.PAGE_HIDDEN_TOLERANCE))}},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},t.startPingTimeoutCheck=function(){var e=this;this.stopPingTimeoutCheck(),this.pingCheckTimer=window.setInterval(function(){if(!e.isDestroyed&&e.websocket)if(e.isPageVisible){if(e.websocket.readyState!==WebSocket.OPEN)return e.debugWarn("WebSocket state is "+e.websocket.readyState+", connection may be broken"),e.connected=!1,e.stopPingTimeoutCheck(),e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),void e.delayedReconnect();var t=Date.now()-e.lastPingTime;t>e.PING_TIMEOUT?(e.debugWarn("Ping timeout: "+t+"ms since last ping, connection may be broken"),e.connected=!1,e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.delayedReconnect()):e.debugLog("Last ping received "+t+"ms ago")}else e.debugLog("Page is hidden, skipping ping timeout check");else e.stopPingTimeoutCheck()},this.PING_CHECK_INTERVAL)},t.stopPingTimeoutCheck=function(){null!==this.pingCheckTimer&&(clearInterval(this.pingCheckTimer),this.pingCheckTimer=null)},t.delayedReconnect=function(){var e=this;null===this.reconnectTimer&&(this.debugLog("Delaying reconnect for "+this.RECONNECT_DELAY/1e3+" seconds to prevent reconnect storm..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectTimer=null,e.handleReconnect()},this.RECONNECT_DELAY))},t.cleanup=function(){this.stopPingTimeoutCheck(),this.websocket&&(this.websocket.close(),this.websocket=null),this.connected=!1},t.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null)},t.unsubscribe=function(){this.cleanup(),this.handlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.cleanupPageVisibilityDetection()},t.destroyWebSocket=function(){this.unsubscribe(),this.isDestroyed=!0,this.cleanupPageVisibilityDetection(),this.notifyConnectionClosed()},t.close=function(){this.destroyWebSocket(),this.debugLog("WebSocket 连接已关闭")},t.isConnected=function(){var e;return this.connected&&(null==(e=this.websocket)?void 0:e.readyState)===WebSocket.OPEN},t.send=function(e){if(!this.websocket||!this.isConnected())return this.debugWarn("WebSocket is not connected, cannot send message"),!1;try{if("string"==typeof e)this.websocket.send(e),this.debugLog("WebSocket message sent (string):",e);else if(e instanceof ArrayBuffer||e instanceof Blob)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBuffer/Blob ("+(e instanceof ArrayBuffer?e.byteLength:e.size)+" bytes)");else if(e instanceof Uint8Array||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof DataView)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBufferView ("+e.byteLength+" bytes)");else{var t=JSON.stringify(e);this.websocket.send(t),this.debugLog("WebSocket message sent (JSON):",t)}return!0}catch(e){return this.debugError("Failed to send WebSocket message:",e),!1}},e}(),O=["protocol"],G=/*#__PURE__*/function(){function e(){}return e.createClient=function(e){var t=e.protocol,n=function(e,t){if(null==e)return{};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o]}return n}(e,O);switch(t){case f.SSE:return new P(n);case f.WEBSOCKET:return new y(n);default:throw new Error("Unsupported connection protocol: "+t)}},e}(),k=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.login=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.Login,method:"POST"}))}catch(e){return Promise.reject(e)}},t.logout=function(){try{return Promise.resolve(this.sdk.sendRequest({data:{},url:u.Logout,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getChatMember=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{chatId:e,parent:t},url:u.GetChatMember,method:"GET"}))}catch(e){return Promise.reject(e)}},e}(),R=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.sendMessage=function(e,t){try{var n=this;return Promise.resolve(function(o,r){try{var i=Promise.resolve(n.sdk.sendRequest({data:e,url:t,method:"POST"}))}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(e){throw console.error("Failed to send message",e),e}))}catch(e){return Promise.reject(e)}},t.getMessageApi=function(e,t){return t===l.PrivateChat?u.PushPrivateMessage:t===l.LiveGroup?u.PushLiveMessage:null!=e&&e.receiverName?u.PushMessageToMember:u.CreateTextMessage},t.createMessage=function(e,t,n,r,i){void 0===r&&(r={});var s={groupType:n};n===l.PublicGroup||n===l.PrivateGroup||n===l.LiveGroup?s.groupId=t:s.receiverName=t;var a=o({},s,r,{msgType:e},i);return this.sendMessage(a,this.getMessageApi(s,n))},t.createTextMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.TEXT,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.createImageMessage=function(e,t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(g.IMAGE,n,o,r,{link:e,snapshot:t}))}catch(e){return Promise.reject(e)}},t.createFileMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.FILE,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createAudioMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.AUDIO,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createVideoMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.VIDEO,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createLinkMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.LINK,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createGifMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.GIF,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createOptionMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.OPTION,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.createEmojiMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.EMOJI,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.createCustomMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(g.CUSTOM,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.getHistoryMessageList=function(e){var t=e.groupId,n=e.lastId,o=e.type,r=e.size,i=void 0===r?100:r;try{return Promise.resolve(this.sdk.sendRequest({url:u.GetHistoryMessageList,method:"POST",data:{groupId:t,lastId:n,type:o,size:i}}))}catch(e){return Promise.reject(e)}},t.getLiveMessageList=function(e){var t=e.groupId;try{var n;return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:null!=(n=this.sdk.getConfig)&&n.anonLogin?u.GetAnonymousLiveMessageList:u.GetLiveMessageList,method:"POST"}))}catch(e){return Promise.reject(e)}},t.prePushCustomerMessage=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.PrePushCustomerMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},e}(),A=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.getConversations=function(e){try{var t=this;return Promise.resolve(t.sdk.sendRequest({data:e,url:u.GetAllConversationList,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(t.normalizeConversation),e})}catch(e){return Promise.reject(e)}},t.getChannels=function(e){try{var t=this;return Promise.resolve(t.sdk.sendRequest({data:e,url:u.GetChannels,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(t.normalizeConversation),e})}catch(e){return Promise.reject(e)}},t.markConversationRead=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},t.markLastRead=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,msgId:t},url:u.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},t.pinConversation=function(e,t){void 0===t&&(t=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,isTop:t},url:u.PinConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},t.muteConversation=function(e,t){void 0===t&&(t=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,mute:t},url:u.MuteConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},t.normalizeConversation=function(e){var t,n,r,i,s,a,c,u;return o({},e,{id:e.id,name:e.name||"",groupType:e.groupType||0,avatar:e.avatar||"",status:null!=(t=e.status)?t:1,latest:null!=(n=e.latest)?n:{},unreadCount:null!=(r=e.unreadCount)?r:0,lastRead:e.lastRead,draftText:null!=(i=e.draftText)?i:"",custom:null!=(s=e.custom)?s:"",groupMemberId:null!=(a=e.groupMemberId)?a:"",pin:null!=(c=e.pin)&&c,supportId:e.supportId||"",supportNick:e.supportNick||"",identity:null!=(u=e.identity)?u:1})},e}(),I=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.getGroupInfo=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:u.GetGroupInfo,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupMember=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:u.GetGroupMember,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupMembers=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.GetGroupMembers,method:"GET"}))}catch(e){return Promise.reject(e)}},t.joinGroup=function(e){try{var t;return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:null!=(t=this.sdk.getConfig)&&t.anonLogin?u.AnonymousJoinGroup:u.JoinGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},t.leftGroup=function(e){try{var t;return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:null!=(t=this.sdk.getConfig)&&t.anonLogin?u.AnonymousLeftGroup:u.LeftGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},t.checkGroupBlock=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:u.CheckGroupBlock,method:"GET"}))}catch(e){return Promise.reject(e)}},t.updateLatestMessage=function(e){try{var t=Object.fromEntries(e.entries());return Promise.resolve(this.sdk.sendRequest({data:{latestMessage:t},url:u.UpdateLatestMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getGroupLatestMessage=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groups:e},url:u.GetLatestGroupChats,method:"POST"}))}catch(e){return Promise.reject(e)}},t.checkGroupLatestMessage=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{ttl:e},url:u.CheckLatestMessages,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getMyGroupPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:u.GetMyGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:u.GetGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupMemberPermission=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,targetMemberId:t},url:u.GetGroupMemberPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},t.updateGroupPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.UpdateGroupPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},t.updateGroupMemberPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.UpdateGroupMemberPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},t.kickGroupMember=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.kickGroupMember,method:"POST"}))}catch(e){return Promise.reject(e)}},t.muteMembers=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.muteMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},t.editGroupName=function(e,t,n){try{return Promise.resolve(this.sdk.sendRequest({url:u.editeGroupName,method:"GET",data:{groupId:e,name:t,avatar:n}}))}catch(e){return Promise.reject(e)}},t.editNotification=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:u.editeNotification,method:"GET",data:{groupId:e,notification:t}}))}catch(e){return Promise.reject(e)}},t.editGroupCustomer=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:u.editeGroupCustomer,method:"GET",data:{groupId:e,customer:t}}))}catch(e){return Promise.reject(e)}},t.addAdmin=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:u.addAdmin,method:"GET",data:{groupId:e,username:t}}))}catch(e){return Promise.reject(e)}},t.deleteAdmin=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:u.deleteAdmin,method:"GET",data:{groupId:e,username:t}}))}catch(e){return Promise.reject(e)}},t.dissolveGroup=function(e){try{return Promise.resolve(this.sdk.sendRequest({url:u.DissolveGroup,method:"GET",data:{groupId:e}}))}catch(e){return Promise.reject(e)}},t.pin=function(e,t,n){try{return Promise.resolve(this.sdk.sendRequest({url:u.pin,method:"GET",data:{groupId:e,messageId:t,type:n}}))}catch(e){return Promise.reject(e)}},t.muteGroup=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:u.muteGroup,method:"GET",data:{groupId:e,type:t}}))}catch(e){return Promise.reject(e)}},t.muteMember=function(e,t,n){try{return Promise.resolve(this.sdk.sendRequest({url:u.muteMember,method:"GET",data:{groupId:e,username:t,type:n}}))}catch(e){return Promise.reject(e)}},t.addGroupMembers=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.AddGroupMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getFileByType=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.GetFileByType,method:"GET"}))}catch(e){return Promise.reject(e)}},t.pinChat=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,type:t},url:u.PinChat,method:"GET"}))}catch(e){return Promise.reject(e)}},e}(),L=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.getContactByType=function(e,t){try{var n={contactType:e};return void 0!==t&&(n.groupId=t),Promise.resolve(this.sdk.sendRequest({data:n,url:u.GetContactByType,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getMemberContacts=function(e){try{return Promise.resolve(this.getContactByType(a.MEMBER,e))}catch(e){return Promise.reject(e)}},t.getColleagueContacts=function(e){try{return Promise.resolve(this.getContactByType(a.COLLEAGUE,e))}catch(e){return Promise.reject(e)}},t.getGroupContacts=function(e){try{return Promise.resolve(this.getContactByType(a.GROUP,e))}catch(e){return Promise.reject(e)}},t.editContactTag=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.EditContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getContactTag=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{contactType:e},url:u.GetContactTag,method:"GET"}))}catch(e){return Promise.reject(e)}},t.allocationContactTag=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:u.AllocationContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},t.allocationMemberTag=function(e,t,n){void 0===n&&(n=0);try{return Promise.resolve(this.allocationContactTag({contactType:a.MEMBER,tag:e,groupIds:t,type:n}))}catch(e){return Promise.reject(e)}},t.allocationColleagueTag=function(e,t,n){void 0===n&&(n=0);try{return Promise.resolve(this.allocationContactTag({contactType:a.COLLEAGUE,tag:e,groupIds:t,type:n}))}catch(e){return Promise.reject(e)}},t.allocationGroupTag=function(e,t,n){void 0===n&&(n=0);try{return Promise.resolve(this.allocationContactTag({contactType:a.GROUP,tag:e,groupIds:t,type:n}))}catch(e){return Promise.reject(e)}},e}(),U=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.services={},this.sdk=e}var t=e.prototype;return t.get=function(e){return this.services[e]||(this.services[e]=this.createService(e)),this.services[e]},t.createService=function(e){switch(e){case s.USER:return new k(this.sdk);case s.MESSAGE:return new R(this.sdk);case s.CONVERSATION:return new A(this.sdk);case s.GROUP:return new I(this.sdk);case s.CONTACT:return new L(this.sdk);default:throw new Error("Unknown service: "+e)}},t.reset=function(){this.services={}},e}();function N(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var _=[u.Logout,d.OnKickedOffline,d.OnUserTokenInvalid,d.OnUserTokenExpired],w=/*#__PURE__*/function(e){function t(t){var n;return void 0===t&&(t=!1),(n=e.call(this)||this).config={debug:!1,isLive:!1,useProtobuf:!1,protocol:f.SSE},n.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},n.cacheManager=void 0,n.connectionClient=void 0,n.serviceManager=void 0,n.lastUnauthorizedTime=0,n.UNAUTHORIZED_THROTTLE_MS=3e3,n.conversationUpdateTimer=null,n.CONVERSATION_UPDATE_THROTTLE_MS=500,n.pendingConversationUpdate=!1,n.lastConversationUpdateTime=0,n.isPageVisible=!0,n.pageVisibilityHandler=null,n.PAGE_HIDDEN_STOP_DELAY_MS=3e3,n.pageHiddenTimer=null,n.isActuallyHidden=!1,n.PAGE_VISIBLE_STABLE_MS=1e3,n.pageVisibleStableTimer=null,n.configure=function(e){void 0!==e.debug&&(n.config.debug=e.debug),e.isLive&&(n.config.isLive=e.isLive),e.apiAddr&&(n.config.apiAddr=e.apiAddr),e.wsAddr&&(n.config.wsAddr=e.wsAddr),e.ossApiAddr&&(n.config.ossApiAddr=e.ossApiAddr),e.appKey&&(n.config.appKey=e.appKey),e.token&&(n.config.token=e.token),e.connectTimeout&&(n.config.connectTimeout=e.connectTimeout),e.maxRetries&&(n.config.maxRetries=e.maxRetries),e.useProtobuf&&(n.config.useProtobuf=e.useProtobuf),e.protocol&&(n.config.protocol=e.protocol)},n.sendRequest=function(e){try{n.internalState.lastActivity=Date.now(),n.config.debug&&n.logRequest(e);var t=n.config.apiAddr+e.url,o=e.data;if("GET"===e.method&&o){var r=new URLSearchParams;Object.entries(o).forEach(function(e){var t=e[1];null!=t&&r.append(e[0],String(t))});var i=r.toString();i&&(t+=(t.includes("?")?"&":"?")+i),o=void 0}return Promise.resolve(N(function(){return Promise.resolve(function(e){try{var t,n=function(e){if(t)return e;throw new Error("Unsupported platform")},o=function(){if(C){var n=new Promise(function(t,n){uni.request({url:e.url,method:e.method||"GET",header:e.headers,data:e.data,success:function(e){401!==e.statusCode?t(e.data):n({status:401,message:"Unauthorized"})},fail:function(e){return n(e)}})});return t=1,n}return function(){if(b)return Promise.resolve(fetch(e.url,{method:e.method||"GET",headers:e.headers,body:e.data?JSON.stringify(e.data):null})).then(function(e){if(401===e.status)throw{status:401,message:"Unauthorized"};return Promise.resolve(e.json()).then(function(e){return t=1,e})})}()}();return Promise.resolve(o&&o.then?o.then(n):n(o))}catch(e){return Promise.reject(e)}}({url:t,method:e.method,headers:{"Content-Type":"application/json",Authorization:n.config.token?"Bearer "+n.config.token:""},data:o}))},function(e){throw 401!==(null==e?void 0:e.status)&&401!==(null==e?void 0:e.statusCode)||n.handleUnauthorizedWithThrottle(t),e}))}catch(e){return Promise.reject(e)}},n.handleUnauthorizedWithThrottle=function(e){var t=Date.now();t-n.lastUnauthorizedTime<n.UNAUTHORIZED_THROTTLE_MS?console.warn("401错误被节流限制,跳过处理:"+e):(n.lastUnauthorizedTime=t,n.handleUnauthorized(e))},n.handleUnauthorized=function(e){console.warn("未授权请求(401):",e),n.handleConnectionClosed(!0)},n.createRequestFunction=function(e,t){return function(o){return n.sendRequest({data:o,url:e,method:t})}},n.createRequestFunctionWithoutParams=function(e,t){return function(){return n.sendRequest({data:void 0,method:t,url:e})}},n.handleMessage=function(e){n.config.debug&&console.log("[SDK] handleMessage response",e),n.isProtobufFormat(e)?n.handleProtobufMessage(e):n.handleJsonMessage(e)},n.handleJsonMessage=function(e){switch(n.config.debug&&console.log("handleMessage response",e),e.ev){case h.EVENT_MESSAGE_PUSH:var t=e.dt;Array.isArray(t)?(t.forEach(function(e){n.updateMessageCache(e)}),n.emit(d.OnReceiveMessages,t)):console.warn("[SDK] Expected response.dt to be an array, but got:",t);break;case h.EVENT_PONG_IDLE:n.internalState.isConnected=!0;break;case h.EVENT_SYSTEM_MESSAGE_PUSH:n.emit(d.OnReceiveSystemMessage,e.dt);break;case h.EVENT_PRE_MESSAGE_PUSH:n.emit(d.OnReceivePreMessage,e.dt);break;case h.EVENT_SUBSCRIBE_MESSAGE_PUSH:n.emit(d.OnReceiveSubscribeMessage,e.dt);break;default:o=e.ev,Object.values(d).includes(o)?(n.emit(e.ev,e.dt),_.includes(e.ev)&&(n.internalState.isLoggedIn=!1,n.internalState.isConnected=!1,n.connectionClient&&(n.connectionClient.close(),n.connectionClient=void 0))):n.config.debug&&console.warn("[SDK] Unknown SSE event type:",e.ev)}var o},n.handleReconnectSuccess=function(){n.config.username&&(n.internalState.isConnected=!0,n.internalState.reconnectAttempts=0,n.config.debug&&console.log("SSE reconnection successful"),n.emit(d.OnReconnected))},n.handleConnectionClosed=function(e){n.internalState.isConnected=!1,n.config.debug&&console.log("SSE connection closed"),n.emit(d.OnDisconnected,e)},n.handleMaxRetriesReached=function(){n.config.debug&&console.log("SSE connection max reconnection attempts reached"),n.emit(d.onMaxRetriesReached)},n.handleConnectionChange=function(e){n.config.debug&&console.log("Connection status changed:",e),n.emit(e?d.OnConnected:d.OnDisconnected)},n.login=function(e){try{var t,r,i=function(o){return t?o:(n.connectionClient=G.createClient({url:n.config.wsAddr+"/"+(e.anonLogin?"anonymousConn":"conn")+"?username="+e.username+"&token="+e.token+"&appKey="+n.config.appKey+"&random="+r,protocol:n.config.protocol||f.WEBSOCKET,debug:n.config.debug,onMessage:n.handleMessage,onReconnectSuccess:n.handleReconnectSuccess,onConnectionClosed:n.handleConnectionClosed,onMaxRetriesReached:n.handleMaxRetriesReached,onConnectionChange:n.handleConnectionChange,token:e.token,connectTimeout:n.config.connectTimeout,maxRetries:n.config.maxRetries}),N(function(){return Promise.resolve(n.connectionClient.connect()).then(function(e){return n.internalState.isLoggedIn=!0,n.internalState.isConnected=!0,n.config.isLive||n.initializeConversationCache(),e})},function(e){return n.internalState.isLoggedIn=!1,n.internalState.isConnected=!1,Promise.reject(e.message)}))};if(n.connectionClient&&(null==n.connectionClient.close||n.connectionClient.close(),n.connectionClient=void 0,n.internalState.isLoggedIn=!1,n.internalState.isConnected=!1),!n.config.apiAddr)return Promise.reject("No apiAddr configured. Please call configure() before login().");if(!n.config.ossApiAddr)return Promise.reject("No ossApiAddr configured. Please call configure() before login().");if(!n.config.appKey)return Promise.reject("No appKey configured. Please call configure() before login().");if(!n.config.token)return Promise.reject("No token configured. Please call configure() before login().");if(n.config.username=e.username,n.config.anonLogin=e.anonLogin||!1,e.protocol&&(n.config.protocol=e.protocol),e.protocol==f.WEBSOCKET&&!n.config.wsAddr)return Promise.reject("WebSocket address (wsAddr) is not configured. Please call configure() before login().");if(n.config.debug&&(console.log("login params",e),console.log("apiAddr",n.config.apiAddr)),!n.config.isLive||!e.anonLogin){n.cacheManager.initialize(e.username),n.cacheManager.resetActiveConversation();var s=n.cacheManager.getConversations();s.length>0&&n.emit(d.OnConversationListUpdated,s)}var a=function(){if(!e.anonLogin)return Promise.resolve(n.user.login(o({},e,{appKey:n.config.appKey}))).then(function(e){var n=e.code,o=e.data;if(0!=n){var i=Promise.resolve("Login failed, Server error, error code is "+n);return t=1,i}r=o})}();return Promise.resolve(a&&a.then?a.then(i):i(a))}catch(e){return Promise.reject(e)}},n.logout=function(){try{return n.connectionClient&&(n.connectionClient.close(),n.connectionClient=void 0),Promise.resolve(n.user.logout()).then(function(e){return n.internalState.isLoggedIn=!1,n.internalState.isConnected=!1,n.config.username=void 0,n.config.token=void 0,n.cacheManager.clear(),e})}catch(e){return Promise.reject(e)}},n.getChatMember=function(e,t){return n.user.getChatMember(e,t)},n.getConversations=function(e){try{return Promise.resolve(N(function(){var t=e.pageNo||1,o=e.pageSize||50;return t<1?(console.warn("[SDK] Invalid pageNo, must be >= 1"),{code:-1,msg:"Invalid pageNo, must be >= 1",data:{records:[],current:1,pages:0}}):o<1||o>100?(console.warn("[SDK] Invalid pageSize, must be between 1 and 100"),{code:-1,msg:"Invalid pageSize, must be between 1 and 100",data:{records:[],current:1,pages:0}}):Promise.resolve(n.conversation.getConversations({pageNo:t,pageSize:o})).then(function(e){var o=e.data;if(0===e.code&&o){var r=n.cacheManager.getConversations();if(1===t)n.cacheManager.setConversations([].concat(o.records),!0);else{var i=o.records||[],s=new Map;r.forEach(function(e){s.set(e.id,e)});var a=[],c=[];i.forEach(function(e){s.has(e.id)?a.push(e):c.push(e)});var u=[];r.forEach(function(e){a.find(function(t){return t.id===e.id})||u.push(e)}),u.push.apply(u,a.concat(c)),n.cacheManager.setConversations(u,!1)}n.emit(d.OnConversationListUpdated,n.cacheManager.getConversations())}else{var l=n.cacheManager.getConversations();l.length>0&&n.emit(d.OnConversationListUpdated,l)}return e})},function(t){console.error("[SDK] Failed to get conversations:",t);var o=n.cacheManager.getConversations();return o.length>0&&n.emit(d.OnConversationListUpdated,o),{code:-1,msg:t instanceof Error?t.message:"Failed to get conversations",data:{records:o,current:e.pageNo||1,pages:0}}}))}catch(e){return Promise.reject(e)}},n.internalUploadFile=function(e,t){try{return Promise.resolve(N(function(){var o=new FormData;return o.append("file",e),o.append("filename",e.name),o.append("groupId",t.toString()),Promise.resolve(fetch(""+n.config.ossApiAddr+u.UploadFile,{method:"POST",headers:{Authorization:n.config.token?"Bearer "+n.config.token:""},body:o})).then(function(e){if(!e.ok)throw new Error("Upload failed with status: "+e.status);return Promise.resolve(e.json()).then(function(e){var t=(null==e?void 0:e.data)||{};return{originalUrl:t.originalUrl||"",thumbnailUrl:t.thumbnailUrl||""}})})},function(e){return console.error("[Upload Error]",e),{error:e instanceof Error?e:new Error("Unknown upload error")}}))}catch(e){return Promise.reject(e)}},n.uploadFile=function(e,t){var o=e.file;try{return Promise.resolve(n.internalUploadFile(o,t)).then(function(e){var t,n=e.originalUrl,o=e.thumbnailUrl,r=e.error;return{data:{originalUrl:void 0===n?"":n,thumbnailUrl:void 0===o?"":o},msg:null!=(t=null==r?void 0:r.message)?t:"",code:r?c.UnknownError:0}})}catch(e){return Promise.reject(e)}},n.sendTextMessage=function(e,t,o,r){return n.message.createTextMessage(e,t,o,r)},n.sendImageMessage=function(e,t,o,r,i){return n.message.createImageMessage(e,t,o,r,i)},n.sendFileMessage=function(e,t,o,r){return n.message.createFileMessage(e,t,o,r)},n.sendAudioMessage=function(e,t,o,r){return n.message.createAudioMessage(e,t,o,r)},n.sendVideoMessage=function(e,t,o,r){return n.message.createVideoMessage(e,t,o,r)},n.sendLinkMessage=function(e,t,o,r){return n.message.createLinkMessage(e,t,o,r)},n.sendGifMessage=function(e,t,o,r){return n.message.createGifMessage(e,t,o,r)},n.sendOptionMessage=function(e,t,o,r){return n.message.createOptionMessage(e,t,o,r)},n.sendEmojiMessage=function(e,t,o,r){return n.message.createEmojiMessage(e,t,o,r)},n.sendCustomMessage=function(e,t,o,r){return n.message.createCustomMessage(e,t,o,r)},n.getHistoryMessageList=function(e){try{return Promise.resolve(n.message.getHistoryMessageList(e))}catch(e){return Promise.reject(e)}},n.getLiveMessageList=function(e){return n.message.getLiveMessageList(e)},n.prePushCustomerMessage=function(e){return n.message.prePushCustomerMessage(e)},n.getGroupInfo=function(e){return n.group.getGroupInfo(e)},n.getGroupMembers=function(e){return n.group.getGroupMembers(e)},n.joinGroup=function(e){return n.group.joinGroup(e)},n.leftGroup=function(e){return n.group.leftGroup(e)},n.checkGroupBlock=function(e){return n.group.checkGroupBlock(e)},n.getMyGroupPermission=function(e){return n.group.getMyGroupPermission(e)},n.getGroupPermission=function(e){return n.group.getGroupPermission(e)},n.getGroupMember=function(e){return n.group.getGroupMember(e)},n.getGroupMemberPermission=function(e,t){return n.group.getGroupMemberPermission(e,t)},n.updateGroupPermission=function(e){return n.group.updateGroupPermission(e)},n.kickGroupMember=function(e){return n.group.kickGroupMember(e)},n.muteMembers=function(e){return n.group.muteMembers(e)},n.updateGroupMemberPermission=function(e){return n.group.updateGroupMemberPermission(e)},n.editGroupName=function(e,t,o){try{return Promise.resolve(n.group.editGroupName(e,t,o)).then(function(r){if(0===r.code){var i=n.cacheManager.getConversations().find(function(t){return t.id===e});if(i){i.name=t,i.avatar=o,n.cacheManager.updateConversation(i);var s=n.cacheManager.getConversations();n.emit(d.OnConversationListUpdated,s)}}return r})}catch(e){return Promise.reject(e)}},n.editNotification=function(e,t){return n.group.editNotification(e,t)},n.editGroupCustomer=function(e,t){return n.group.editGroupCustomer(e,t)},n.addAdmin=function(e,t){return n.group.addAdmin(e,t)},n.deleteAdmin=function(e,t){return n.group.deleteAdmin(e,t)},n.pin=function(e,t,o){return n.group.pin(e,t,o)},n.muteGroup=function(e,t){return n.group.muteGroup(e,t)},n.muteMember=function(e,t,o){return n.group.muteMember(e,t,o)},n.addGroupMembers=function(e){return n.group.addGroupMembers(e)},n.getFileByType=function(e){return n.group.getFileByType(e)},n.pinChat=function(e,t){return n.group.pinChat(e,t)},n.dissolveGroup=function(e){return n.group.dissolveGroup(e)},n.markConversationRead=function(e){try{return Promise.resolve(n.conversation.markConversationRead(e)).then(function(t){if(0===t.code&&e.groupId){e.id?n.cacheManager.updateConversationLastRead(e.groupId,e.id):n.cacheManager.clearConversationUnread(e.groupId);var o=n.cacheManager.getConversations();n.emit(d.OnConversationListUpdated,o)}return t})}catch(e){return Promise.reject(e)}},n.markLastRead=function(e,t){try{return Promise.resolve(n.conversation.markLastRead(e,t)).then(function(o){if(0===o.code){n.cacheManager.updateConversationLastRead(e,t);var r=n.cacheManager.getConversations();n.emit(d.OnConversationListUpdated,r)}return o})}catch(e){return Promise.reject(e)}},n.markLastReadLocal=function(e,t){n.cacheManager.updateConversationLastRead(e,t);var o=n.cacheManager.getConversations();n.emit(d.OnConversationListUpdated,o)},n.pinConversation=function(e,t){void 0===t&&(t=1);try{return Promise.resolve(n.conversation.pinConversation(e,t)).then(function(o){if(0===o.code){n.cacheManager.updateConversationPinStatus(e,1===t);var r=n.cacheManager.getConversations();n.emit(d.OnConversationListUpdated,r)}return o})}catch(e){return Promise.reject(e)}},n.muteConversation=function(e,t){return void 0===t&&(t=1),n.conversation.muteConversation(e,t)},n.getChannels=function(e){return n.conversation.getChannels(e)},n.clearConversationUnread=function(e){n.cacheManager.clearConversationUnread(e);var t=n.cacheManager.getConversations();n.emit(d.OnConversationListUpdated,t)},n.clearAllConversationUnread=function(){n.cacheManager.clearAllConversationUnread();var e=n.cacheManager.getConversations();n.emit(d.OnConversationListUpdated,e)},n.getContactByType=function(e,t){return n.contact.getContactByType(e,t)},n.getMemberContacts=function(e){return n.contact.getMemberContacts(e)},n.getColleagueContacts=function(e){return n.contact.getColleagueContacts(e)},n.getGroupContacts=function(e){return n.contact.getGroupContacts(e)},n.editContactTag=function(e){return n.contact.editContactTag(e)},n.getContactTag=function(e){return n.contact.getContactTag(e)},n.allocationContactTag=function(e){return n.contact.allocationContactTag(e)},n.allocationMemberTag=function(e,t,o){return void 0===o&&(o=0),n.contact.allocationMemberTag(e,t,o)},n.allocationColleagueTag=function(e,t,o){return void 0===o&&(o=0),n.contact.allocationColleagueTag(e,t,o)},n.allocationGroupTag=function(e,t,o){return void 0===o&&(o=0),n.contact.allocationGroupTag(e,t,o)},n.config.debug=t,t&&(console.log("🚀 SIM SDK Web v1.1.0 (本地开发版本)"),console.log("📦 支持协议: SSE, WebSocket")),n.cacheManager=new E({persistEnabled:!0,debug:t}),n.serviceManager=new U(n),n.initPageVisibilityDetection(),n}var n,a;a=e,(n=t).prototype=Object.create(a.prototype),n.prototype.constructor=n,r(n,a);var l,g,m=t.prototype;return m.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.isActuallyHidden=!this.isPageVisible,this.pageVisibilityHandler=function(){var t=e.isPageVisible;e.isPageVisible=!document.hidden,e.config.debug&&console.log("[SDK] Page visibility changed: "+(e.isPageVisible?"visible":"hidden")),t&&!e.isPageVisible?e.handlePageHidden():!t&&e.isPageVisible&&e.handlePageVisible()},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},m.handlePageHidden=function(){var e=this;null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.pageHiddenTimer=window.setTimeout(function(){e.isPageVisible||(e.isActuallyHidden=!0,e.config.debug&&console.log("[SDK] Page is actually hidden, stopping conversation updates")),e.pageHiddenTimer=null},this.PAGE_HIDDEN_STOP_DELAY_MS)},m.handlePageVisible=function(){var e=this;null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.isActuallyHidden=!1,null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),this.pageVisibleStableTimer=window.setTimeout(function(){e.isPageVisible&&e.pendingConversationUpdate&&(e.config.debug&&console.log("[SDK] Page is stable visible, triggering conversation update"),e.flushConversationUpdate()),e.pageVisibleStableTimer=null},this.PAGE_VISIBLE_STABLE_MS)},m.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null)},m.destroy=function(){this.connectionClient&&(this.connectionClient.close(),this.connectionClient=void 0),this.cacheManager.destroy(),this.cleanupPageVisibilityDetection(),null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},this.config.debug&&console.log("[SDK] Resources destroyed")},m.getService=function(e){return this.serviceManager.get(e)},m.isConnected=function(){return this.config.debug&&console.log("[SDK] Connection status: "+(this.internalState.isConnected?"connected":"disconnected")),this.internalState.isConnected},m.isLoggedIn=function(){return this.config.debug&&console.log("[SDK] Login status: "+(this.internalState.isLoggedIn?"logged in":"not logged in")),this.internalState.isLoggedIn},m.logRequest=function(e){var t=Math.random().toString(36).substring(2,8),n={GET:"#4CAF50",POST:"#2196F3",PUT:"#FF9800",DELETE:"#F44336"}[e.method]||"#9C27B0",o={GET:"🔍",POST:"📝",PUT:"🔄",DELETE:"🗑️"}[e.method]||"📡";console.log("%c "+(new Date).toISOString().substring(11,19)+" %c SDK %c "+o+" "+e.method+" %c "+e.url+" %c #"+t,"color: #888; font-size: 11px; padding: 2px 0;","background: #7CAEFF; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","background: "+n+"; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","color: #0066cc; font-weight: bold;","color: #888; font-style: italic;"),e.data&&Object.keys(e.data).length>0&&(console.log("%c─── 📦 Request Payload ───────────────────────────────","color: #999; font-style: italic;"),console.log("%c%s","color: #333; background: #f8f8f8; padding: 8px; border-radius: 4px; border-left: 4px solid #7CAEFF; font-family: monospace; line-height: 1.5;",JSON.stringify(e.data,null,2)),console.log("%c─────────────────────────────────────────────────────","color: #999;"))},m.handlePongMessage=function(e){e&&e.timestamp&&(this.config.debug&&console.log("[SDK] Received pong message with timestamp:",e.timestamp),this.internalState.isConnected=!0,this.internalState.lastActivity=Date.now())},m.isProtobufFormat=function(e){return this.config.useProtobuf||"string"==typeof e&&this.isBase64String(e)||e instanceof Uint8Array},m.isBase64String=function(e){try{return btoa(atob(e))===e}catch(e){return!1}},m.handleProtobufMessage=function(e){this.emit(d.OnReceiveProtoMessage,e)},m.initializeConversationCache=function(){try{var e=this,t=N(function(){return Promise.resolve(e.conversation.getConversations({pageNo:1,pageSize:50})).then(function(t){var n=t.code,o=t.data;if(e.config.debug&&console.log("[SDK] Initialize conversation cache:",n,o),0===n&&o&&o.records){e.cacheManager.setConversations(o.records,!0);var r=e.cacheManager.getConversations();e.emit(d.OnConversationListUpdated,r),e.config.debug&&console.log("[SDK] Conversation cache initialized with",o.records.length,"conversations")}})},function(e){console.error("[SDK] Failed to initialize conversation cache:",e)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},m.onMessage=function(e){var t=this;return this.on(d.OnReceiveMessage,e),function(){return t.off(d.OnReceiveMessage,e)}},m.onMessages=function(e){var t=this;return this.on(d.OnReceiveMessages,e),function(){return t.off(d.OnReceiveMessages,e)}},m.onConnectionChange=function(e){var t=this,n=function(){return e(!0)},o=function(){return e(!1)};return this.on(d.OnConnected,n),this.on(d.OnDisconnected,o),function(){t.off(d.OnConnected,n),t.off(d.OnDisconnected,o)}},m.onKickedOffline=function(e){var t=this;return this.on(d.OnKickedOffline,e),function(){return t.off(d.OnKickedOffline,e)}},m.updateMessageCache=function(e){e.groupId&&this.cacheManager.addGroupMessage(e),this.cacheManager.updateConversationWithMessage(e,this.config.username)&&this.scheduleConversationUpdate()},m.scheduleConversationUpdate=function(){var e=this;if(this.pendingConversationUpdate=!0,this.isActuallyHidden)this.config.debug&&console.log("[SDK] Page is actually hidden, deferring conversation update");else{var t=Date.now()-this.lastConversationUpdateTime;if(t<this.CONVERSATION_UPDATE_THROTTLE_MS){if(null!==this.conversationUpdateTimer)return;this.conversationUpdateTimer=window.setTimeout(function(){e.flushConversationUpdate()},this.CONVERSATION_UPDATE_THROTTLE_MS-t)}else this.flushConversationUpdate()}},m.flushConversationUpdate=function(){null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.pendingConversationUpdate=!1,this.lastConversationUpdateTime=Date.now();var e=this.cacheManager.getConversations();this.emit(d.OnConversationListUpdated,e),this.config.debug&&console.log("[SDK] Conversation list updated, count:",e.length)},m.getCachedGroupMessages=function(e){return this.cacheManager.getGroupMessages(e)},l=t,(g=[{key:"message",get:function(){return this.getService(s.MESSAGE)}},{key:"conversation",get:function(){return this.getService(s.CONVERSATION)}},{key:"group",get:function(){return this.getService(s.GROUP)}},{key:"user",get:function(){return this.getService(s.USER)}},{key:"contact",get:function(){return this.getService(s.CONTACT)}},{key:"username",get:function(){return this.config.username}},{key:"getConfig",get:function(){return this.config}},{key:"getConnectionClient",get:function(){return this.connectionClient}},{key:"uuid",get:function(){return(36*Math.random()).toString(36).slice(2)+(new Date).getTime().toString()}}])&&function(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,i(o.key),o)}}(l.prototype,g),Object.defineProperty(l,"prototype",{writable:!1}),l}(v);export{d as CbEvents,f as ConnectionProtocol,a as ContactType,c as ErrorCode,m as GroupMemberEventType,l as GroupType,g as MessageType,u as RequestApi,w as SIMSDK,s as ServiceName,h as SseEventType,p as SystemMessageType};
1
+ import{EventSourcePolyfill as e}from"event-source-polyfill";import t from"protobufjs";function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function o(e,t){var o="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(o)return(o=o.call(e)).next.bind(o);if(Array.isArray(e)||(o=function(e,t){if(e){if("string"==typeof e)return n(e,t);var o={}.toString.call(e).slice(8,-1);return"Object"===o&&e.constructor&&(o=e.constructor.name),"Map"===o||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?n(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){o&&(e=o);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function r(){return r=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},r.apply(null,arguments)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function s(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var a,c,u,d,l;!function(e){e.MESSAGE="message",e.CONVERSATION="conversation",e.GROUP="group",e.USER="user",e.CONTACT="contact"}(a||(a={})),function(e){e[e.MEMBER=0]="MEMBER",e[e.COLLEAGUE=1]="COLLEAGUE",e[e.GROUP=2]="GROUP"}(c||(c={})),function(e){e[e.UnknownError=10005]="UnknownError"}(u||(u={})),function(e){e.Login="/chat/member/login",e.Logout="/chat/member/logout",e.GetChatMember="/chat/member/getChatMember",e.GetGroupInfo="/chat/group/groupInfo",e.GetGroupMembers="/chat/group/groupMembers",e.JoinGroup="/chat/group/joinGroup",e.LeftGroup="/chat/group/leftGroup",e.AnonymousJoinGroup="/chat/group/anonymousJoinGroup",e.AnonymousLeftGroup="/chat/group/anonymousLeftGroup",e.CheckGroupBlock="/chat/group/checkBlock",e.GetMyGroupPermission="/chat/group/permission/getPermission",e.GetGroupPermission="/chat/group/permission/groupPermission",e.GetGroupMember="/chat/group/groupMember",e.GetGroupMemberPermission="/chat/group/permission/groupMemberPermission",e.UpdateGroupPermission="/chat/group/permission/updateGroupPermission",e.UpdateGroupMemberPermission="/chat/group/permission/updateGroupMemberPermission",e.editeGroupName="/chat/group/operation/editeGroupName",e.editeNotification="/chat/group/operation/editeNotification",e.editeGroupCustomer="/chat/group/operation/editeGroupCustomer",e.addAdmin="/chat/group/operation/addAdmin",e.deleteAdmin="/chat/group/operation/deleteAdmin",e.pin="/chat/group/operation/pin",e.muteGroup="/chat/group/operation/muteGroup",e.muteMember="/chat/group/operation/muteMember",e.kickGroupMember="/chat/group/operation/kickGroupMember",e.muteMembers="/chat/group/operation/muteMembers",e.DissolveGroup="/chat/group/dissolve",e.GetAllConversationList="/chat/conversation/conversationList",e.GetChannels="/chat/conversation/getChannels",e.MarkConversationMessageAsRead="/chat/conversation/lastRead",e.PinConversation="/chat/conversation/pinChat",e.MuteConversation="/chat/conversation/mute",e.UpdateLatestMessage="/chat/group/updateLatestMessage",e.GetLatestGroupChats="/chat/group/latestGroupChats",e.CheckLatestMessages="/chat/group/checkLatestMessages",e.CreateTextMessage="/chat/message/push",e.PushMessageToMember="/chat/message/push2Member",e.PushPrivateMessage="/chat/message/pushPrivateMessage",e.PushLiveMessage="/chat/message/liveGroupPush",e.GetHistoryMessageList="/chat/message/pull",e.GetLiveMessageList="/chat/message/liveGroupPull",e.GetAnonymousLiveMessageList="/chat/message/anonymousLiveGroupPull",e.PrePushCustomerMessage="/chat/message/prePushCustomerMessage",e.UploadFile="/chat/img/upload",e.UploadCredential="/chat/img/uploadCredential",e.GetContactByType="/chat/contact/contactByType",e.EditContactTag="/chat/contact/editeContactTag",e.GetContactTag="/chat/contact/getContactTag",e.AllocationContactTag="/chat/contact/allocationContactTag",e.AddGroupMembers="/chat/group/operation/addGroupMembers",e.GetFileByType="/chat/message/getFileByType",e.PinChat="/chat/member/pinChat"}(d||(d={})),function(e){e.OnConnected="OnConnected",e.OnDisconnected="OnDisconnected",e.onMaxRetriesReached="onMaxRetriesReached",e.OnReconnecting="OnReconnecting",e.OnReconnected="OnReconnected",e.OnReconnectFailed="OnReconnectFailed",e.OnNetworkChange="OnNetworkChange",e.OnReceiveMessage="OnReceiveMessage",e.OnReceiveProtoMessage="OnReceiveProtoMessage",e.OnReceiveMessages="OnReceiveMessages",e.OnReceiveSubscribeMessage="OnReceiveSubscribeMessage",e.OnReceiveSystemMessage="OnReceiveSystemMessage",e.OnReceivePreMessage="OnReceivePreMessage",e.OnMessagesListLoaded="OnMessagesListLoaded",e.OnActiveConversationSync="OnActiveConversationSync",e.OnMessageSent="OnMessageSent",e.OnMessageFailed="OnMessageFailed",e.OnMessageRevoked="OnMessageRevoked",e.OnMessageDeleted="OnMessageDeleted",e.OnMessageRead="OnMessageRead",e.OnTypingStatusUpdate="OnTypingStatusUpdate",e.OnUserStatusChange="OnUserStatusChange",e.OnKickedOffline="OnKickedOffline",e.OnUserTokenInvalid="OnUserTokenInvalid",e.OnUserTokenExpired="OnUserTokenExpired",e.OnForceOffline="OnForceOffline",e.OnUserInfoUpdated="OnUserInfoUpdated",e.OnGroupCreated="OnGroupCreated",e.OnGroupInfoUpdated="OnGroupInfoUpdated",e.OnGroupDissolved="OnGroupDissolved",e.OnJoinGroup="OnJoinGroup",e.OnLeaveGroup="OnLeaveGroup",e.OnGroupMemberJoined="OnGroupMemberJoined",e.OnGroupMemberLeft="OnGroupMemberLeft",e.OnGroupMemberKicked="OnGroupMemberKicked",e.OnGroupOwnerChanged="OnGroupOwnerChanged",e.OnGroupAdminAdded="OnGroupAdminAdded",e.OnGroupAdminRemoved="OnGroupAdminRemoved",e.OnGroupMemberMuted="OnGroupMemberMuted",e.OnGroupMemberUnmuted="OnGroupMemberUnmuted",e.OnGroupAllMemberMuted="OnGroupAllMemberMuted",e.OnGroupAllMemberUnmuted="OnGroupAllMemberUnmuted",e.OnConversationCreated="OnConversationCreated",e.OnConversationDeleted="OnConversationDeleted",e.OnConversationListUpdated="OnConversationListUpdated",e.OnConversationUpdated="OnConversationUpdated",e.OnUnreadCountChanged="OnUnreadCountChanged",e.OnConversationPinned="OnConversationPinned",e.OnConversationUnpinned="OnConversationUnpinned",e.OnConversationMuted="OnConversationMuted",e.OnConversationUnmuted="OnConversationUnmuted",e.OnPongConn="OnPongConn",e.OnPongReConn="OnPongReConn",e.OnPongIdle="OnPongIdle",e.OnError="OnError",e.OnWarning="OnWarning",e.OnLog="OnLog"}(l||(l={}));var g,h,m,p,f,v,C=/*#__PURE__*/function(){function e(){var e;this.events=((e={})[l.OnReceiveMessage]=[],e[l.OnReceiveSystemMessage]=[],e[l.OnReceiveMessages]=[],e[l.OnConversationListUpdated]=[],e[l.OnMessagesListLoaded]=[],e[l.OnActiveConversationSync]=[],e[l.OnConnected]=[],e[l.OnDisconnected]=[],e[l.OnReconnected]=[],e)}var t=e.prototype;return t.emit=function(e,t){var n=this.events[e];return n&&n.forEach(function(e){return e(t)}),this},t.on=function(e,t){var n;return this.events[e]||(this.events[e]=[]),null==(n=this.events[e])||n.push(t),this},t.off=function(e,t){var n=this.events[e];if(n){var o=n.indexOf(t);o>-1&&(n.splice(o,1),0===n.length&&delete this.events[e])}return this},e}();!function(e){e[e.PrivateChat=0]="PrivateChat",e[e.PrivateGroup=1]="PrivateGroup",e[e.PublicGroup=2]="PublicGroup",e[e.CustomerService=3]="CustomerService",e[e.LiveGroup=4]="LiveGroup",e[e.ChanneRoom=5]="ChanneRoom"}(g||(g={})),function(e){e[e.TEXT=0]="TEXT",e[e.IMAGE=1]="IMAGE",e[e.FILE=2]="FILE",e[e.AUDIO=3]="AUDIO",e[e.VIDEO=4]="VIDEO",e[e.LINK=5]="LINK",e[e.GIF=6]="GIF",e[e.OPTION=7]="OPTION",e[e.EMOJI=8]="EMOJI",e[e.CUSTOM=100]="CUSTOM"}(h||(h={})),function(e){e[e.EVENT_PONG_CONN=0]="EVENT_PONG_CONN",e[e.EVENT_PONG_RE_CONN=1]="EVENT_PONG_RE_CONN",e[e.EVENT_PONG_IDLE=2]="EVENT_PONG_IDLE",e[e.EVENT_MESSAGE_PUSH=3]="EVENT_MESSAGE_PUSH",e[e.EVENT_SYSTEM_MESSAGE_PUSH=4]="EVENT_SYSTEM_MESSAGE_PUSH",e[e.EVENT_LIVE_SYSTEM_MESSAGE_PUSH=5]="EVENT_LIVE_SYSTEM_MESSAGE_PUSH",e[e.EVENT_PRE_MESSAGE_PUSH=6]="EVENT_PRE_MESSAGE_PUSH",e[e.EVENT_SUBSCRIBE_MESSAGE_PUSH=7]="EVENT_SUBSCRIBE_MESSAGE_PUSH"}(m||(m={})),function(e){e[e.JOIN=0]="JOIN",e[e.LEFT=1]="LEFT",e[e.LAST_READ_UPDATE=2]="LAST_READ_UPDATE",e[e.PERMISSION_UPDATE=3]="PERMISSION_UPDATE",e[e.IDENTITY_UPDATE=4]="IDENTITY_UPDATE",e[e.PING_UPDATE=5]="PING_UPDATE"}(p||(p={})),function(e){e[e.GroupMemberPermissionChange=3]="GroupMemberPermissionChange",e[e.GroupPermissionChange=4]="GroupPermissionChange"}(f||(f={})),function(e){e.SSE="sse",e.WEBSOCKET="websocket"}(v||(v={}));var S="undefined"!=typeof uni,b="undefined"!=typeof window,E="simsdk_",M={CONVERSATIONS:E+"conversations",GROUP_MESSAGES:E+"group_messages",USER_INFO:E+"user_info",META_INFO:E+"meta"},T={MAX_CONVERSATIONS:100,MAX_GROUP_MESSAGES:200,STORAGE_CHUNK_SIZE:512e3,CACHE_TTL:6048e5,EXPIRY_CHECK_INTERVAL:18e5},P=/*#__PURE__*/function(){function e(e){var t=void 0===e?{}:e,n=t.persistEnabled,o=void 0===n||n,i=t.debug,s=void 0!==i&&i,a=t.config,c=void 0===a?{}:a;this.conversationCache=[],this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder=new Map,this.userInfo={},this.currentUsername=void 0,this.activeConversation=void 0,this.metaInfo={},this.persistEnabled=void 0,this.debug=void 0,this.config=void 0,this.cleanupTimer=void 0,this.persistEnabled=o,this.debug=s,this.config=r({},T,c)}var t=e.prototype;return t.initialize=function(e){this.currentUsername&&this.currentUsername!==e&&(this.debug&&console.log("User switched from "+this.currentUsername+" to "+e+", clearing cache"),this.clear()),this.currentUsername=e,this.userInfo.username=e,this.persistEnabled&&this.loadFromStorage(),this.setupCleanupInterval(),this.debug&&(console.log("Cache initialized for user:",e),console.log("Loaded conversations:",this.conversationCache.length),console.log("Loaded group messages for groups:",Object.keys(this.groupMessageCache).length))},t.clear=function(){this.conversationCache=[],this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder.clear(),this.persistEnabled&&this.clearCurrentUserStorage(),this.debug&&console.log("Cache cleared")},t.clearCurrentUserStorage=function(){try{if(!this.currentUsername)return void this.clearStorage();var e=this.getUserStorageKey(M.CONVERSATIONS);localStorage.removeItem(e);var t=this.getUserStorageKey(M.USER_INFO);localStorage.removeItem(t);for(var n,r=o(Object.keys(localStorage).filter(function(e){return e.startsWith(M.GROUP_MESSAGES+".")}));!(n=r()).done;)localStorage.removeItem(n.value)}catch(e){console.error("Failed to clear current user storage:",e)}},t.getConversations=function(){return[].concat(this.conversationCache)},t.clearConversationUnread=function(e){var t=this.conversationCache.find(function(t){return t.id===e});t&&(t.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.updateConversationLastRead=function(e,t){var n=this.conversationCache.find(function(t){return t.id===e});n&&(n.lastRead=t,n.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.clearAllConversationUnread=function(){this.conversationCache.forEach(function(e){e.unreadCount>0&&(e.unreadCount=0)}),this.persistEnabled&&this.saveConversationsToStorage()},t.getActiveConversation=function(){return this.activeConversation},t.setConversations=function(e,t){var n=this;if(void 0===t&&(t=!1),this.conversationCache=e.length>this.config.MAX_CONVERSATIONS?e.slice(0,this.config.MAX_CONVERSATIONS):[].concat(e),t)this.pinnedConversationOrder.clear(),this.conversationCache.forEach(function(e,t){e.pin&&n.pinnedConversationOrder.set(e.id,t)});else{var o=-1;this.pinnedConversationOrder.forEach(function(e){e>o&&(o=e)}),this.conversationCache.forEach(function(e,t){e.pin&&!n.pinnedConversationOrder.has(e.id)&&n.pinnedConversationOrder.set(e.id,o+t+1)})}this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversation=function(e){var t=this.conversationCache.findIndex(function(t){return t.id===e.id});t>=0?this.conversationCache[t]=r({},e):(this.conversationCache.push(r({},e)),this.conversationCache.length>this.config.MAX_CONVERSATIONS&&this.enforceConversationLimit()),this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversationPinStatus=function(e,t){var n=this.conversationCache.findIndex(function(t){return t.id===e});if(-1!==n){var o=this.conversationCache[n],r=!0===o.pin;if(o.pin=t,t&&!r){var i=-1;this.pinnedConversationOrder.forEach(function(e){e>i&&(i=e)}),this.pinnedConversationOrder.set(e,i+1)}else!t&&r&&this.pinnedConversationOrder.delete(e);this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()}},t.updateConversationWithMessage=function(e,t){var n,o=e.groupId;if(!o)return!1;var r=this.conversationCache.findIndex(function(e){return e.id===o});if(-1===r)return!1;var i=this.conversationCache[r],s=(null==(n=i.latest)?void 0:n.msgId)||0;return this.activeConversation&&this.activeConversation.id===o?(i.unreadCount=0,i.lastRead=e.msgId):t!==e.username&&(i.unreadCount+=e.msgId>s?e.msgId-s:1),i.latest=e,this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage(),!0},t.getGroupMessages=function(e){return this.recordAccess(e),!this.groupMessageCache[e]&&this.persistEnabled&&this.loadGroupMessagesFromStorage(e),this.groupMessageCache[e]||[]},t.addGroupMessage=function(e){if(e.groupId){this.recordAccess(e.groupId),this.groupMessageCache[e.groupId]||(this.groupMessageCache[e.groupId]=[]);var t=this.groupMessageCache[e.groupId].findIndex(function(t){return t.msgId===e.msgId});t>=0?this.groupMessageCache[e.groupId][t]=e:this.groupMessageCache[e.groupId].push(e),this.sortGroupMessages(e.groupId),this.limitGroupMessageCache(e.groupId),this.enforceMemoryLimits(),this.persistEnabled&&this.saveGroupMessagesToStorage(e.groupId)}},t.addGroupMessages=function(e){for(var t,n=this,r={},i=o(e);!(t=i()).done;){var s=t.value;s.groupId&&(r[s.groupId]||(r[s.groupId]=[]),r[s.groupId].push(s))}for(var a=0,c=Object.entries(r);a<c.length;a++){var u=c[a],d=u[0],l=u[1];this.recordAccess(Number(d)),this.groupMessageCache[d]||(this.groupMessageCache[d]=[]);for(var g,h=function(){var e=g.value,t=n.groupMessageCache[d].findIndex(function(t){return t.msgId===e.msgId});t>=0?n.groupMessageCache[d][t]=e:n.groupMessageCache[d].push(e)},m=o(l);!(g=m()).done;)h();this.sortGroupMessages(Number(d)),this.limitGroupMessageCache(Number(d)),this.persistEnabled&&this.saveGroupMessagesToStorage(Number(d))}this.enforceMemoryLimits()},t.sortConversations=function(){var e=this;this.conversationCache.sort(function(t,n){var o,r,i,s,a=!0===t.pin,c=!0===n.pin;if(a&&!c)return-1;if(!a&&c)return 1;if(a&&c)return(null!=(i=e.pinnedConversationOrder.get(t.id))?i:0)-(null!=(s=e.pinnedConversationOrder.get(n.id))?s:0);var u=(null==(o=t.latest)?void 0:o.createTime)||0;return((null==(r=n.latest)?void 0:r.createTime)||0)-u})},t.sortGroupMessages=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].sort(function(e,t){return(t.createTime||0)-(e.createTime||0)})},t.limitGroupMessageCache=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].length>this.config.MAX_GROUP_MESSAGES&&(this.groupMessageCache[e]=this.groupMessageCache[e].slice(0,this.config.MAX_GROUP_MESSAGES))},t.recordAccess=function(e){this.accessTimeRecord[e]=Date.now()},t.enforceConversationLimit=function(){this.conversationCache.length<=this.config.MAX_CONVERSATIONS||(this.sortConversations(),this.conversationCache=this.conversationCache.slice(0,this.config.MAX_CONVERSATIONS))},t.enforceMemoryLimits=function(){var e=this,t=Object.keys(this.groupMessageCache).length;if(t>10){var n=Object.keys(this.groupMessageCache).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}});n.sort(function(e,t){return e.lastAccess-t.lastAccess});for(var o=Math.ceil(.3*t),r=0;r<o&&r<n.length;r++){var i=n[r].groupId;this.persistEnabled&&(delete this.groupMessageCache[i],this.debug&&console.log("Released memory for inactive group: "+i))}}},t.setupCleanupInterval=function(){var e=this;this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=window.setInterval(function(){e.cleanupExpiredData()},this.config.EXPIRY_CHECK_INTERVAL)},t.cleanupExpiredData=function(){var e=Date.now();this.metaInfo.lastCleanup=e,this.debug&&console.log("Running cache cleanup");for(var t=0,n=Object.entries(this.accessTimeRecord);t<n.length;t++){var o=n[t],r=o[0];e-o[1]>this.config.CACHE_TTL&&(delete this.accessTimeRecord[r],this.groupMessageCache[r]&&delete this.groupMessageCache[r])}this.persistEnabled&&this.saveMetaInfoToStorage()},t.getUserStorageKey=function(e){return this.currentUsername?e+"_"+this.currentUsername:e},t.loadFromStorage=function(){var e=this;try{var t=localStorage.getItem(M.META_INFO);t&&(this.metaInfo=JSON.parse(t));var n=this.getUserStorageKey(M.CONVERSATIONS),o=localStorage.getItem(n);this.conversationCache=o?JSON.parse(o):[],Object.keys(localStorage).filter(function(e){return e.startsWith(M.GROUP_MESSAGES+".")}).forEach(function(t){var n=t.split(".")[1];n&&!isNaN(Number(n))&&(e.accessTimeRecord[n]=0)});var r=this.getUserStorageKey(M.USER_INFO),i=localStorage.getItem(r);this.userInfo=i?JSON.parse(i):{username:this.currentUsername}}catch(e){console.error("Failed to load cache from storage:",e),this.clearStorage()}},t.loadGroupMessagesFromStorage=function(e){try{for(var t=[],n=0,o=!0;o;){var r=localStorage.getItem(M.GROUP_MESSAGES+"."+e+(n>0?"."+n:""));if(r){var i=JSON.parse(r);t=t.concat(i),n++}else o=!1}t.length>0&&(this.groupMessageCache[e]=t,this.sortGroupMessages(e),this.limitGroupMessageCache(e),this.debug&&console.log("Loaded "+t.length+" messages for group "+e+" from storage"))}catch(t){console.error("Failed to load group messages for "+e+" from storage:",t)}},t.saveConversationsToStorage=function(){try{var e=this.getUserStorageKey(M.CONVERSATIONS);localStorage.setItem(e,JSON.stringify(this.conversationCache))}catch(e){console.error("Failed to save conversations to storage:",e),this.handleStorageError()}},t.saveGroupMessagesToStorage=function(e){try{if(void 0!==e){var t=this.groupMessageCache[e];if(!t||0===t.length)return;var n=JSON.stringify(t);if(n.length>this.config.STORAGE_CHUNK_SIZE){this.clearGroupMessageStorage(e);for(var o=t.length,r=Math.max(1,Math.floor(this.config.STORAGE_CHUNK_SIZE/(n.length/o))),i=0;i<o;i+=r){var s=t.slice(i,i+r),a=Math.floor(i/r);localStorage.setItem(M.GROUP_MESSAGES+"."+e+(a>0?"."+a:""),JSON.stringify(s))}}else localStorage.setItem(M.GROUP_MESSAGES+"."+e,n)}else for(var c=0,u=Object.keys(this.groupMessageCache);c<u.length;c++)this.saveGroupMessagesToStorage(Number(u[c]))}catch(e){console.error("Failed to save group messages to storage:",e),this.handleStorageError()}},t.saveMetaInfoToStorage=function(){try{localStorage.setItem(M.META_INFO,JSON.stringify(this.metaInfo))}catch(e){console.error("Failed to save meta info to storage:",e)}},t.handleStorageError=function(){for(var e=this,t=Object.keys(this.accessTimeRecord).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}}).sort(function(e,t){return e.lastAccess-t.lastAccess}),n=Math.max(1,Math.floor(.2*t.length)),o=0;o<n&&o<t.length;o++)this.clearGroupMessageStorage(Number(t[o].groupId)),this.debug&&console.log("Cleared storage for group "+t[o].groupId+" due to quota exceeded")},t.clearGroupMessageStorage=function(e){for(var t=0,n=!0;n;){var o=M.GROUP_MESSAGES+"."+e+(t>0?"."+t:"");null!==localStorage.getItem(o)?(localStorage.removeItem(o),t++):n=!1}},t.saveUserInfoToStorage=function(){try{var e=this.getUserStorageKey(M.USER_INFO);localStorage.setItem(e,JSON.stringify(this.userInfo))}catch(e){console.error("Failed to save user info to storage:",e)}},t.clearStorage=function(){try{for(var e,t=o(Object.keys(localStorage).filter(function(e){return e.startsWith(E)}));!(e=t()).done;)localStorage.removeItem(e.value)}catch(e){console.error("Failed to clear storage:",e)}},t.destroy=function(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.debug&&console.log("Cache manager destroyed")},t.markConversationAsActive=function(e,t){void 0===t&&(t=!0),this.accessTimeRecord[e]=Date.now();var n,o=this.conversationCache.find(function(t){return t.id===e});return!!o&&(this.activeConversation=r({},o),t&&o.unreadCount>0&&(o.unreadCount=0,null!=(n=o.latest)&&n.msgId&&(o.lastRead=o.latest.msgId),this.persistEnabled&&this.saveConversationsToStorage()),!0)},t.resetActiveConversation=function(){var e,t=!(null==(e=this.activeConversation)||!e.id);return this.activeConversation=void 0,this.debug&&t&&console.log("Active conversation reset"),t},e}(),y=/*#__PURE__*/function(){function t(e){this.url=void 0,this.token=void 0,this.eventSource=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.isDestroyed=!1,this.debug=!1,this._openHandler=null,this._errorHandler=null,this._messageHandler=null,this._customHandlers=new Map,this.connectTimeoutRef=null,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange}var n=t.prototype;return n.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.removeAllEventListeners=function(){var e=this;this.eventSource&&(this._openHandler&&this.eventSource.removeEventListener("open",this._openHandler),this._errorHandler&&this.eventSource.removeEventListener("error",this._errorHandler),this._messageHandler&&this.eventSource.removeEventListener("message",this._messageHandler),this.handlers.forEach(function(t,n){var o=e._customHandlers.get(n);o&&e.eventSource&&e.eventSource.removeEventListener(n,o)}))},n.subscribe=function(e,t){var n=this;this.handlers.set(e,t);var o=function(e){try{var o=JSON.parse(e.data);t(o)}catch(e){n.debugError("Error parsing message data:",e)}};this._customHandlers.set(e,o),this.eventSource?this.eventSource.addEventListener(e,o):this.connect()},n.connect=function(){var t=this;return this.connected&&this.eventSource?Promise.reject(new Error("SSE is already connected!")):new Promise(function(n,o){try{t.eventSource=new e(t.url,{heartbeatTimeout:36e5,withCredentials:!1,headers:{Authorization:"Bearer "+t.token}}),t._openHandler=function(e){t.debugLog("SSE connection established"),t.connected=!0,t.onConnectionChangeCallback&&t.onConnectionChangeCallback(!0),t.reconnectAttempts>0&&t.onReconnectSuccessCallback&&t.onReconnectSuccessCallback(),t.reconnectAttempts=0,t.reconnectTimeout=5e3,n("SSE connect successful!")},t._errorHandler=function(e){t.debugError("SSE connection error:",e),t.connected=!1,t.onConnectionChangeCallback&&t.onConnectionChangeCallback(!1),401===e.status||e.statusText&&e.statusText.includes("Unauthorized")?(t.cleanup(),t.connectTimeoutRef&&(clearTimeout(t.connectTimeoutRef),t.connectTimeoutRef=null),t.notifyConnectionClosed(!0)):t.handleReconnect(),t.connected||o(new Error("SSE connect error"))},t._messageHandler=function(e){try{t.debugLog("SSE received message:",e.data);var n=JSON.parse(e.data);t.onMessageCallback&&t.onMessageCallback(n)}catch(e){t.debugError("Error parsing message:",e)}},t.eventSource.addEventListener("open",t._openHandler),t.eventSource.addEventListener("error",t._errorHandler),t.eventSource.addEventListener("message",t._messageHandler),t.handlers.forEach(function(e,n){var o=t._customHandlers.get(n);o&&t.eventSource&&t.eventSource.addEventListener(n,o)}),t.connectTimeoutRef=setTimeout(function(){t.connected||(o(new Error("Connection timeout")),t.handleReconnect())},t.connectTimeout);var r=t._openHandler;t._openHandler=function(e){clearTimeout(t.connectTimeoutRef),r(e)}}catch(e){t.debugError("Failed to create EventSource:",e),t.handleReconnect(),o(e)}})},n.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("SSE connection closed due to authentication error"):this.debugLog("SSE connection closed")},n.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("SSE is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroySse(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},n.cleanup=function(){this.eventSource&&(this.removeAllEventListeners(),this.eventSource.close(),this.eventSource=null),this.connected=!1},n.unsubscribe=function(){this.cleanup(),this.handlers.clear(),this._customHandlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)},n.destroySse=function(){this.unsubscribe(),this.isDestroyed=!0,this.notifyConnectionClosed()},n.close=function(){this.destroySse(),this.debugLog("SSE 连接已关闭")},n.isConnected=function(){return this.connected},n.send=function(e){var t="当前协议不可用:SSE 是单向通信协议,不支持客户端向服务器发送消息";throw this.debugError(t),new Error(t)},t}(),O=/*#__PURE__*/function(){function e(e){this.url=void 0,this.token=void 0,this.websocket=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.connectTimeoutRef=null,this.isDestroyed=!1,this.debug=!1,this.lastPingTime=0,this.pingCheckTimer=null,this.pageVisibilityHandler=null,this.isPageVisible=!0,this.lastVisibleTime=Date.now(),this.PING_TIMEOUT=12e4,this.PING_CHECK_INTERVAL=5e3,this.RECONNECT_DELAY=3e3,this.PAGE_HIDDEN_TOLERANCE=6e4,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange,this.initPageVisibilityDetection()}var t=e.prototype;return t.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.subscribe=function(e,t){this.handlers.set(e,t),this.websocket?this.addMessageHandler(e,t):this.connect()},t.addMessageHandler=function(e,t){var n=this;this.websocket&&this.websocket.addEventListener("message",function(o){try{var r=JSON.parse(o.data);r.type===e&&t(r)}catch(e){n.debugError("Error parsing WebSocket message data:",e)}})},t.connect=function(){var e=this;return this.connected&&this.websocket?Promise.reject(new Error("WebSocket is already connected!")):new Promise(function(t,n){try{var o=new URL(e.url);o.searchParams.set("token",e.token),e.websocket=new WebSocket(o.toString()),e.websocket.binaryType="arraybuffer",e.connectTimeoutRef=setTimeout(function(){e.connected||(n(new Error("WebSocket connection timeout")),e.handleReconnect())},e.connectTimeout),e.websocket.onopen=function(n){e.debugLog("WebSocket connection established"),e.connected=!0,clearTimeout(e.connectTimeoutRef),e.lastPingTime=Date.now(),e.startPingTimeoutCheck(),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!0),e.reconnectAttempts>0&&e.onReconnectSuccessCallback&&e.onReconnectSuccessCallback(),e.reconnectAttempts=0,e.reconnectTimeout=5e3,t("WebSocket connect successful!")},e.websocket.onerror=function(t){e.debugError("WebSocket connection error:",t),e.connected=!1,clearTimeout(e.connectTimeoutRef),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!1),e.handleReconnect(),e.connected||n(new Error("WebSocket connect error"))},e.websocket.onclose=function(t){e.debugLog("WebSocket connection closed:",t.code,t.reason),e.connected=!1,1002===t.code||1003===t.code||t.reason&&t.reason.includes("Unauthorized")?(e.cleanup(),e.notifyConnectionClosed(!0)):(e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.handleReconnect())},e.websocket.onmessage=function(t){try{t.data instanceof ArrayBuffer?e.handleBinaryMessage(t.data):e.handleTextMessage(t.data),e.lastPingTime=Date.now()}catch(t){e.debugError("Error handling WebSocket message:",t)}},e.handlers.forEach(function(t,n){e.addMessageHandler(n,t)})}catch(t){e.debugError("Failed to create WebSocket:",t),e.handleReconnect(),n(t)}})},t.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("WebSocket connection closed due to authentication error"):this.debugLog("WebSocket connection closed")},t.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("WebSocket is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroyWebSocket(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds... (attempt "+(this.reconnectAttempts+1)+"/"+this.maxReconnectAttempts+")"),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},t.handleBinaryMessage=function(e){var t=new DataView(e);if(!(e.byteLength<1)){var n=t.getUint8(0);if(125===n&&e.byteLength>=9){var o=t.getBigInt64(1,!1);return this.debugLog("收到服务端心跳 ping:",o.toString()),this.lastPingTime=Date.now(),void this.sendPong(o)}this.onMessageCallback?this.onMessageCallback(new Uint8Array(e)):this.debugLog("收到二进制消息,类型:","0x"+n.toString(16),"长度:",e.byteLength)}},t.handleTextMessage=function(e){try{this.debugLog("WebSocket received text message:",e);var t=JSON.parse(e);if("pong"===t.type||2===t.ev)return this.connected=!0,void(this.lastPingTime=Date.now());this.onMessageCallback&&this.onMessageCallback(t)}catch(e){this.debugError("Error parsing WebSocket text message:",e)}},t.sendPong=function(e){if(this.websocket&&this.websocket.readyState===WebSocket.OPEN)try{var t=new ArrayBuffer(9),n=new DataView(t);n.setUint8(0,126),n.setBigInt64(1,e,!1),this.websocket.send(t),this.debugLog("已回复心跳 pong, timestamp:",e.toString())}catch(e){this.debugError("Failed to send pong:",e)}else this.debugWarn("WebSocket is not open, cannot send pong")},t.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.lastVisibleTime=Date.now(),this.pageVisibilityHandler=function(){var t=e.isPageVisible;if(e.isPageVisible=!document.hidden,t&&!e.isPageVisible)e.lastVisibleTime=Date.now(),e.debugLog("Page became hidden, pausing ping timeout check");else if(!t&&e.isPageVisible){var n=Date.now()-e.lastVisibleTime;e.debugLog("Page became visible after "+n+"ms"),e.websocket&&e.websocket.readyState===WebSocket.OPEN&&n>e.PAGE_HIDDEN_TOLERANCE&&(e.debugLog("Page was hidden for a long time, adjusting ping time"),e.lastPingTime=Date.now()-(e.PING_TIMEOUT-e.PAGE_HIDDEN_TOLERANCE))}},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},t.startPingTimeoutCheck=function(){var e=this;this.stopPingTimeoutCheck(),this.pingCheckTimer=window.setInterval(function(){if(!e.isDestroyed&&e.websocket)if(e.isPageVisible){if(e.websocket.readyState!==WebSocket.OPEN)return e.debugWarn("WebSocket state is "+e.websocket.readyState+", connection may be broken"),e.connected=!1,e.stopPingTimeoutCheck(),e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),void e.delayedReconnect();var t=Date.now()-e.lastPingTime;t>e.PING_TIMEOUT?(e.debugWarn("Ping timeout: "+t+"ms since last ping, connection may be broken"),e.connected=!1,e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.delayedReconnect()):e.debugLog("Last ping received "+t+"ms ago")}else e.debugLog("Page is hidden, skipping ping timeout check");else e.stopPingTimeoutCheck()},this.PING_CHECK_INTERVAL)},t.stopPingTimeoutCheck=function(){null!==this.pingCheckTimer&&(clearInterval(this.pingCheckTimer),this.pingCheckTimer=null)},t.delayedReconnect=function(){var e=this;null===this.reconnectTimer&&(this.debugLog("Delaying reconnect for "+this.RECONNECT_DELAY/1e3+" seconds to prevent reconnect storm..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectTimer=null,e.handleReconnect()},this.RECONNECT_DELAY))},t.cleanup=function(){this.stopPingTimeoutCheck(),this.websocket&&(this.websocket.close(),this.websocket=null),this.connected=!1},t.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null)},t.unsubscribe=function(){this.cleanup(),this.handlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.cleanupPageVisibilityDetection()},t.destroyWebSocket=function(){this.unsubscribe(),this.isDestroyed=!0,this.cleanupPageVisibilityDetection(),this.notifyConnectionClosed()},t.close=function(){this.destroyWebSocket(),this.debugLog("WebSocket 连接已关闭")},t.isConnected=function(){var e;return this.connected&&(null==(e=this.websocket)?void 0:e.readyState)===WebSocket.OPEN},t.send=function(e){if(!this.websocket||!this.isConnected())return this.debugWarn("WebSocket is not connected, cannot send message"),!1;try{if("string"==typeof e)this.websocket.send(e),this.debugLog("WebSocket message sent (string):",e);else if(e instanceof ArrayBuffer||e instanceof Blob)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBuffer/Blob ("+(e instanceof ArrayBuffer?e.byteLength:e.size)+" bytes)");else if(e instanceof Uint8Array||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof DataView)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBufferView ("+e.byteLength+" bytes)");else{var t=JSON.stringify(e);this.websocket.send(t),this.debugLog("WebSocket message sent (JSON):",t)}return!0}catch(e){return this.debugError("Failed to send WebSocket message:",e),!1}},e}(),G=["protocol"],k=/*#__PURE__*/function(){function e(){}return e.createClient=function(e){var t=e.protocol,n=function(e,t){if(null==e)return{};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o]}return n}(e,G);switch(t){case v.SSE:return new y(n);case v.WEBSOCKET:return new O(n);default:throw new Error("Unsupported connection protocol: "+t)}},e}(),R=null,A=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.login=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.Login,method:"POST"}))}catch(e){return Promise.reject(e)}},t.logout=function(){try{return Promise.resolve(this.sdk.sendRequest({data:{},url:d.Logout,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getChatMember=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{chatId:e,parent:t},url:d.GetChatMember,method:"GET"}))}catch(e){return Promise.reject(e)}},e}(),I=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.sendMessage=function(e,t){try{var n=this;return Promise.resolve(function(o,r){try{var i=Promise.resolve(n.sdk.sendRequest({data:e,url:t,method:"POST"}))}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(e){throw console.error("Failed to send message",e),e}))}catch(e){return Promise.reject(e)}},t.getMessageApi=function(e,t){return t===g.PrivateChat?d.PushPrivateMessage:t===g.LiveGroup?d.PushLiveMessage:null!=e&&e.receiverName?d.PushMessageToMember:d.CreateTextMessage},t.createMessage=function(e,t,n,o,i){void 0===o&&(o={});var s={groupType:n};n===g.PublicGroup||n===g.PrivateGroup||n===g.LiveGroup?s.groupId=t:s.receiverName=t;var a=r({},s,o,{msgType:e},i);return this.sendMessage(a,this.getMessageApi(s,n))},t.createTextMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.TEXT,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.createImageMessage=function(e,t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(h.IMAGE,n,o,r,{link:e,snapshot:t}))}catch(e){return Promise.reject(e)}},t.createFileMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.FILE,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createAudioMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.AUDIO,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createVideoMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.VIDEO,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createLinkMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.LINK,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createGifMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.GIF,t,n,o,{link:e}))}catch(e){return Promise.reject(e)}},t.createOptionMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.OPTION,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.createEmojiMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.EMOJI,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.createCustomMessage=function(e,t,n,o){void 0===o&&(o={});try{return Promise.resolve(this.createMessage(h.CUSTOM,t,n,o,{text:e}))}catch(e){return Promise.reject(e)}},t.getHistoryMessageList=function(e){var t=e.groupId,n=e.lastId,o=e.type,r=e.size,i=void 0===r?100:r;try{return Promise.resolve(this.sdk.sendRequest({url:d.GetHistoryMessageList,method:"POST",data:{groupId:t,lastId:n,type:o,size:i}}))}catch(e){return Promise.reject(e)}},t.getLiveMessageList=function(e){var t=e.groupId;try{var n;return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:null!=(n=this.sdk.getConfig)&&n.anonLogin?d.GetAnonymousLiveMessageList:d.GetLiveMessageList,method:"POST"}))}catch(e){return Promise.reject(e)}},t.prePushCustomerMessage=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.PrePushCustomerMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},e}(),_=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.getConversations=function(e){try{var t=this;return Promise.resolve(t.sdk.sendRequest({data:e,url:d.GetAllConversationList,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(t.normalizeConversation),e})}catch(e){return Promise.reject(e)}},t.getChannels=function(e){try{var t=this;return Promise.resolve(t.sdk.sendRequest({data:e,url:d.GetChannels,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(t.normalizeConversation),e})}catch(e){return Promise.reject(e)}},t.markConversationRead=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},t.markLastRead=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,msgId:t},url:d.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},t.pinConversation=function(e,t){void 0===t&&(t=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,isTop:t},url:d.PinConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},t.muteConversation=function(e,t){void 0===t&&(t=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,mute:t},url:d.MuteConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},t.normalizeConversation=function(e){var t,n,o,i,s,a,c,u,d;return r({},e,{id:e.id,name:e.name||"",groupType:e.groupType||0,avatar:e.avatar||"",status:null!=(t=e.status)?t:1,latest:null!=(n=e.latest)?n:{},unreadCount:null!=(o=e.unreadCount)?o:0,lastRead:e.lastRead,draftText:null!=(i=e.draftText)?i:"",custom:null!=(s=e.custom)?s:"",groupMemberId:null!=(a=e.groupMemberId)?a:"",pin:null!=(c=e.pin)&&c,supportId:e.supportId||"",supportNick:e.supportNick||"",identity:null!=(u=e.identity)?u:1,mute:null!=(d=e.mute)&&d})},e}(),U=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.getGroupInfo=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:d.GetGroupInfo,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupMember=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:d.GetGroupMember,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupMembers=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.GetGroupMembers,method:"GET"}))}catch(e){return Promise.reject(e)}},t.joinGroup=function(e){try{var t;return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:null!=(t=this.sdk.getConfig)&&t.anonLogin?d.AnonymousJoinGroup:d.JoinGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},t.leftGroup=function(e){try{var t;return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:null!=(t=this.sdk.getConfig)&&t.anonLogin?d.AnonymousLeftGroup:d.LeftGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},t.checkGroupBlock=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:d.CheckGroupBlock,method:"GET"}))}catch(e){return Promise.reject(e)}},t.updateLatestMessage=function(e){try{var t=Object.fromEntries(e.entries());return Promise.resolve(this.sdk.sendRequest({data:{latestMessage:t},url:d.UpdateLatestMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getGroupLatestMessage=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groups:e},url:d.GetLatestGroupChats,method:"POST"}))}catch(e){return Promise.reject(e)}},t.checkGroupLatestMessage=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{ttl:e},url:d.CheckLatestMessages,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getMyGroupPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:d.GetMyGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e},url:d.GetGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getGroupMemberPermission=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,targetMemberId:t},url:d.GetGroupMemberPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},t.updateGroupPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.UpdateGroupPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},t.updateGroupMemberPermission=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.UpdateGroupMemberPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},t.kickGroupMember=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.kickGroupMember,method:"POST"}))}catch(e){return Promise.reject(e)}},t.muteMembers=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.muteMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},t.editGroupName=function(e,t,n){try{return Promise.resolve(this.sdk.sendRequest({url:d.editeGroupName,method:"GET",data:{groupId:e,name:t,avatar:n}}))}catch(e){return Promise.reject(e)}},t.editNotification=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:d.editeNotification,method:"GET",data:{groupId:e,notification:t}}))}catch(e){return Promise.reject(e)}},t.editGroupCustomer=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:d.editeGroupCustomer,method:"GET",data:{groupId:e,customer:t}}))}catch(e){return Promise.reject(e)}},t.addAdmin=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:d.addAdmin,method:"GET",data:{groupId:e,username:t}}))}catch(e){return Promise.reject(e)}},t.deleteAdmin=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:d.deleteAdmin,method:"GET",data:{groupId:e,username:t}}))}catch(e){return Promise.reject(e)}},t.dissolveGroup=function(e){try{return Promise.resolve(this.sdk.sendRequest({url:d.DissolveGroup,method:"GET",data:{groupId:e}}))}catch(e){return Promise.reject(e)}},t.pin=function(e,t,n){try{return Promise.resolve(this.sdk.sendRequest({url:d.pin,method:"GET",data:{groupId:e,messageId:t,type:n}}))}catch(e){return Promise.reject(e)}},t.muteGroup=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({url:d.muteGroup,method:"GET",data:{groupId:e,type:t}}))}catch(e){return Promise.reject(e)}},t.muteMember=function(e,t,n){try{return Promise.resolve(this.sdk.sendRequest({url:d.muteMember,method:"GET",data:{groupId:e,username:t,type:n}}))}catch(e){return Promise.reject(e)}},t.addGroupMembers=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.AddGroupMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getFileByType=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.GetFileByType,method:"GET"}))}catch(e){return Promise.reject(e)}},t.pinChat=function(e,t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:e,type:t},url:d.PinChat,method:"GET"}))}catch(e){return Promise.reject(e)}},e}(),N=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.sdk=e}var t=e.prototype;return t.getContactByType=function(e,t){try{var n={contactType:e};return void 0!==t&&(n.groupId=t),Promise.resolve(this.sdk.sendRequest({data:n,url:d.GetContactByType,method:"GET"}))}catch(e){return Promise.reject(e)}},t.getMemberContacts=function(e){try{return Promise.resolve(this.getContactByType(c.MEMBER,e))}catch(e){return Promise.reject(e)}},t.getColleagueContacts=function(e){try{return Promise.resolve(this.getContactByType(c.COLLEAGUE,e))}catch(e){return Promise.reject(e)}},t.getGroupContacts=function(e){try{return Promise.resolve(this.getContactByType(c.GROUP,e))}catch(e){return Promise.reject(e)}},t.editContactTag=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.EditContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},t.getContactTag=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:{contactType:e},url:d.GetContactTag,method:"GET"}))}catch(e){return Promise.reject(e)}},t.allocationContactTag=function(e){try{return Promise.resolve(this.sdk.sendRequest({data:e,url:d.AllocationContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},t.allocationMemberTag=function(e,t,n){void 0===n&&(n=0);try{return Promise.resolve(this.allocationContactTag({contactType:c.MEMBER,tag:e,groupIds:t,type:n}))}catch(e){return Promise.reject(e)}},t.allocationColleagueTag=function(e,t,n){void 0===n&&(n=0);try{return Promise.resolve(this.allocationContactTag({contactType:c.COLLEAGUE,tag:e,groupIds:t,type:n}))}catch(e){return Promise.reject(e)}},t.allocationGroupTag=function(e,t,n){void 0===n&&(n=0);try{return Promise.resolve(this.allocationContactTag({contactType:c.GROUP,tag:e,groupIds:t,type:n}))}catch(e){return Promise.reject(e)}},e}(),L=/*#__PURE__*/function(){function e(e){this.sdk=void 0,this.services={},this.sdk=e}var t=e.prototype;return t.get=function(e){return this.services[e]||(this.services[e]=this.createService(e)),this.services[e]},t.createService=function(e){switch(e){case a.USER:return new A(this.sdk);case a.MESSAGE:return new I(this.sdk);case a.CONVERSATION:return new _(this.sdk);case a.GROUP:return new U(this.sdk);case a.CONTACT:return new N(this.sdk);default:throw new Error("Unknown service: "+e)}},t.reset=function(){this.services={}},e}();function w(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var D=[d.Logout,l.OnKickedOffline,l.OnUserTokenInvalid,l.OnUserTokenExpired],V=/*#__PURE__*/function(e){function n(t){var o;return void 0===t&&(t=!1),(o=e.call(this)||this).config={debug:!1,isLive:!1,useProtobuf:!1,protocol:v.SSE},o.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},o.cacheManager=void 0,o.connectionClient=void 0,o.serviceManager=void 0,o.lastUnauthorizedTime=0,o.UNAUTHORIZED_THROTTLE_MS=3e3,o.conversationUpdateTimer=null,o.CONVERSATION_UPDATE_THROTTLE_MS=500,o.pendingConversationUpdate=!1,o.lastConversationUpdateTime=0,o.isPageVisible=!0,o.pageVisibilityHandler=null,o.PAGE_HIDDEN_STOP_DELAY_MS=3e3,o.pageHiddenTimer=null,o.isActuallyHidden=!1,o.PAGE_VISIBLE_STABLE_MS=1e3,o.pageVisibleStableTimer=null,o.configure=function(e){void 0!==e.debug&&(o.config.debug=e.debug),e.isLive&&(o.config.isLive=e.isLive),e.apiAddr&&(o.config.apiAddr=e.apiAddr),e.wsAddr&&(o.config.wsAddr=e.wsAddr),e.ossApiAddr&&(o.config.ossApiAddr=e.ossApiAddr),e.appKey&&(o.config.appKey=e.appKey),e.token&&(o.config.token=e.token),e.connectTimeout&&(o.config.connectTimeout=e.connectTimeout),e.maxRetries&&(o.config.maxRetries=e.maxRetries),e.useProtobuf&&(o.config.useProtobuf=e.useProtobuf),e.protocol&&(o.config.protocol=e.protocol)},o.sendRequest=function(e){try{o.internalState.lastActivity=Date.now(),o.config.debug&&o.logRequest(e);var t=o.config.apiAddr+e.url,n=e.data;if("GET"===e.method&&n){var r=new URLSearchParams;Object.entries(n).forEach(function(e){var t=e[1];null!=t&&r.append(e[0],String(t))});var i=r.toString();i&&(t+=(t.includes("?")?"&":"?")+i),n=void 0}return Promise.resolve(w(function(){return Promise.resolve(function(e){try{var t,n=function(e){if(t)return e;throw new Error("Unsupported platform")},o=function(){if(S){var n=new Promise(function(t,n){uni.request({url:e.url,method:e.method||"GET",header:e.headers,data:e.data,success:function(e){401!==e.statusCode?t(e.data):n({status:401,message:"Unauthorized"})},fail:function(e){return n(e)}})});return t=1,n}return function(){if(b)return Promise.resolve(fetch(e.url,{method:e.method||"GET",headers:e.headers,body:e.data?JSON.stringify(e.data):null})).then(function(e){if(401===e.status)throw{status:401,message:"Unauthorized"};return Promise.resolve(e.json()).then(function(e){return t=1,e})})}()}();return Promise.resolve(o&&o.then?o.then(n):n(o))}catch(e){return Promise.reject(e)}}({url:t,method:e.method,headers:{"Content-Type":"application/json",Authorization:o.config.token?"Bearer "+o.config.token:""},data:n}))},function(e){throw 401!==(null==e?void 0:e.status)&&401!==(null==e?void 0:e.statusCode)||o.handleUnauthorizedWithThrottle(t),e}))}catch(e){return Promise.reject(e)}},o.handleUnauthorizedWithThrottle=function(e){var t=Date.now();t-o.lastUnauthorizedTime<o.UNAUTHORIZED_THROTTLE_MS?console.warn("401错误被节流限制,跳过处理:"+e):(o.lastUnauthorizedTime=t,o.handleUnauthorized(e))},o.handleUnauthorized=function(e){console.warn("未授权请求(401):",e),o.handleConnectionClosed(!0)},o.createRequestFunction=function(e,t){return function(n){return o.sendRequest({data:n,url:e,method:t})}},o.createRequestFunctionWithoutParams=function(e,t){return function(){return o.sendRequest({data:void 0,method:t,url:e})}},o.handleMessage=function(e){if(o.config.debug&&console.log("[SDK] handleMessage response",e),o.isBinaryMessage(e)){var t=o.normalizeToBinaryBuffer(e);if(!t||t.length<1)o.config.debug&&console.warn("[SDK] [Proto] 二进制消息长度不足,已忽略");else{var r=t[0];switch(r){case n.BINARY_MSG_TYPE.BYTE_MESSAGE:o.handleProtobufMessage(t).catch(function(e){console.error("[SDK] handleProtobufMessage error",e)});break;case n.BINARY_MSG_TYPE.HEARTBEAT_PONG:o.internalState.isConnected=!0,o.config.debug&&console.log("[SDK] [Proto] 收到 PONG(0x7E),已更新 isConnected");break;case n.BINARY_MSG_TYPE.HEARTBEAT_PING:o.config.debug&&console.log("[SDK] [Proto] 收到 PING(0x7D),应由连接层回复 PONG");break;default:o.config.debug&&console.warn("[SDK] [Proto] 未知二进制类型,已忽略",{messageType:"0x"+r.toString(16),length:t.length})}}}else o.handleJsonMessage(e)},o.handleJsonMessage=function(e){switch(o.config.debug&&console.log("handleMessage response",e),e.ev){case m.EVENT_MESSAGE_PUSH:var t=e.dt;Array.isArray(t)?(t.forEach(function(e){o.updateMessageCache(e)}),o.emit(l.OnReceiveMessages,t)):console.warn("[SDK] Expected response.dt to be an array, but got:",t);break;case m.EVENT_PONG_IDLE:o.internalState.isConnected=!0;break;case m.EVENT_SYSTEM_MESSAGE_PUSH:o.emit(l.OnReceiveSystemMessage,e.dt);break;case m.EVENT_PRE_MESSAGE_PUSH:o.emit(l.OnReceivePreMessage,e.dt);break;case m.EVENT_SUBSCRIBE_MESSAGE_PUSH:o.emit(l.OnReceiveSubscribeMessage,e.dt);break;default:n=e.ev,Object.values(l).includes(n)?(o.emit(e.ev,e.dt),D.includes(e.ev)&&(o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1,o.connectionClient&&(o.connectionClient.close(),o.connectionClient=void 0))):o.config.debug&&console.warn("[SDK] Unknown SSE event type:",e.ev)}var n},o.handleReconnectSuccess=function(){o.config.username&&(o.internalState.isConnected=!0,o.internalState.reconnectAttempts=0,o.config.debug&&console.log("SSE reconnection successful"),o.emit(l.OnReconnected))},o.handleConnectionClosed=function(e){o.internalState.isConnected=!1,o.config.debug&&console.log("SSE connection closed"),o.emit(l.OnDisconnected,e)},o.handleMaxRetriesReached=function(){o.config.debug&&console.log("SSE connection max reconnection attempts reached"),o.emit(l.onMaxRetriesReached)},o.handleConnectionChange=function(e){o.config.debug&&console.log("Connection status changed:",e),o.emit(e?l.OnConnected:l.OnDisconnected)},o.login=function(e){try{var t,n,i=function(r){return t?r:(o.connectionClient=k.createClient({url:o.config.wsAddr+"/"+(e.anonLogin?"anonymousConn":"conn")+"?username="+e.username+"&token="+e.token+"&appKey="+o.config.appKey+"&random="+n,protocol:o.config.protocol||v.WEBSOCKET,debug:o.config.debug,onMessage:o.handleMessage,onReconnectSuccess:o.handleReconnectSuccess,onConnectionClosed:o.handleConnectionClosed,onMaxRetriesReached:o.handleMaxRetriesReached,onConnectionChange:o.handleConnectionChange,token:e.token,connectTimeout:o.config.connectTimeout,maxRetries:o.config.maxRetries}),w(function(){return Promise.resolve(o.connectionClient.connect()).then(function(e){return o.internalState.isLoggedIn=!0,o.internalState.isConnected=!0,o.config.isLive||o.initializeConversationCache(),e})},function(e){return o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1,Promise.reject(e.message)}))};if(o.connectionClient&&(null==o.connectionClient.close||o.connectionClient.close(),o.connectionClient=void 0,o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1),!o.config.apiAddr)return Promise.reject("No apiAddr configured. Please call configure() before login().");if(!o.config.ossApiAddr)return Promise.reject("No ossApiAddr configured. Please call configure() before login().");if(!o.config.appKey)return Promise.reject("No appKey configured. Please call configure() before login().");if(!o.config.token)return Promise.reject("No token configured. Please call configure() before login().");if(o.config.username=e.username,o.config.anonLogin=e.anonLogin||!1,e.protocol&&(o.config.protocol=e.protocol),e.protocol==v.WEBSOCKET&&!o.config.wsAddr)return Promise.reject("WebSocket address (wsAddr) is not configured. Please call configure() before login().");if(o.config.debug&&(console.log("login params",e),console.log("apiAddr",o.config.apiAddr)),!o.config.isLive||!e.anonLogin){o.cacheManager.initialize(e.username),o.cacheManager.resetActiveConversation();var s=o.cacheManager.getConversations();s.length>0&&o.emit(l.OnConversationListUpdated,s)}var a=function(){if(!e.anonLogin)return Promise.resolve(o.user.login(r({},e,{appKey:o.config.appKey}))).then(function(e){var o=e.code,r=e.data;if(0!=o){var i=Promise.resolve("Login failed, Server error, error code is "+o);return t=1,i}n=r})}();return Promise.resolve(a&&a.then?a.then(i):i(a))}catch(e){return Promise.reject(e)}},o.logout=function(){try{return o.connectionClient&&(o.connectionClient.close(),o.connectionClient=void 0),Promise.resolve(o.user.logout()).then(function(e){return o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1,o.config.username=void 0,o.config.token=void 0,o.cacheManager.clear(),e})}catch(e){return Promise.reject(e)}},o.getChatMember=function(e,t){return o.user.getChatMember(e,t)},o.getConversations=function(e){try{return Promise.resolve(w(function(){var t=e.pageNo||1,n=e.pageSize||50;return t<1?(console.warn("[SDK] Invalid pageNo, must be >= 1"),{code:-1,msg:"Invalid pageNo, must be >= 1",data:{records:[],current:1,pages:0}}):n<1||n>100?(console.warn("[SDK] Invalid pageSize, must be between 1 and 100"),{code:-1,msg:"Invalid pageSize, must be between 1 and 100",data:{records:[],current:1,pages:0}}):Promise.resolve(o.conversation.getConversations({pageNo:t,pageSize:n})).then(function(e){var n=e.data;if(0===e.code&&n){var r=o.cacheManager.getConversations();if(1===t)o.cacheManager.setConversations([].concat(n.records),!0);else{var i=n.records||[],s=new Map;r.forEach(function(e){s.set(e.id,e)});var a=[],c=[];i.forEach(function(e){s.has(e.id)?a.push(e):c.push(e)});var u=[];r.forEach(function(e){a.find(function(t){return t.id===e.id})||u.push(e)}),u.push.apply(u,a.concat(c)),o.cacheManager.setConversations(u,!1)}o.emit(l.OnConversationListUpdated,o.cacheManager.getConversations())}else{var d=o.cacheManager.getConversations();d.length>0&&o.emit(l.OnConversationListUpdated,d)}return e})},function(t){console.error("[SDK] Failed to get conversations:",t);var n=o.cacheManager.getConversations();return n.length>0&&o.emit(l.OnConversationListUpdated,n),{code:-1,msg:t instanceof Error?t.message:"Failed to get conversations",data:{records:n,current:e.pageNo||1,pages:0}}}))}catch(e){return Promise.reject(e)}},o.internalUploadFile=function(e,t){try{return Promise.resolve(w(function(){var n=""+o.config.apiAddr+d.UploadCredential+"?groupId="+t+"&filename="+encodeURIComponent(e.name);return Promise.resolve(fetch(n,{method:"GET",headers:{Authorization:o.config.token?"Bearer "+o.config.token:""}})).then(function(t){if(!t.ok)throw new Error("Get upload credential failed: "+t.status);return Promise.resolve(t.json()).then(function(t){var n=(null==t?void 0:t.data)||{};if(null==t||!t.success||null==n||!n.uploadUrl||null==n||!n.accessUrl)throw new Error((null==t?void 0:t.msg)||"Invalid upload credential response");var o=n.accessUrl;return Promise.resolve(fetch(n.uploadUrl,{method:"PUT",headers:{"Content-Type":e.type||"application/octet-stream"},body:e})).then(function(t){var r;if(!t.ok)throw new Error("Upload to OSS failed with status: "+t.status);var i=null!=(r=n.thumbnailUrl)?r:e.type.startsWith("image/")?o+(o.includes("?")?"&":"?")+"x-oss-process=image/resize,m_lfit,w_200,h_200":"";return{originalUrl:o,thumbnailUrl:i}})})})},function(e){return console.error("[Upload Error]",e),{error:e instanceof Error?e:new Error("Unknown upload error")}}))}catch(e){return Promise.reject(e)}},o.uploadFile=function(e,t){var n=e.file;try{return Promise.resolve(o.internalUploadFile(n,t)).then(function(e){var t,n=e.originalUrl,o=e.thumbnailUrl,r=e.error;return{data:{originalUrl:void 0===n?"":n,thumbnailUrl:void 0===o?"":o},msg:null!=(t=null==r?void 0:r.message)?t:"",code:r?u.UnknownError:0}})}catch(e){return Promise.reject(e)}},o.sendTextMessage=function(e,t,n,r){return o.message.createTextMessage(e,t,n,r)},o.sendImageMessage=function(e,t,n,r,i){return o.message.createImageMessage(e,t,n,r,i)},o.sendFileMessage=function(e,t,n,r){return o.message.createFileMessage(e,t,n,r)},o.sendAudioMessage=function(e,t,n,r){return o.message.createAudioMessage(e,t,n,r)},o.sendVideoMessage=function(e,t,n,r){return o.message.createVideoMessage(e,t,n,r)},o.sendLinkMessage=function(e,t,n,r){return o.message.createLinkMessage(e,t,n,r)},o.sendGifMessage=function(e,t,n,r){return o.message.createGifMessage(e,t,n,r)},o.sendOptionMessage=function(e,t,n,r){return o.message.createOptionMessage(e,t,n,r)},o.sendEmojiMessage=function(e,t,n,r){return o.message.createEmojiMessage(e,t,n,r)},o.sendCustomMessage=function(e,t,n,r){return o.message.createCustomMessage(e,t,n,r)},o.getHistoryMessageList=function(e){try{return Promise.resolve(o.message.getHistoryMessageList(e))}catch(e){return Promise.reject(e)}},o.getLiveMessageList=function(e){return o.message.getLiveMessageList(e)},o.prePushCustomerMessage=function(e){return o.message.prePushCustomerMessage(e)},o.getGroupInfo=function(e){return o.group.getGroupInfo(e)},o.getGroupMembers=function(e){return o.group.getGroupMembers(e)},o.joinGroup=function(e){return o.group.joinGroup(e)},o.leftGroup=function(e){return o.group.leftGroup(e)},o.checkGroupBlock=function(e){return o.group.checkGroupBlock(e)},o.getMyGroupPermission=function(e){return o.group.getMyGroupPermission(e)},o.getGroupPermission=function(e){return o.group.getGroupPermission(e)},o.getGroupMember=function(e){return o.group.getGroupMember(e)},o.getGroupMemberPermission=function(e,t){return o.group.getGroupMemberPermission(e,t)},o.updateGroupPermission=function(e){return o.group.updateGroupPermission(e)},o.kickGroupMember=function(e){return o.group.kickGroupMember(e)},o.muteMembers=function(e){return o.group.muteMembers(e)},o.updateGroupMemberPermission=function(e){return o.group.updateGroupMemberPermission(e)},o.editGroupName=function(e,t,n){try{return Promise.resolve(o.group.editGroupName(e,t,n)).then(function(r){if(0===r.code){var i=o.cacheManager.getConversations().find(function(t){return t.id===e});if(i){i.name=t,i.avatar=n,o.cacheManager.updateConversation(i);var s=o.cacheManager.getConversations();o.emit(l.OnConversationListUpdated,s)}}return r})}catch(e){return Promise.reject(e)}},o.editNotification=function(e,t){return o.group.editNotification(e,t)},o.editGroupCustomer=function(e,t){return o.group.editGroupCustomer(e,t)},o.addAdmin=function(e,t){return o.group.addAdmin(e,t)},o.deleteAdmin=function(e,t){return o.group.deleteAdmin(e,t)},o.pin=function(e,t,n){return o.group.pin(e,t,n)},o.muteGroup=function(e,t){return o.group.muteGroup(e,t)},o.muteMember=function(e,t,n){return o.group.muteMember(e,t,n)},o.addGroupMembers=function(e){return o.group.addGroupMembers(e)},o.getFileByType=function(e){return o.group.getFileByType(e)},o.pinChat=function(e,t){return o.group.pinChat(e,t)},o.dissolveGroup=function(e){return o.group.dissolveGroup(e)},o.markConversationRead=function(e){try{return Promise.resolve(o.conversation.markConversationRead(e)).then(function(t){if(0===t.code&&e.groupId){e.id?o.cacheManager.updateConversationLastRead(e.groupId,e.id):o.cacheManager.clearConversationUnread(e.groupId);var n=o.cacheManager.getConversations();o.emit(l.OnConversationListUpdated,n)}return t})}catch(e){return Promise.reject(e)}},o.markLastRead=function(e,t){try{return Promise.resolve(o.conversation.markLastRead(e,t)).then(function(n){if(0===n.code){o.cacheManager.updateConversationLastRead(e,t);var r=o.cacheManager.getConversations();o.emit(l.OnConversationListUpdated,r)}return n})}catch(e){return Promise.reject(e)}},o.markLastReadLocal=function(e,t){o.cacheManager.updateConversationLastRead(e,t);var n=o.cacheManager.getConversations();o.emit(l.OnConversationListUpdated,n)},o.pinConversation=function(e,t){void 0===t&&(t=1);try{return Promise.resolve(o.conversation.pinConversation(e,t)).then(function(n){if(0===n.code){o.cacheManager.updateConversationPinStatus(e,1===t);var r=o.cacheManager.getConversations();o.emit(l.OnConversationListUpdated,r)}return n})}catch(e){return Promise.reject(e)}},o.muteConversation=function(e,t){return void 0===t&&(t=1),o.conversation.muteConversation(e,t)},o.getChannels=function(e){return o.conversation.getChannels(e)},o.clearConversationUnread=function(e){o.cacheManager.clearConversationUnread(e);var t=o.cacheManager.getConversations();o.emit(l.OnConversationListUpdated,t)},o.clearAllConversationUnread=function(){o.cacheManager.clearAllConversationUnread();var e=o.cacheManager.getConversations();o.emit(l.OnConversationListUpdated,e)},o.getContactByType=function(e,t){return o.contact.getContactByType(e,t)},o.getMemberContacts=function(e){return o.contact.getMemberContacts(e)},o.getColleagueContacts=function(e){return o.contact.getColleagueContacts(e)},o.getGroupContacts=function(e){return o.contact.getGroupContacts(e)},o.editContactTag=function(e){return o.contact.editContactTag(e)},o.getContactTag=function(e){return o.contact.getContactTag(e)},o.allocationContactTag=function(e){return o.contact.allocationContactTag(e)},o.allocationMemberTag=function(e,t,n){return void 0===n&&(n=0),o.contact.allocationMemberTag(e,t,n)},o.allocationColleagueTag=function(e,t,n){return void 0===n&&(n=0),o.contact.allocationColleagueTag(e,t,n)},o.allocationGroupTag=function(e,t,n){return void 0===n&&(n=0),o.contact.allocationGroupTag(e,t,n)},o.config.debug=t,t&&(console.log("🚀 SIM SDK Web v1.1.0 (本地开发版本)"),console.log("📦 支持协议: SSE, WebSocket")),o.cacheManager=new P({persistEnabled:!0,debug:t}),o.serviceManager=new L(o),o.initPageVisibilityDetection(),o}var o,c;c=e,(o=n).prototype=Object.create(c.prototype),o.prototype.constructor=o,i(o,c);var g,h,p=n.prototype;return p.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.isActuallyHidden=!this.isPageVisible,this.pageVisibilityHandler=function(){var t=e.isPageVisible;e.isPageVisible=!document.hidden,e.config.debug&&console.log("[SDK] Page visibility changed: "+(e.isPageVisible?"visible":"hidden")),t&&!e.isPageVisible?e.handlePageHidden():!t&&e.isPageVisible&&e.handlePageVisible()},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},p.handlePageHidden=function(){var e=this;null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.pageHiddenTimer=window.setTimeout(function(){e.isPageVisible||(e.isActuallyHidden=!0,e.config.debug&&console.log("[SDK] Page is actually hidden, stopping conversation updates")),e.pageHiddenTimer=null},this.PAGE_HIDDEN_STOP_DELAY_MS)},p.handlePageVisible=function(){var e=this;null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.isActuallyHidden=!1,null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),this.pageVisibleStableTimer=window.setTimeout(function(){e.isPageVisible&&e.pendingConversationUpdate&&(e.config.debug&&console.log("[SDK] Page is stable visible, triggering conversation update"),e.flushConversationUpdate()),e.pageVisibleStableTimer=null},this.PAGE_VISIBLE_STABLE_MS)},p.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null)},p.destroy=function(){this.connectionClient&&(this.connectionClient.close(),this.connectionClient=void 0),this.cacheManager.destroy(),this.cleanupPageVisibilityDetection(),null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},this.config.debug&&console.log("[SDK] Resources destroyed")},p.getService=function(e){return this.serviceManager.get(e)},p.isConnected=function(){return this.config.debug&&console.log("[SDK] Connection status: "+(this.internalState.isConnected?"connected":"disconnected")),this.internalState.isConnected},p.isLoggedIn=function(){return this.config.debug&&console.log("[SDK] Login status: "+(this.internalState.isLoggedIn?"logged in":"not logged in")),this.internalState.isLoggedIn},p.logRequest=function(e){var t=Math.random().toString(36).substring(2,8),n={GET:"#4CAF50",POST:"#2196F3",PUT:"#FF9800",DELETE:"#F44336"}[e.method]||"#9C27B0",o={GET:"🔍",POST:"📝",PUT:"🔄",DELETE:"🗑️"}[e.method]||"📡";console.log("%c "+(new Date).toISOString().substring(11,19)+" %c SDK %c "+o+" "+e.method+" %c "+e.url+" %c #"+t,"color: #888; font-size: 11px; padding: 2px 0;","background: #7CAEFF; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","background: "+n+"; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","color: #0066cc; font-weight: bold;","color: #888; font-style: italic;"),e.data&&Object.keys(e.data).length>0&&(console.log("%c─── 📦 Request Payload ───────────────────────────────","color: #999; font-style: italic;"),console.log("%c%s","color: #333; background: #f8f8f8; padding: 8px; border-radius: 4px; border-left: 4px solid #7CAEFF; font-family: monospace; line-height: 1.5;",JSON.stringify(e.data,null,2)),console.log("%c─────────────────────────────────────────────────────","color: #999;"))},p.handlePongMessage=function(e){e&&e.timestamp&&(this.config.debug&&console.log("[SDK] Received pong message with timestamp:",e.timestamp),this.internalState.isConnected=!0,this.internalState.lastActivity=Date.now())},p.isBinaryMessage=function(e){return e instanceof Uint8Array||"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer||"string"==typeof e&&this.isBase64String(e)},p.normalizeToBinaryBuffer=function(e){if(e instanceof Uint8Array)return e;if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer)return new Uint8Array(e);if("string"==typeof e)try{for(var t=atob(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}catch(e){return null}return null},p.isBase64String=function(e){try{return btoa(atob(e))===e}catch(e){return!1}},p.protoGroupChatToMessageItem=function(e){var t,n,o,r=function(t){var n;return null!=(n=e[t])?n:e[t.replace(/([A-Z])/g,"_$1").toLowerCase()]},i=function(e){return Number(r(e))||0},s=function(e){var t;return String(null!=(t=r(e))?t:"")},a=null!=(t=e.avatar_map)?t:e.avatarMap,c=i("send"),u=null!=(n=null==a||null==(o=a[c])?void 0:o.avatar)?n:"";return{msgId:i("msg_id"),groupId:i("group_id"),groupType:i("group_type"),replyMsgId:i("reply_msg_id"),clientMsgId:s("client_msg_id"),recvId:s("recv_id"),receiverName:s("receiverName")||"",userId:i("userId")||0,send:c,to:i("to")||0,username:s("username"),msgType:i("msg_type"),text:s("text")||void 0,link:s("link")||void 0,snapshot:s("snapshot")||void 0,createTime:i("create_time"),updateTime:i("update_time")||void 0,status:i("status"),avatar:u||void 0}},p.handleProtobufMessage=function(e){try{var n,o,r=function(e){var t,n,r=Number(o.ev),s=null!=(n=((t={})[m.EVENT_PONG_CONN]="EVENT_PONG_CONN",t[m.EVENT_PONG_RE_CONN]="EVENT_PONG_RE_CONN",t[m.EVENT_PONG_IDLE]="EVENT_PONG_IDLE",t[m.EVENT_MESSAGE_PUSH]="EVENT_MESSAGE_PUSH",t[m.EVENT_SYSTEM_MESSAGE_PUSH]="EVENT_SYSTEM_MESSAGE_PUSH",t[m.EVENT_LIVE_SYSTEM_MESSAGE_PUSH]="EVENT_LIVE_SYSTEM_MESSAGE_PUSH",t[m.EVENT_PRE_MESSAGE_PUSH]="EVENT_PRE_MESSAGE_PUSH",t[m.EVENT_SUBSCRIBE_MESSAGE_PUSH]="EVENT_SUBSCRIBE_MESSAGE_PUSH",t)[r])?n:"ev="+r;switch(i.config.debug?console.log("[SDK] [Proto] 解码成功",{ev:r,evName:s,keys:Object.keys(o)}):console.log("[SDK] [Proto] ev=",s),r){case m.EVENT_PONG_IDLE:i.internalState.isConnected=!0,i.config.debug&&console.log("[SDK] [Proto] 心跳 PONG_IDLE,已更新 isConnected");break;case m.EVENT_MESSAGE_PUSH:var a,c,u=null!=(a=o.group_chat_list)?a:o.groupChatList,d=(null!=(c=null==u?void 0:u.items)?c:[]).map(function(e){return i.protoGroupChatToMessageItem(e)});i.config.debug&&console.log("[SDK] [Proto] EVENT_MESSAGE_PUSH",{count:d.length,msgIds:d.map(function(e){return e.msgId}),groupIds:[].concat(new Set(d.map(function(e){return e.groupId})))}),d.forEach(function(e){return i.updateMessageCache(e)}),i.emit(l.OnReceiveMessages,d);break;case m.EVENT_SYSTEM_MESSAGE_PUSH:var g,h=null!=(g=o.sys_message)?g:o.sysMessage;i.config.debug&&console.log("[SDK] [Proto] EVENT_SYSTEM_MESSAGE_PUSH",h),i.emit(l.OnReceiveSystemMessage,h);break;case m.EVENT_PRE_MESSAGE_PUSH:var p,f=null!=(p=o.raw_data)?p:o.rawData,v="string"==typeof f?f?JSON.parse(f):void 0:null!=f?JSON.parse((new TextDecoder).decode(f)):void 0;i.config.debug&&console.log("[SDK] [Proto] EVENT_PRE_MESSAGE_PUSH",v),i.emit(l.OnReceivePreMessage,v);break;case m.EVENT_SUBSCRIBE_MESSAGE_PUSH:var C,S=null!=(C=o.subscribe_message)?C:o.subscribeMessage;i.config.debug&&console.log("[SDK] [Proto] EVENT_SUBSCRIBE_MESSAGE_PUSH",S),i.emit(l.OnReceiveSubscribeMessage,S);break;default:console.warn("[SDK] [Proto] 未知 ev,回退 OnReceiveProtoMessage",{ev:r,evName:s}),i.emit(l.OnReceiveProtoMessage,o)}},i=this,s=e instanceof Uint8Array;if(i.config.debug&&console.log("[SDK] [Proto] 入口",{type:s?"Uint8Array":"Base64",length:s||"string"==typeof e?e.length:0,preview:s&&e.length>0?"0x"+e[0].toString(16):void 0}),s)n=e.length>1?e.slice(1):e,i.config.debug&&console.log("[SDK] [Proto] 跳过首字节后 buffer.length=",n.length);else{var a=atob(e);n=new Uint8Array(a.length);for(var c=0;c<a.length;c++)n[c]=a.charCodeAt(c);n.length>1&&(n=n.slice(1)),i.config.debug&&console.log("[SDK] [Proto] Base64 解码后 buffer.length=",n.length)}var u=w(function(){return Promise.resolve(function(e){return Promise.resolve(function(){try{var e=function(){if(!R)return Promise.resolve(t.load("/proto/chat_message.proto")).then(function(e){R=e})}();return Promise.resolve(e&&e.then?e.then(function(){return R}):R)}catch(e){return Promise.reject(e)}}()).then(function(t){var n=t.lookupType("com.chat.proto.SseMessage"),o=n.verify(e);if(o)throw new Error(o);var r=n.decode(e);return n.toObject(r,{longs:Number})})}(n)).then(function(e){o=e})},function(e){throw console.error("[SDK] [Proto] decodeSseMessage 失败",{bufferLength:n.length,error:e}),e});return Promise.resolve(u&&u.then?u.then(r):r())}catch(e){return Promise.reject(e)}},p.initializeConversationCache=function(){try{var e=this,t=w(function(){return Promise.resolve(e.conversation.getConversations({pageNo:1,pageSize:50})).then(function(t){var n=t.code,o=t.data;if(e.config.debug&&console.log("[SDK] Initialize conversation cache:",n,o),0===n&&o&&o.records){e.cacheManager.setConversations(o.records,!0);var r=e.cacheManager.getConversations();e.emit(l.OnConversationListUpdated,r),e.config.debug&&console.log("[SDK] Conversation cache initialized with",o.records.length,"conversations")}})},function(e){console.error("[SDK] Failed to initialize conversation cache:",e)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},p.onMessage=function(e){var t=this;return this.on(l.OnReceiveMessage,e),function(){return t.off(l.OnReceiveMessage,e)}},p.onMessages=function(e){var t=this;return this.on(l.OnReceiveMessages,e),function(){return t.off(l.OnReceiveMessages,e)}},p.onConnectionChange=function(e){var t=this,n=function(){return e(!0)},o=function(){return e(!1)};return this.on(l.OnConnected,n),this.on(l.OnDisconnected,o),function(){t.off(l.OnConnected,n),t.off(l.OnDisconnected,o)}},p.onKickedOffline=function(e){var t=this;return this.on(l.OnKickedOffline,e),function(){return t.off(l.OnKickedOffline,e)}},p.updateMessageCache=function(e){e.groupId&&this.cacheManager.addGroupMessage(e),this.cacheManager.updateConversationWithMessage(e,this.config.username)&&this.scheduleConversationUpdate()},p.scheduleConversationUpdate=function(){var e=this;if(this.pendingConversationUpdate=!0,this.isActuallyHidden)this.config.debug&&console.log("[SDK] Page is actually hidden, deferring conversation update");else{var t=Date.now()-this.lastConversationUpdateTime;if(t<this.CONVERSATION_UPDATE_THROTTLE_MS){if(null!==this.conversationUpdateTimer)return;this.conversationUpdateTimer=window.setTimeout(function(){e.flushConversationUpdate()},this.CONVERSATION_UPDATE_THROTTLE_MS-t)}else this.flushConversationUpdate()}},p.flushConversationUpdate=function(){null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.pendingConversationUpdate=!1,this.lastConversationUpdateTime=Date.now();var e=this.cacheManager.getConversations();this.emit(l.OnConversationListUpdated,e),this.config.debug&&console.log("[SDK] Conversation list updated, count:",e.length)},p.getCachedGroupMessages=function(e){return this.cacheManager.getGroupMessages(e)},g=n,(h=[{key:"message",get:function(){return this.getService(a.MESSAGE)}},{key:"conversation",get:function(){return this.getService(a.CONVERSATION)}},{key:"group",get:function(){return this.getService(a.GROUP)}},{key:"user",get:function(){return this.getService(a.USER)}},{key:"contact",get:function(){return this.getService(a.CONTACT)}},{key:"username",get:function(){return this.config.username}},{key:"getConfig",get:function(){return this.config}},{key:"getConnectionClient",get:function(){return this.connectionClient}},{key:"uuid",get:function(){return(36*Math.random()).toString(36).slice(2)+(new Date).getTime().toString()}}])&&function(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,s(o.key),o)}}(g.prototype,h),Object.defineProperty(g,"prototype",{writable:!1}),g}(C);V.BINARY_MSG_TYPE={BYTE_MESSAGE:1,HEARTBEAT_PING:125,HEARTBEAT_PONG:126};export{l as CbEvents,v as ConnectionProtocol,c as ContactType,u as ErrorCode,p as GroupMemberEventType,g as GroupType,h as MessageType,d as RequestApi,V as SIMSDK,a as ServiceName,m as SseEventType,f as SystemMessageType};