easemob-websdk 5.0.1 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/chat-client.d.ts +25 -12
  3. package/chunks/chat-manager-DCqgMxLm.js +2 -0
  4. package/chunks/chat-manager-D_KF5qM1.cjs +1 -0
  5. package/chunks/{common-BW2KLpvb.js → common-D_DfwSd3.js} +1 -1
  6. package/chunks/{group-user-info-resolver-Diqjmjyj.js → group-user-info-resolver-lEtRdWli.js} +1 -1
  7. package/chunks/index-BmwQgZ3E.js +1 -0
  8. package/chunks/index-BsIqq7LU.cjs +1 -0
  9. package/chunks/index-CFMcR5a_.js +1 -0
  10. package/chunks/index-Dvvh1nf6.cjs +1 -0
  11. package/chunks/light-Dg9A1Xmd.js +1 -0
  12. package/chunks/light-dJjIln5b.cjs +1 -0
  13. package/chunks/reflection-proto-codec-BerStgkC.cjs +1 -0
  14. package/chunks/reflection-proto-codec-CjRraw85.js +1 -0
  15. package/chunks/{session-list-query-DtoToipt.js → session-list-query-rynxSxtv.js} +1 -1
  16. package/chunks/{user-info-22jZtcSi.js → user-info-DfbCp80h.js} +1 -1
  17. package/index.cjs +1 -1
  18. package/index.js +2 -2
  19. package/managers/chat/index.cjs +1 -1
  20. package/managers/chat/index.js +1 -1
  21. package/managers/chat-manager.d.ts +3 -2
  22. package/managers/chat-thread/index.js +1 -1
  23. package/managers/chat-thread-manager.d.ts +3 -2
  24. package/managers/chatroom/index.js +1 -1
  25. package/managers/contact/index.cjs +1 -1
  26. package/managers/contact/index.js +1 -1
  27. package/managers/group/index.cjs +1 -1
  28. package/managers/group/index.js +1 -1
  29. package/managers/presence/index.js +1 -1
  30. package/managers/push/index.js +1 -1
  31. package/managers/user-info/index.js +1 -1
  32. package/package.json +1 -1
  33. package/rest/dns-config.d.ts +10 -2
  34. package/types/chat-client.d.ts +28 -3
  35. package/validators/chat-client.d.ts +13 -5
  36. package/chunks/chat-manager-5wHx7UeW.cjs +0 -1
  37. package/chunks/chat-manager-DdAnJpcH.js +0 -2
  38. package/chunks/index-BItCF8E7.cjs +0 -1
  39. package/chunks/index-DKksD5YM.js +0 -1
  40. package/chunks/index-DKmdsV1-.cjs +0 -1
  41. package/chunks/index-VEUtqiDw.js +0 -1
  42. package/chunks/reflection-proto-codec-64ocOTHU.js +0 -1
  43. package/chunks/reflection-proto-codec-BnQFQdZC.cjs +0 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/chat-manager-5wHx7UeW.cjs");exports.ChatManager=e.ChatManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/chat-manager-D_KF5qM1.cjs");exports.ChatManager=e.ChatManager;
@@ -1 +1 @@
1
- import{C as a}from"../../chunks/chat-manager-DdAnJpcH.js";export{a as ChatManager};
1
+ import{C as a}from"../../chunks/chat-manager-DCqgMxLm.js";export{a as ChatManager};
@@ -277,8 +277,9 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
277
277
  */
278
278
  getCurrentConversation(): ConversationLocator | null;
279
279
  /**
280
- * [zh-CN] 主动向服务端刷新会话列表,并返回刷新后的会话列表。
281
- * [en-US] Refreshes the conversation list from the server and returns the updated conversation list.
280
+ * @internal
281
+ * [zh-CN] 主动向服务端刷新会话列表,供 SDK 内部同步流程使用。
282
+ * [en-US] Refreshes the conversation list from the server for internal SDK synchronization flows.
282
283
  *
283
284
  * @example
284
285
  * ```ts
@@ -1 +1 @@
1
- import{p as e,V as t,E as r,f as a,S as s,m as o,i as n}from"../../chunks/common-BW2KLpvb.js";import{i,s as d}from"../../chunks/cache-utils-B99glc0H.js";import{c as h}from"../../chunks/query-params-Bu3Xq4b6.js";class u{constructor(e,t){this.chatThreadId=e,this.manager=t}getInfo(){return this.manager.getChatThreadInfo({chatThreadId:this.chatThreadId})}refresh(){return this.getInfo()}join(){return this.manager.joinChatThread({chatThreadId:this.chatThreadId})}leave(){return this.manager.leaveChatThread({chatThreadId:this.chatThreadId})}destroy(){return this.manager.destroyChatThread({chatThreadId:this.chatThreadId})}updateName(e){return this.manager.updateChatThreadName({chatThreadId:this.chatThreadId,name:e.name})}getMemberList(e={}){return this.manager.getChatThreadMemberList({chatThreadId:this.chatThreadId,...e})}removeMember(e){return this.manager.removeChatThreadMember({chatThreadId:this.chatThreadId,memberId:e.memberId})}}const c=e=>new t(`${e} is required`,{code:r.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),l=(e,a)=>new t(a,{code:r.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:a,rule:"invalid_format"}]}}),p=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw c(t);return e.trim()},m=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw l(t,`${t} must be a string`);return e},g=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw l(t,`${t} must be an integer between 1 and 50`);return e},_=t=>{const{orgName:r,appName:a}=e(t.appKey);return{orgName:r,appName:a,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},y=e=>i(e)?e:null,T=e=>{const t=y(e);return t?.data??e},v=e=>{const t=y(e);if(Array.isArray(t?.entities))return t.entities;const r=T(e);if(Array.isArray(r))return r;const a=y(r);return Array.isArray(a?.entities)?a.entities:Array.isArray(a?.affiliations)?a.affiliations:[]},f=e=>{const t=y(e),r=y(t?.data),a=y(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof a?.cursor?a.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},b=e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const a="number"==typeof t.timestamp?t.timestamp:0,s=t.payload,o="string"==typeof s?d(s,{}):y(s)??{},n=Array.isArray(o.bodies)?o.bodies:[],i=y(n[0])??{};return{msgId:r,type:("string"==typeof i.type?i.type:void 0)??("string"==typeof o.type?o.type:void 0)??"",body:i,timestamp:a}},I=e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0)??("string"==typeof t.chatThreadId?t.chatThreadId:void 0),a=("string"==typeof t.parentId?t.parentId:void 0)??("string"==typeof t.groupId?t.groupId:void 0)??("string"==typeof t.group_id?t.group_id:void 0),s="string"==typeof t.name?t.name:"";return r&&a&&s?{chatThreadId:r,parentId:a,name:s,ownerId:"string"==typeof t.owner?t.owner:void 0,memberCount:"number"==typeof t.affiliationsCount?t.affiliationsCount:"number"==typeof t.affiliations_count?t.affiliations_count:void 0,messageCount:"number"==typeof t.messageCount?t.messageCount:"number"==typeof t.message_count?t.message_count:void 0,createdAt:"number"==typeof t.created?t.created:"number"==typeof t.createTimestamp?t.createTimestamp:void 0,lastMessage:b(t.lastMessage??t.last_message)}:null},C=e=>({items:v(e).map(e=>I(e)).filter(e=>null!==e),cursor:f(e)}),N=async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");return(e=>{const t=T(e),r=Array.isArray(t)?t[0]:t,a=I(r);if(!a)throw l("response.data","response.data is invalid");return a})(await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}`,{operation:"getChatThreadInfo"}))},w=async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=g(r.pageSize,"params.pageSize"),n=m(r.cursor,"params.cursor"),i=h({limit:String(o),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users?${i.toString()}`,{operation:"getChatThreadMemberList"});return{items:v(u=d).map(e=>{if("string"==typeof e)return{memberId:e};const t=y(e);if(!t)return null;const r=("string"==typeof t.memberId?t.memberId:void 0)??("string"==typeof t.user?t.user:void 0)??("string"==typeof t.username?t.username:void 0);return r?{memberId:r,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null}).filter(e=>null!==e),cursor:f(u)};var u},S=async(e,t,r)=>{const a=_(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw c("params.chatThreadIds");if(r.chatThreadIds.length>20)throw l("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const s=r.chatThreadIds.map((e,t)=>p(e,`params.chatThreadIds[${t}]`)),o=await e.post(`/${a.orgName}/${a.appName}/thread/message`,{threadIds:s},{operation:"getChatThreadLastMessageList"});return{items:v(o).map(e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.chatThreadId?t.chatThreadId:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0);return r?{chatThreadId:r,lastMessage:b(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},R=o(n,{common:{},apis:{createChatThread:{range:"4,110,201,210,301,303,606",localErrors:{createChatThread:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getJoinedChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getJoinedChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadInfo:{range:"110,201,210,301,303,606",localErrors:{getChatThreadInfo:{validation_invalid:{code:110,retryable:!1}},getInfo:{validation_invalid:{code:110,retryable:!1}},refresh:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},joinChatThread:{range:"4,110,201,210,301,303,606",localErrors:{joinChatThread:{validation_invalid:{code:110,retryable:!1}},join:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},leaveChatThread:{range:"110,201,210,301,303,606",localErrors:{leaveChatThread:{validation_invalid:{code:110,retryable:!1}},leave:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},destroyChatThread:{range:"110,201,210,301,303,606",localErrors:{destroyChatThread:{validation_invalid:{code:110,retryable:!1}},destroy:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},updateChatThreadName:{range:"110,201,210,301,303,606",localErrors:{updateChatThreadName:{validation_invalid:{code:110,retryable:!1}},updateName:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadMemberList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadMemberList:{validation_invalid:{code:110,retryable:!1}},getMemberList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},removeChatThreadMember:{range:"110,201,210,301,303,606",localErrors:{removeChatThreadMember:{validation_invalid:{code:110,retryable:!1}},removeMember:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadLastMessageList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadLastMessageList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}}}}),O=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=/* @__PURE__ */new Map}bind(e,t){this.client=e,this.eventContext=t??null,this.registry.clear()}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}handleRawNotify(e){if("chatThread"!==e.type)return;const t=this.buildChatThreadPublicEvent(e.payload);t&&this.eventContext?.dispatch?.(t.eventName,t.payload)}getChatThread(e){const a=e.trim();if(0===a.length)throw new t("chatThreadId is required",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const s=this.registry.get(a);if(s)return s;const o=new u(a,this);return this.registry.set(a,o),o}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=_(t),s=p(r.parentId,"params.parentId"),o=p(r.name,"params.name"),n=p(r.messageId,"params.messageId"),i=await e.post(`/${a.orgName}/${a.appName}/thread?resource=${a.encodedResource}`,{name:o,msg_id:n,group_id:s,owner:t.userId},{operation:"createChatThread"}),d=y(T(i)),h="string"==typeof d?.thread_id?d.thread_id:void 0;if(!h)throw l("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:h}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=_(t),s=p(r.parentId,"params.parentId"),o=g(r.pageSize,"params.pageSize"),n=m(r.cursor,"params.cursor"),i=h({limit:String(o),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(s)}?${i.toString()}`,{operation:"getChatThreadList"});return C(d)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const a=_(t),s=g(r.pageSize,"params.pageSize"),o=m(r.cursor,"params.cursor"),n=h({limit:String(s),cursor:o}),i="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${a.encodedUserId}?${n.toString()}`:`/${a.orgName}/${a.appName}/threads/user/${a.encodedUserId}?${n.toString()}`,d=await e.get(i,{operation:"getJoinedChatThreadList"});return C(d)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return N(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.post(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/join?resource=${a.encodedResource}`,void 0,{operation:"joinChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async leaveChatThread(e){return this.runOperation("leaveChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/quit?resource=${a.encodedResource}`,{operation:"leaveChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async destroyChatThread(e){return this.runOperation("destroyChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{operation:"destroyChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async updateChatThreadName(e){return this.runOperation("updateChatThreadName",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=p(r.name,"params.name");await e.put(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{name:o},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return w(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=p(r.memberId,"params.memberId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users/${encodeURIComponent(o)}?resource=${a.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return S(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new t("ChatThreadManager is not bound to client",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.client",message:"ChatThreadManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getEventContextOrThrow(){if(!this.eventContext)throw new t("ChatThreadManager is not bound to event context",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new a(e.restBaseUrl,{errorMap:R,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}async runOperation(e,t){try{return await t()}catch(a){if(a instanceof s)throw a;const t=a instanceof Error?a.message:String(a);throw new s(`ChatThreadManager ${e} failed: ${t}`,r.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",a="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!a)return null;const s="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,o="string"==typeof t.name?t.name:void 0,n="number"==typeof t.message_count?t.message_count:void 0,i=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,d="number"==typeof t.timestamp?t.timestamp:0,h="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:a,name:o??"",messageId:s,messageCount:n,lastMessage:i};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,thread:u,timestamp:d}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,messageCount:n,lastMessage:i,thread:u,timestamp:d}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:a,operatorId:h,timestamp:d}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:a,operatorId:h,memberId:t.userIds?.[0],timestamp:d}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};O.key="chatThreadManager";let $=O;export{u as ChatThread,$ as ChatThreadManager};
1
+ import{p as e,V as t,E as r,f as a,S as s,m as o,i as n}from"../../chunks/common-D_DfwSd3.js";import{i,s as d}from"../../chunks/cache-utils-B99glc0H.js";import{c as h}from"../../chunks/query-params-Bu3Xq4b6.js";class u{constructor(e,t){this.chatThreadId=e,this.manager=t}getInfo(){return this.manager.getChatThreadInfo({chatThreadId:this.chatThreadId})}refresh(){return this.getInfo()}join(){return this.manager.joinChatThread({chatThreadId:this.chatThreadId})}leave(){return this.manager.leaveChatThread({chatThreadId:this.chatThreadId})}destroy(){return this.manager.destroyChatThread({chatThreadId:this.chatThreadId})}updateName(e){return this.manager.updateChatThreadName({chatThreadId:this.chatThreadId,name:e.name})}getMemberList(e={}){return this.manager.getChatThreadMemberList({chatThreadId:this.chatThreadId,...e})}removeMember(e){return this.manager.removeChatThreadMember({chatThreadId:this.chatThreadId,memberId:e.memberId})}}const c=e=>new t(`${e} is required`,{code:r.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),l=(e,a)=>new t(a,{code:r.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:a,rule:"invalid_format"}]}}),p=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw c(t);return e.trim()},m=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw l(t,`${t} must be a string`);return e},g=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw l(t,`${t} must be an integer between 1 and 50`);return e},_=t=>{const{orgName:r,appName:a}=e(t.appKey);return{orgName:r,appName:a,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},y=e=>i(e)?e:null,T=e=>{const t=y(e);return t?.data??e},v=e=>{const t=y(e);if(Array.isArray(t?.entities))return t.entities;const r=T(e);if(Array.isArray(r))return r;const a=y(r);return Array.isArray(a?.entities)?a.entities:Array.isArray(a?.affiliations)?a.affiliations:[]},f=e=>{const t=y(e),r=y(t?.data),a=y(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof a?.cursor?a.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},b=e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const a="number"==typeof t.timestamp?t.timestamp:0,s=t.payload,o="string"==typeof s?d(s,{}):y(s)??{},n=Array.isArray(o.bodies)?o.bodies:[],i=y(n[0])??{};return{msgId:r,type:("string"==typeof i.type?i.type:void 0)??("string"==typeof o.type?o.type:void 0)??"",body:i,timestamp:a}},I=e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0)??("string"==typeof t.chatThreadId?t.chatThreadId:void 0),a=("string"==typeof t.parentId?t.parentId:void 0)??("string"==typeof t.groupId?t.groupId:void 0)??("string"==typeof t.group_id?t.group_id:void 0),s="string"==typeof t.name?t.name:"";return r&&a&&s?{chatThreadId:r,parentId:a,name:s,ownerId:"string"==typeof t.owner?t.owner:void 0,memberCount:"number"==typeof t.affiliationsCount?t.affiliationsCount:"number"==typeof t.affiliations_count?t.affiliations_count:void 0,messageCount:"number"==typeof t.messageCount?t.messageCount:"number"==typeof t.message_count?t.message_count:void 0,createdAt:"number"==typeof t.created?t.created:"number"==typeof t.createTimestamp?t.createTimestamp:void 0,lastMessage:b(t.lastMessage??t.last_message)}:null},C=e=>({items:v(e).map(e=>I(e)).filter(e=>null!==e),cursor:f(e)}),N=async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");return(e=>{const t=T(e),r=Array.isArray(t)?t[0]:t,a=I(r);if(!a)throw l("response.data","response.data is invalid");return a})(await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}`,{operation:"getChatThreadInfo"}))},w=async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=g(r.pageSize,"params.pageSize"),n=m(r.cursor,"params.cursor"),i=h({limit:String(o),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users?${i.toString()}`,{operation:"getChatThreadMemberList"});return{items:v(u=d).map(e=>{if("string"==typeof e)return{memberId:e};const t=y(e);if(!t)return null;const r=("string"==typeof t.memberId?t.memberId:void 0)??("string"==typeof t.user?t.user:void 0)??("string"==typeof t.username?t.username:void 0);return r?{memberId:r,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null}).filter(e=>null!==e),cursor:f(u)};var u},S=async(e,t,r)=>{const a=_(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw c("params.chatThreadIds");if(r.chatThreadIds.length>20)throw l("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const s=r.chatThreadIds.map((e,t)=>p(e,`params.chatThreadIds[${t}]`)),o=await e.post(`/${a.orgName}/${a.appName}/thread/message`,{threadIds:s},{operation:"getChatThreadLastMessageList"});return{items:v(o).map(e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.chatThreadId?t.chatThreadId:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0);return r?{chatThreadId:r,lastMessage:b(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},R=o(n,{common:{},apis:{createChatThread:{range:"4,110,201,210,301,303,606",localErrors:{createChatThread:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getJoinedChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getJoinedChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadInfo:{range:"110,201,210,301,303,606",localErrors:{getChatThreadInfo:{validation_invalid:{code:110,retryable:!1}},getInfo:{validation_invalid:{code:110,retryable:!1}},refresh:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},joinChatThread:{range:"4,110,201,210,301,303,606",localErrors:{joinChatThread:{validation_invalid:{code:110,retryable:!1}},join:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},leaveChatThread:{range:"110,201,210,301,303,606",localErrors:{leaveChatThread:{validation_invalid:{code:110,retryable:!1}},leave:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},destroyChatThread:{range:"110,201,210,301,303,606",localErrors:{destroyChatThread:{validation_invalid:{code:110,retryable:!1}},destroy:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},updateChatThreadName:{range:"110,201,210,301,303,606",localErrors:{updateChatThreadName:{validation_invalid:{code:110,retryable:!1}},updateName:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadMemberList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadMemberList:{validation_invalid:{code:110,retryable:!1}},getMemberList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},removeChatThreadMember:{range:"110,201,210,301,303,606",localErrors:{removeChatThreadMember:{validation_invalid:{code:110,retryable:!1}},removeMember:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadLastMessageList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadLastMessageList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}}}}),O=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=/* @__PURE__ */new Map}bind(e,t){this.client=e,this.eventContext=t??null,this.registry.clear()}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}handleRawNotify(e){if("chatThread"!==e.type)return;const t=this.buildChatThreadPublicEvent(e.payload);t&&this.eventContext?.dispatch?.(t.eventName,t.payload)}getChatThread(e){const a=e.trim();if(0===a.length)throw new t("chatThreadId is required",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const s=this.registry.get(a);if(s)return s;const o=new u(a,this);return this.registry.set(a,o),o}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=_(t),s=p(r.parentId,"params.parentId"),o=p(r.name,"params.name"),n=p(r.messageId,"params.messageId"),i=await e.post(`/${a.orgName}/${a.appName}/thread?resource=${a.encodedResource}`,{name:o,msg_id:n,group_id:s,owner:t.userId},{operation:"createChatThread"}),d=y(T(i)),h="string"==typeof d?.thread_id?d.thread_id:void 0;if(!h)throw l("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:h}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=_(t),s=p(r.parentId,"params.parentId"),o=g(r.pageSize,"params.pageSize"),n=m(r.cursor,"params.cursor"),i=h({limit:String(o),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(s)}?${i.toString()}`,{operation:"getChatThreadList"});return C(d)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const a=_(t),s=g(r.pageSize,"params.pageSize"),o=m(r.cursor,"params.cursor"),n=h({limit:String(s),cursor:o}),i="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${a.encodedUserId}?${n.toString()}`:`/${a.orgName}/${a.appName}/threads/user/${a.encodedUserId}?${n.toString()}`,d=await e.get(i,{operation:"getJoinedChatThreadList"});return C(d)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return N(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.post(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/join?resource=${a.encodedResource}`,void 0,{operation:"joinChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async leaveChatThread(e){return this.runOperation("leaveChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/quit?resource=${a.encodedResource}`,{operation:"leaveChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async destroyChatThread(e){return this.runOperation("destroyChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{operation:"destroyChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async updateChatThreadName(e){return this.runOperation("updateChatThreadName",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=p(r.name,"params.name");await e.put(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{name:o},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return w(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=p(r.memberId,"params.memberId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users/${encodeURIComponent(o)}?resource=${a.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return S(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new t("ChatThreadManager is not bound to client",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.client",message:"ChatThreadManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getEventContextOrThrow(){if(!this.eventContext)throw new t("ChatThreadManager is not bound to event context",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new a(e.restBaseUrl,{errorMap:R,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}async runOperation(e,t){try{return await t()}catch(a){if(a instanceof s)throw a;const t=a instanceof Error?a.message:String(a);throw new s(`ChatThreadManager ${e} failed: ${t}`,r.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",a="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!a)return null;const s="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,o="string"==typeof t.name?t.name:void 0,n="number"==typeof t.message_count?t.message_count:void 0,i=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,d="number"==typeof t.timestamp?t.timestamp:0,h="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:a,name:o??"",messageId:s,messageCount:n,lastMessage:i};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,thread:u,timestamp:d}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,messageCount:n,lastMessage:i,thread:u,timestamp:d}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:a,operatorId:h,timestamp:d}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:a,operatorId:h,memberId:t.userIds?.[0],timestamp:d}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};O.key="chatThreadManager";let $=O;export{u as ChatThread,$ as ChatThreadManager};
@@ -16,10 +16,11 @@ export declare class ChatThreadManager implements ManagerBase<ChatClient> {
16
16
  private restBaseUrl;
17
17
  private restToken;
18
18
  private readonly registry;
19
+ /** @internal SDK 管理器注册流程使用,不作为公开 API。 */
19
20
  bind(client: ChatClient, context?: ManagerEventContext): void;
20
21
  /**
21
- * [zh-CN] 注册 ChatThread 事件处理器。只包含移动端对齐的 4 个公开事件,不包含 `onChatThreadChange`。
22
- * [en-US] Registers message thread event handlers. Only the four mobile-aligned public events are supported; `onChatThreadChange` is not exposed.
22
+ * [zh-CN] 注册 ChatThread 事件处理器。
23
+ * [en-US] Registers ChatThread event handlers.
23
24
  *
24
25
  * @example [zh-CN] 调用示例(监听消息话题创建) [en-US] Usage example (listen for thread creation)
25
26
  * ```ts
@@ -1 +1 @@
1
- import{E as e,p as t,V as r,l as o,S as a,f as s,m as n,i}from"../../chunks/common-BW2KLpvb.js";import{b as c}from"../../chunks/event-system-D6IJA0C4.js";import{c as u}from"../../chunks/query-params-Bu3Xq4b6.js";import{i as m}from"../../chunks/cache-utils-B99glc0H.js";import{b as h,a as d,n as l}from"../../chunks/user-info-22jZtcSi.js";class p{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const R=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],g=e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},I=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),y=e=>({userId:e}),f=(e,t,r)=>{const o={userId:r};for(const a of R){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},b=async(e,t)=>{const r=g(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const a=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const n of a)o.set(n.userId,I(n));const s=r.filter(e=>!o.has(e));if(s.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:s});for(const t of e)o.set(t.userId,t)}for(const n of r)o.has(n)||o.set(n,y(n));return o},C=e=>m(e)?e:null,w=e=>"string"==typeof e?e:void 0,_=e=>{const t=w(e)?.trim();return t||void 0},A=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},M=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},v=e=>{const t=C(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},U=e=>{const t=C(e);return t?C(t.data)?t.data:t:null},E=(e,t)=>{const r=C(e),o=r&&C(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return A(a[0])},S=e=>_(e.chatRoomId)??_(e.chatroomid)??_(e.id)??"",O=e=>w(e.name)??w(e.title)??w(e.groupname)??"",T=e=>y(e),x=(e,t)=>{const r=C(e);if(!r)return null;const o=S(r);if(!o)return null;const a=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(_(r.owner)):_(r.owner);return{chatRoomId:o,name:O(r),owner:a?T(a):void 0,memberCount:A(r.memberCount)??A(r.affiliations_count),disabled:M(r.disabled)}},k=(e,t)=>{const r=(e=>{const t=C(e);return t?A(t.count):void 0})(e),o=v(e).map(e=>x(e,t)).filter(e=>null!==e),a=E(e,"pagenum"),s=E(e,"pagesize");return{items:o,pageNum:a,pageSize:s,total:r,hasMore:void 0!==r&&void 0!==a&&void 0!==s?a*s<r:void 0}},$=(e,t)=>{const r=v(e),o=C(r[0])??U(e)??{},a=x(o)??{chatRoomId:S(o),name:O(o)},s=((e,t)=>{if(!t)return;if(_(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const o of r){const e=C(o);if(e){if(_(e.owner)===t)return"owner";if(_(e.admin)===t)return"admin";if(_(e.member)===t)return"member"}}})(o,t),n=A(o.muteExpireAt)??A(o.mute_expire)??A(o.expire),i=M(o.inAllowlist)??M(o.white)??M(o.in_whitelist),c=M(o.muted);return{...a,description:w(o.description),maxMembers:A(o.maxMembers)??A(o.maxusers)??A(o.max_users),createdAt:A(o.createdAt)??A(o.created),ext:w(o.ext)??w(o.custom),announcement:w(o.announcement),permissionType:s,currentUserStatus:void 0!==i||void 0!==c||void 0!==n||void 0!==s?{inAllowlist:i,muted:c,muteExpireAt:n,permissionType:s}:void 0}},L=e=>v(e).map(e=>_(e)).filter(e=>Boolean(e)).map(e=>T(e)),N=(e,t)=>{const r=U(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=C(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:F(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},D=e=>{const t=C(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=C(e),r=(e=>{const t=C(e);if(!t)return null;const r=_(t.user),o=_(t.chatRoomId)??_(t.chatroomid)??_(t.id),a=w(t.action),s=M(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:T(r),action:a,reason:w(t.reason),...s?{}:{reason:w(t.reason)??"failed"}}:null})(e);if(!r||!t)return;M(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},F=t=>t.includes("is exceeding maximum limit")||t.includes("size of metadata")&&t.includes("exceeds")?e.SERVICE_LIMIT_EXCEEDED:t.includes("is not part of you")?e.CHATROOM_PERMISSION_DENIED:t.includes("is not Legal")||t.includes("is not exist")?e.VALIDATION_REQUIRED:e.REST_BUSINESS_UNKNOWN,B=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},z=t=>new r(`${t} is required`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),j=(t,o)=>new r(o,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:o,rule:"invalid_format"}]}}),V=(e,t)=>`/${e.orgName}/${e.appName}${t}`,q=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw j(t,`${t} must be a string`);return e}},P=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw j(t,`${t} must be a number`);return e}},W=(e,t)=>{const r=u();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const o=r.toString();return o?`?${o}`:""},H=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw z(t);return e.trim()},K=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw z(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw j(`${t}[${a}]`,`${t}[${a}] must be a string`);const s=e.trim();s&&!o.has(s)&&(o.add(s),r.push(s))}),0===r.length)throw z(t);return r},G=(e,t)=>K(e,t),Q=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s={},n=q(r.name,"params.name"),i=q(r.description,"params.description"),c=P(r.maxMembers,"params.maxMembers");if(void 0!==n&&(s.groupname=n),void 0!==i&&(s.description=i),void 0!==c&&(s.maxusers=c),0===Object.keys(s).length)throw z("params");const u=V(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=U(e)??{};return{nameUpdated:M(t.groupname),descriptionUpdated:M(t.description),maxMembersUpdated:M(t.maxusers)}})(await e.put(u,s,{operation:"updateChatRoomInfo"}))},J=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/users${(e=>{const t=u();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const a of v(e)){const e=C(a);if(!e)continue;const r=_(e.owner),o=_(e.admin),s=_(e.member),n=r??o??s;n&&t.push({user:T(n),role:r?"owner":o?"admin":"member",joinedAt:A(e.joinedAt)??A(e.joined_time)})}const r=C(e),o=r?_(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(s,{operation:"getChatRoomMemberList"}))},X=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return L(n)},Y=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=u();s.set("version","v3"),"number"==typeof r.pageNum&&s.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&s.set("pagesize",String(r.pageSize));const n=V(o,`/chatrooms/${encodeURIComponent(a)}/mute?${s.toString()}`);return(e=>{const t=v(e);if(t.every(e=>"string"==typeof e))return L(e).map(e=>({user:e}));const r=[];for(const o of t){const e=C(o);if(!e)continue;const t=_(e.user)??_(e.member)??_(e.owner)??_(e.admin);t&&r.push({user:T(t),muteExpire:A(e.muteExpire)??A(e.expire)??A(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(n,{operation:"getChatRoomMuteList"}))},Z=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return{muted:M(t.muted)??M(t.value)??Boolean(t.data),muteExpireAt:A(t.muteExpireAt)??A(t.expire)??A(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},ee=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=W(r),n=s?"&":"",i=V(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return L(c).map(e=>({user:e}))},te=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return L(n).map(e=>({user:e}))},re=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return M(t.value)??M(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},oe=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=U(e)??{};return{announcement:w(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},ae=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=U(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?G(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},se=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw j(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw z(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw j(t,`${t} contains invalid key`);if("string"!=typeof r)throw j(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:n=!0,isForced:i=!1}=r,c=i?"/forced":"",u=V(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),m=await e.put(u,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return N(m,a)},ne={onChatRoomDestroyed:c.CHAT_ROOM_DESTROYED,onMembersJoined:c.MEMBERS_JOINED,onMembersExited:c.MEMBERS_EXITED,onRemovedFromChatRoom:c.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:c.MUTE_LIST_ADDED,onMuteListRemoved:c.MUTE_LIST_REMOVED,onAllowListAdded:c.ALLOW_LIST_ADDED,onAllowListRemoved:c.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:c.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:c.ADMIN_ADDED,onAdminRemoved:c.ADMIN_REMOVED,onOwnerChanged:c.OWNER_CHANGED,onAnnouncementChanged:c.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:c.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:c.ATTRIBUTES_UPDATE,onAttributesRemoved:c.ATTRIBUTES_REMOVED},ie=n(i,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),ce=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=/* @__PURE__ */new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=ne[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const o=ne[t.eventName];o&&this.eventContext?.dispatch?.(o,r)}async buildIncomingEventPayload(e,t){const r=t.payload,o=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,o)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,o),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,o)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,o)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,o)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,o),oldOwner:this.pickEventUser(r.oldOwnerId,o)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,o)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,o)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const o=B(t),a=V(o,`/chatrooms${W(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return k(s)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(t){this.requireClient();const o=t.trim();if(0===o.length)throw new r("chatRoomId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const a=this.chatRoomRegistry.get(o);if(a)return a;const s=new p(o,this);return this.chatRoomRegistry.set(o,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true`),n=await e.get(s,{operation:"getChatRoomInfo"});return $(n,t.userId)})(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return Q(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=H(e.chatRoomId,"params.chatRoomId"),o=this.normalizeOptionalString(e.ext,"params.ext"),a=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:o,leaveOtherRooms:a})).chatRoomInfo??{}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=H(e.chatRoomId,"params.chatRoomId");await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await J(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await X(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=H(r.userId,"params.userId"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/admin?resource=${o.encodedResource}`);await e.post(n,{newadmin:s},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=H(r.userId,"params.userId"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/admin/${encodeURIComponent(s)}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await Y(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=P(r.duration,"params.duration"),i=V(o,`/chatrooms/${encodeURIComponent(a)}/mute?resource=${o.encodedResource}`);await e.post(i,{usernames:s,mute_duration:n},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return Z(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await ee(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=1===s.length,i=V(o,n?`/chatrooms/${encodeURIComponent(a)}/blocks/users/${encodeURIComponent(s[0]??"")}?resource=${o.encodedResource}`:`/chatrooms/${encodeURIComponent(a)}/blocks/users?resource=${o.encodedResource}`),c=await e.post(i,n?void 0:{usernames:s},{operation:"blockChatRoomMembers"});return D(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await te(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return re(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return oe(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=q(r.announcement,"params.announcement");if(void 0===s)throw z("params.announcement");const n=V(o,`/chatrooms/${encodeURIComponent(a)}/announcement?resource=${o.encodedResource}`);await e.post(n,{announcement:s},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return ae(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await se(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=G(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=V(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),u=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return N(u,a)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw o.warn(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(t,r){return r instanceof a?r:r instanceof Error?new a(`ChatRoomManager ${t} failed: ${r.message}`,e.UNKNOWN):new a(`ChatRoomManager ${t} failed`,e.UNKNOWN)}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new a(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new s(e.restBaseUrl,{errorMap:ie,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new a("ChatRoomManager is not bound to client",e.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(t,o){if(void 0!==t){if("string"!=typeof t)throw new r(`${o} must be a string`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} must be a string`,rule:"invalid_format"}]}});return t}}normalizeOptionalBoolean(t,o){if(void 0!==t){if("boolean"!=typeof t)throw new r(`${o} must be a boolean`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} must be a boolean`,rule:"invalid_format"}]}});return t}}getCacheManager(){return this.client?.getCacheManager()??null}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return b(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=g(e),o=await b(r,t);return r.map(e=>f(void 0,o.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=h(e),o=await this.getRestClient(t).request(d(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return l(o,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],o=[],a=/* @__PURE__ */new Set;for(const s of r){if("string"!=typeof s)continue;const e=s.trim();e&&!a.has(e)&&(a.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return f(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>f(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){o.warn("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:f(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:f(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:f(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ce.key="chatRoomManager";let ue=ce;export{p as ChatRoom,ue as ChatRoomManager};
1
+ import{E as e,p as t,V as r,l as o,S as a,f as s,m as n,i}from"../../chunks/common-D_DfwSd3.js";import{b as c}from"../../chunks/event-system-D6IJA0C4.js";import{c as u}from"../../chunks/query-params-Bu3Xq4b6.js";import{i as m}from"../../chunks/cache-utils-B99glc0H.js";import{b as h,a as d,n as l}from"../../chunks/user-info-DfbCp80h.js";class p{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const R=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],g=e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},I=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),y=e=>({userId:e}),f=(e,t,r)=>{const o={userId:r};for(const a of R){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},b=async(e,t)=>{const r=g(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const a=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const n of a)o.set(n.userId,I(n));const s=r.filter(e=>!o.has(e));if(s.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:s});for(const t of e)o.set(t.userId,t)}for(const n of r)o.has(n)||o.set(n,y(n));return o},C=e=>m(e)?e:null,w=e=>"string"==typeof e?e:void 0,_=e=>{const t=w(e)?.trim();return t||void 0},A=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},M=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},v=e=>{const t=C(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},U=e=>{const t=C(e);return t?C(t.data)?t.data:t:null},E=(e,t)=>{const r=C(e),o=r&&C(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return A(a[0])},S=e=>_(e.chatRoomId)??_(e.chatroomid)??_(e.id)??"",O=e=>w(e.name)??w(e.title)??w(e.groupname)??"",T=e=>y(e),x=(e,t)=>{const r=C(e);if(!r)return null;const o=S(r);if(!o)return null;const a=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(_(r.owner)):_(r.owner);return{chatRoomId:o,name:O(r),owner:a?T(a):void 0,memberCount:A(r.memberCount)??A(r.affiliations_count),disabled:M(r.disabled)}},k=(e,t)=>{const r=(e=>{const t=C(e);return t?A(t.count):void 0})(e),o=v(e).map(e=>x(e,t)).filter(e=>null!==e),a=E(e,"pagenum"),s=E(e,"pagesize");return{items:o,pageNum:a,pageSize:s,total:r,hasMore:void 0!==r&&void 0!==a&&void 0!==s?a*s<r:void 0}},$=(e,t)=>{const r=v(e),o=C(r[0])??U(e)??{},a=x(o)??{chatRoomId:S(o),name:O(o)},s=((e,t)=>{if(!t)return;if(_(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const o of r){const e=C(o);if(e){if(_(e.owner)===t)return"owner";if(_(e.admin)===t)return"admin";if(_(e.member)===t)return"member"}}})(o,t),n=A(o.muteExpireAt)??A(o.mute_expire)??A(o.expire),i=M(o.inAllowlist)??M(o.white)??M(o.in_whitelist),c=M(o.muted);return{...a,description:w(o.description),maxMembers:A(o.maxMembers)??A(o.maxusers)??A(o.max_users),createdAt:A(o.createdAt)??A(o.created),ext:w(o.ext)??w(o.custom),announcement:w(o.announcement),permissionType:s,currentUserStatus:void 0!==i||void 0!==c||void 0!==n||void 0!==s?{inAllowlist:i,muted:c,muteExpireAt:n,permissionType:s}:void 0}},L=e=>v(e).map(e=>_(e)).filter(e=>Boolean(e)).map(e=>T(e)),N=(e,t)=>{const r=U(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=C(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:F(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},D=e=>{const t=C(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=C(e),r=(e=>{const t=C(e);if(!t)return null;const r=_(t.user),o=_(t.chatRoomId)??_(t.chatroomid)??_(t.id),a=w(t.action),s=M(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:T(r),action:a,reason:w(t.reason),...s?{}:{reason:w(t.reason)??"failed"}}:null})(e);if(!r||!t)return;M(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},F=t=>t.includes("is exceeding maximum limit")||t.includes("size of metadata")&&t.includes("exceeds")?e.SERVICE_LIMIT_EXCEEDED:t.includes("is not part of you")?e.CHATROOM_PERMISSION_DENIED:t.includes("is not Legal")||t.includes("is not exist")?e.VALIDATION_REQUIRED:e.REST_BUSINESS_UNKNOWN,B=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},z=t=>new r(`${t} is required`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),j=(t,o)=>new r(o,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:o,rule:"invalid_format"}]}}),V=(e,t)=>`/${e.orgName}/${e.appName}${t}`,q=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw j(t,`${t} must be a string`);return e}},P=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw j(t,`${t} must be a number`);return e}},W=(e,t)=>{const r=u();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const o=r.toString();return o?`?${o}`:""},H=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw z(t);return e.trim()},K=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw z(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw j(`${t}[${a}]`,`${t}[${a}] must be a string`);const s=e.trim();s&&!o.has(s)&&(o.add(s),r.push(s))}),0===r.length)throw z(t);return r},G=(e,t)=>K(e,t),Q=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s={},n=q(r.name,"params.name"),i=q(r.description,"params.description"),c=P(r.maxMembers,"params.maxMembers");if(void 0!==n&&(s.groupname=n),void 0!==i&&(s.description=i),void 0!==c&&(s.maxusers=c),0===Object.keys(s).length)throw z("params");const u=V(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=U(e)??{};return{nameUpdated:M(t.groupname),descriptionUpdated:M(t.description),maxMembersUpdated:M(t.maxusers)}})(await e.put(u,s,{operation:"updateChatRoomInfo"}))},J=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/users${(e=>{const t=u();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const a of v(e)){const e=C(a);if(!e)continue;const r=_(e.owner),o=_(e.admin),s=_(e.member),n=r??o??s;n&&t.push({user:T(n),role:r?"owner":o?"admin":"member",joinedAt:A(e.joinedAt)??A(e.joined_time)})}const r=C(e),o=r?_(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(s,{operation:"getChatRoomMemberList"}))},X=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return L(n)},Y=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=u();s.set("version","v3"),"number"==typeof r.pageNum&&s.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&s.set("pagesize",String(r.pageSize));const n=V(o,`/chatrooms/${encodeURIComponent(a)}/mute?${s.toString()}`);return(e=>{const t=v(e);if(t.every(e=>"string"==typeof e))return L(e).map(e=>({user:e}));const r=[];for(const o of t){const e=C(o);if(!e)continue;const t=_(e.user)??_(e.member)??_(e.owner)??_(e.admin);t&&r.push({user:T(t),muteExpire:A(e.muteExpire)??A(e.expire)??A(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(n,{operation:"getChatRoomMuteList"}))},Z=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return{muted:M(t.muted)??M(t.value)??Boolean(t.data),muteExpireAt:A(t.muteExpireAt)??A(t.expire)??A(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},ee=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=W(r),n=s?"&":"",i=V(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return L(c).map(e=>({user:e}))},te=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return L(n).map(e=>({user:e}))},re=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return M(t.value)??M(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},oe=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=U(e)??{};return{announcement:w(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},ae=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=U(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?G(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},se=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw j(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw z(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw j(t,`${t} contains invalid key`);if("string"!=typeof r)throw j(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:n=!0,isForced:i=!1}=r,c=i?"/forced":"",u=V(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),m=await e.put(u,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return N(m,a)},ne={onChatRoomDestroyed:c.CHAT_ROOM_DESTROYED,onMembersJoined:c.MEMBERS_JOINED,onMembersExited:c.MEMBERS_EXITED,onRemovedFromChatRoom:c.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:c.MUTE_LIST_ADDED,onMuteListRemoved:c.MUTE_LIST_REMOVED,onAllowListAdded:c.ALLOW_LIST_ADDED,onAllowListRemoved:c.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:c.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:c.ADMIN_ADDED,onAdminRemoved:c.ADMIN_REMOVED,onOwnerChanged:c.OWNER_CHANGED,onAnnouncementChanged:c.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:c.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:c.ATTRIBUTES_UPDATE,onAttributesRemoved:c.ATTRIBUTES_REMOVED},ie=n(i,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),ce=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=/* @__PURE__ */new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=ne[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const o=ne[t.eventName];o&&this.eventContext?.dispatch?.(o,r)}async buildIncomingEventPayload(e,t){const r=t.payload,o=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,o)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,o),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,o)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,o)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,o)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,o),oldOwner:this.pickEventUser(r.oldOwnerId,o)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,o)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,o)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const o=B(t),a=V(o,`/chatrooms${W(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return k(s)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(t){this.requireClient();const o=t.trim();if(0===o.length)throw new r("chatRoomId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const a=this.chatRoomRegistry.get(o);if(a)return a;const s=new p(o,this);return this.chatRoomRegistry.set(o,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true`),n=await e.get(s,{operation:"getChatRoomInfo"});return $(n,t.userId)})(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return Q(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=H(e.chatRoomId,"params.chatRoomId"),o=this.normalizeOptionalString(e.ext,"params.ext"),a=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:o,leaveOtherRooms:a})).chatRoomInfo??{}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=H(e.chatRoomId,"params.chatRoomId");await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await J(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await X(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=H(r.userId,"params.userId"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/admin?resource=${o.encodedResource}`);await e.post(n,{newadmin:s},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=H(r.userId,"params.userId"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/admin/${encodeURIComponent(s)}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await Y(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=P(r.duration,"params.duration"),i=V(o,`/chatrooms/${encodeURIComponent(a)}/mute?resource=${o.encodedResource}`);await e.post(i,{usernames:s,mute_duration:n},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return Z(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await ee(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=1===s.length,i=V(o,n?`/chatrooms/${encodeURIComponent(a)}/blocks/users/${encodeURIComponent(s[0]??"")}?resource=${o.encodedResource}`:`/chatrooms/${encodeURIComponent(a)}/blocks/users?resource=${o.encodedResource}`),c=await e.post(i,n?void 0:{usernames:s},{operation:"blockChatRoomMembers"});return D(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await te(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return re(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return oe(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=q(r.announcement,"params.announcement");if(void 0===s)throw z("params.announcement");const n=V(o,`/chatrooms/${encodeURIComponent(a)}/announcement?resource=${o.encodedResource}`);await e.post(n,{announcement:s},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return ae(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await se(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=G(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=V(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),u=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return N(u,a)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw o.warn(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(t,r){return r instanceof a?r:r instanceof Error?new a(`ChatRoomManager ${t} failed: ${r.message}`,e.UNKNOWN):new a(`ChatRoomManager ${t} failed`,e.UNKNOWN)}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new a(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new s(e.restBaseUrl,{errorMap:ie,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new a("ChatRoomManager is not bound to client",e.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(t,o){if(void 0!==t){if("string"!=typeof t)throw new r(`${o} must be a string`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} must be a string`,rule:"invalid_format"}]}});return t}}normalizeOptionalBoolean(t,o){if(void 0!==t){if("boolean"!=typeof t)throw new r(`${o} must be a boolean`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} must be a boolean`,rule:"invalid_format"}]}});return t}}getCacheManager(){return this.client?.getCacheManager()??null}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return b(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=g(e),o=await b(r,t);return r.map(e=>f(void 0,o.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=h(e),o=await this.getRestClient(t).request(d(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return l(o,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],o=[],a=/* @__PURE__ */new Set;for(const s of r){if("string"!=typeof s)continue;const e=s.trim();e&&!a.has(e)&&(a.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return f(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>f(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){o.warn("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:f(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:f(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:f(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ce.key="chatRoomManager";let ue=ce;export{p as ChatRoom,ue as ChatRoomManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-DKmdsV1-.cjs");exports.ContactManager=e.ContactManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-BsIqq7LU.cjs");exports.ContactManager=e.ContactManager;
@@ -1 +1 @@
1
- import{C as a}from"../../chunks/index-DKksD5YM.js";export{a as ContactManager};
1
+ import{C as a}from"../../chunks/index-BmwQgZ3E.js";export{a as ContactManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-BItCF8E7.cjs");exports.Group=e.Group,exports.GroupManager=e.GroupManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-Dvvh1nf6.cjs");exports.Group=e.Group,exports.GroupManager=e.GroupManager;
@@ -1 +1 @@
1
- import{G as r,a as o}from"../../chunks/index-VEUtqiDw.js";export{r as Group,o as GroupManager};
1
+ import{G as r,a as o}from"../../chunks/index-CFMcR5a_.js";export{r as Group,o as GroupManager};
@@ -1 +1 @@
1
- import{l as e,S as t,E as r,V as s,f as a,m as i,i as n}from"../../chunks/common-BW2KLpvb.js";const u=i(n,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),o=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(t){return this.runOperation("publishPresence",async()=>{this.validateDescription(t.customStatus);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${r.clientResource}/1`,u={ext:t.customStatus};e.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:u,operation:"publishPresence"})})}async subscribePresence(t){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(t.userIds),this.validateExpiry(t.expiry);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${t.expiry}`,u={usernames:t.userIds};e.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const o=await s.request(n,{method:"POST",body:u,operation:"subscribePresences"});return this.normalizeSubscribeResponse(o)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`;e.debug("Call unsubscribePresence",{userIds:t.userIds}),await s.request(n,{method:"DELETE",body:t.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(t){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(t.pageNum,t.pageSize);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const u=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(u)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`,u={usernames:t.userIds};e.debug("Call getPresenceStatus",{userIds:t.userIds});const o=await s.request(n,{method:"POST",body:u,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(o)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.warn(`PresenceManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(e,s){return s instanceof t?s:s instanceof Error?new t(`PresenceManager ${e} failed: ${s.message}`,r.UNKNOWN):new t(`PresenceManager ${e} failed`,r.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new s("PresenceManager is not bound to event context",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new s("PresenceManager is not bound to client",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new a(e.restBaseUrl,{errorMap:u,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,a]of Object.entries(e))if("number"==typeof a&&Number.isFinite(a))r[s]=Math.trunc(a);else if("string"==typeof a&&a.trim().length>0){const e=Number(a);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new s("Invalid parameters",{code:r.VALIDATION_INVALID_FORMAT,details:{fields:e}})}};o.key="presenceManager";let l=o;export{l as PresenceManager};
1
+ import{l as e,S as t,E as r,V as s,f as a,m as i,i as n}from"../../chunks/common-D_DfwSd3.js";const u=i(n,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),o=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(t){return this.runOperation("publishPresence",async()=>{this.validateDescription(t.customStatus);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${r.clientResource}/1`,u={ext:t.customStatus};e.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:u,operation:"publishPresence"})})}async subscribePresence(t){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(t.userIds),this.validateExpiry(t.expiry);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${t.expiry}`,u={usernames:t.userIds};e.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const o=await s.request(n,{method:"POST",body:u,operation:"subscribePresences"});return this.normalizeSubscribeResponse(o)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`;e.debug("Call unsubscribePresence",{userIds:t.userIds}),await s.request(n,{method:"DELETE",body:t.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(t){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(t.pageNum,t.pageSize);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const u=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(u)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`,u={usernames:t.userIds};e.debug("Call getPresenceStatus",{userIds:t.userIds});const o=await s.request(n,{method:"POST",body:u,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(o)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.warn(`PresenceManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(e,s){return s instanceof t?s:s instanceof Error?new t(`PresenceManager ${e} failed: ${s.message}`,r.UNKNOWN):new t(`PresenceManager ${e} failed`,r.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new s("PresenceManager is not bound to event context",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new s("PresenceManager is not bound to client",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new a(e.restBaseUrl,{errorMap:u,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,a]of Object.entries(e))if("number"==typeof a&&Number.isFinite(a))r[s]=Math.trunc(a);else if("string"==typeof a&&a.trim().length>0){const e=Number(a);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new s("Invalid parameters",{code:r.VALIDATION_INVALID_FORMAT,details:{fields:e}})}};o.key="presenceManager";let l=o;export{l as PresenceManager};
@@ -1 +1 @@
1
- import{l as e,S as t,E as n,f as r,V as o,m as i,i as a}from"../../chunks/common-BW2KLpvb.js";import{q as s}from"../../chunks/session-list-query-DtoToipt.js";const l=i(a,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),u=["singleChat","groupChat"],d=["ALL","AT","NONE","DEFAULT"],p=["ALL","AT","NONE"],c=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),h=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(t){return this.runOperation(async()=>{this.validateUploadPushTokenParams(t);const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}`;e.debug("Call uploadPushToken",{deviceId:t.deviceId,notifierName:t.notifierName}),await r.request(a,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken"})})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/user/${n.userId}?resource=${encodeURIComponent(n.clientResource)}`,s=this.buildSilentModePayload(t.rule);e.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await r.request(a,{method:"PUT",body:s,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/user/${t.userId}`;e.debug("Call getGlobalSilentMode");const a=await n.request(i,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await r.request(s,{method:"PUT",body:l,operation:"setConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(u),t.rule)}})}async getConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}`;e.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l))}})}async clearConversationRemindType(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`;e.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),{remindType:"DEFAULT"})}})}async getConversationSilentModes(t){return this.runOperation(async()=>{this.validateConversationList(t.conversationList,"conversationList");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),s=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${o}/${i}/users/${n.userId}/notification?user=${a}&group=${s}`;e.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await r.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),p=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:p[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(t){await this.runOperation(async()=>{this.validateLanguage(t.language,"language");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/language`;e.debug("Call setPushLanguage",{language:t.language}),await r.request(a,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/language`;e.debug("Call getPushLanguage");const a=await n.request(i,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(a,"")}})}getConversationListByRemindType(t){return this.runOperation(()=>{e.debug("Call getConversationListByRemindType",{pageSize:t.pageSize,hasCursor:Boolean(t.cursor)});const n=this.getClientOrThrow(),r=s({items:n.getCacheManager()?.loadSessionList()??[],pageSize:t.pageSize,cursor:t.cursor});return Promise.resolve(r)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof t?e:e instanceof Error?new t(`PushManager operation failed: ${e.message}`,n.UNKNOWN):new t("PushManager operation failed",n.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new r(e.restBaseUrl,{errorMap:l,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new t("PushManager is not bound to client",n.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!u.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,n)=>{this.validateConversationId(e.conversationId,`${t}[${n}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${n}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!c(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!p.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,n){const r=Object.keys(e).find(e=>!n.includes(e));if(r)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${r}`,message:`${r} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!c(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const n=this.parseRuleView(e);return n?t?{...this.toRuleViewFromFallback(t),...n}:n:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!c(e))return null;const t={},n=this.normalizeRemindType(e.type);null!==n&&(t.remindType=n);const r=e.ignoreDuration;"number"==typeof r&&Number.isInteger(r)&&r>0&&(t.expireTimestamp=r);const o=e.ignoreInterval;if("string"==typeof o){const e=this.parseInterval(o);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const n=Number(t[1]),r=Number(t[2]),o=Number(t[3]),i=Number(t[4]);return Number.isInteger(n)&&Number.isInteger(r)&&Number.isInteger(o)&&Number.isInteger(i)?n<0||n>23||o<0||o>23||r<0||r>59||i<0||i>59?null:{startTime:{hours:n,minutes:r},endTime:{hours:o,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(c(e.data)){const n=e.data[t];if(c(n))return n}const n=e[t];return c(n)?n:{}}resolveSilentModeRuleSource(e){if(!c(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return c(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":d.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(c(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const n=e.data.language;if("string"==typeof n&&n.length>0)return n}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(e,t){return new o(e,{code:n.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};h.key="pushManager";let g=h;export{g as PushManager};
1
+ import{l as e,S as t,E as n,f as r,V as o,m as i,i as a}from"../../chunks/common-D_DfwSd3.js";import{q as s}from"../../chunks/session-list-query-rynxSxtv.js";const l=i(a,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),u=["singleChat","groupChat"],d=["ALL","AT","NONE","DEFAULT"],p=["ALL","AT","NONE"],c=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),h=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(t){return this.runOperation(async()=>{this.validateUploadPushTokenParams(t);const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}`;e.debug("Call uploadPushToken",{deviceId:t.deviceId,notifierName:t.notifierName}),await r.request(a,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken"})})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/user/${n.userId}?resource=${encodeURIComponent(n.clientResource)}`,s=this.buildSilentModePayload(t.rule);e.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await r.request(a,{method:"PUT",body:s,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/user/${t.userId}`;e.debug("Call getGlobalSilentMode");const a=await n.request(i,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await r.request(s,{method:"PUT",body:l,operation:"setConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(u),t.rule)}})}async getConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}`;e.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l))}})}async clearConversationRemindType(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`;e.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),{remindType:"DEFAULT"})}})}async getConversationSilentModes(t){return this.runOperation(async()=>{this.validateConversationList(t.conversationList,"conversationList");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),s=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${o}/${i}/users/${n.userId}/notification?user=${a}&group=${s}`;e.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await r.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),p=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:p[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(t){await this.runOperation(async()=>{this.validateLanguage(t.language,"language");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/language`;e.debug("Call setPushLanguage",{language:t.language}),await r.request(a,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/language`;e.debug("Call getPushLanguage");const a=await n.request(i,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(a,"")}})}getConversationListByRemindType(t){return this.runOperation(()=>{e.debug("Call getConversationListByRemindType",{pageSize:t.pageSize,hasCursor:Boolean(t.cursor)});const n=this.getClientOrThrow(),r=s({items:n.getCacheManager()?.loadSessionList()??[],pageSize:t.pageSize,cursor:t.cursor});return Promise.resolve(r)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof t?e:e instanceof Error?new t(`PushManager operation failed: ${e.message}`,n.UNKNOWN):new t("PushManager operation failed",n.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new r(e.restBaseUrl,{errorMap:l,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new t("PushManager is not bound to client",n.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!u.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,n)=>{this.validateConversationId(e.conversationId,`${t}[${n}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${n}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!c(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!p.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,n){const r=Object.keys(e).find(e=>!n.includes(e));if(r)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${r}`,message:`${r} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!c(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const n=this.parseRuleView(e);return n?t?{...this.toRuleViewFromFallback(t),...n}:n:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!c(e))return null;const t={},n=this.normalizeRemindType(e.type);null!==n&&(t.remindType=n);const r=e.ignoreDuration;"number"==typeof r&&Number.isInteger(r)&&r>0&&(t.expireTimestamp=r);const o=e.ignoreInterval;if("string"==typeof o){const e=this.parseInterval(o);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const n=Number(t[1]),r=Number(t[2]),o=Number(t[3]),i=Number(t[4]);return Number.isInteger(n)&&Number.isInteger(r)&&Number.isInteger(o)&&Number.isInteger(i)?n<0||n>23||o<0||o>23||r<0||r>59||i<0||i>59?null:{startTime:{hours:n,minutes:r},endTime:{hours:o,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(c(e.data)){const n=e.data[t];if(c(n))return n}const n=e[t];return c(n)?n:{}}resolveSilentModeRuleSource(e){if(!c(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return c(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":d.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(c(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const n=e.data.language;if("string"==typeof n&&n.length>0)return n}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(e,t){return new o(e,{code:n.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};h.key="pushManager";let g=h;export{g as PushManager};
@@ -1 +1 @@
1
- import{i as e}from"../../chunks/cache-utils-B99glc0H.js";import{a as t}from"../../chunks/profile-version-DLMz8lqW.js";import{p as r,E as s,V as n,l as a,S as o,f as i,m as d,i as u}from"../../chunks/common-BW2KLpvb.js";import{c as l,b as c,a as p,d as h,e as f,f as b,g as m,h as y,i as I}from"../../chunks/user-info-22jZtcSi.js";import{a as g}from"../../chunks/event-system-D6IJA0C4.js";const U=e=>{const{orgName:t,appName:s}=r(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},_=(e,t="params.userIds")=>l(e,t),w=e=>{const t=_(e);if(t.length>100)throw((e,t,r,a=s.VALIDATION_INVALID_FORMAT)=>new n(e,{code:a,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",s.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},v=(e,t)=>{const r=(e=>_(e))(t);return`${U(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},S=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},C=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],O=d(u,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),x=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=S(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const o=r.applyUserInfoNotifyPatch(n);if(!o.applied)return void a.debug("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:o.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[o.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",o.record.profile);const i=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(g.CONTACT_INFO_UPDATED,{userInfo:o.record.profile,contact:i})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=c(l(e.userIds,"params.userIds")),n=p(t);a.debug("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=h(l(e.userIds,"params.userIds"),f(e.attributes,"params.attributes")),n=p(t);a.debug("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>U(e))(t),n=w(e.userIds);a.debug("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=v(t,e.userIds);a.debug("UserInfoManager unsubscribeUsersInfo",{userIds:l(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>U(e))(e);a.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=/* @__PURE__ */new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=b(e),n=m(t);a.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const o=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),i=this.normalizeUpdateEnvelope(o,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([i]),this.dispatchSelfUpdate(i.profile),i.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=y(e,t),o=m(r);a.debug("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const i=await s.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),d=this.normalizeUpdateEnvelope(i,r.userId,{userId:r.userId,[e]:t});return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof o?t:(a.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new o(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new n("UserInfoManager is not bound to client",{code:s.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new i(e.restBaseUrl,{errorMap:O,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return I(e,t)}normalizeUpdateEnvelope(t,r,s){const n=e(t)?t:null,a=(n&&e(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of C)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return C.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:s,lastSyncAt:r,lastAccess:r,lastUpdate:e.lastModified??r}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};x.key="userInfoManager";let T=x;export{T as UserInfoManager};
1
+ import{i as e}from"../../chunks/cache-utils-B99glc0H.js";import{a as t}from"../../chunks/profile-version-DLMz8lqW.js";import{p as r,E as s,V as n,l as a,S as o,f as i,m as d,i as u}from"../../chunks/common-D_DfwSd3.js";import{c as l,b as c,a as p,d as h,e as f,f as b,g as m,h as y,i as I}from"../../chunks/user-info-DfbCp80h.js";import{a as g}from"../../chunks/event-system-D6IJA0C4.js";const U=e=>{const{orgName:t,appName:s}=r(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},_=(e,t="params.userIds")=>l(e,t),w=e=>{const t=_(e);if(t.length>100)throw((e,t,r,a=s.VALIDATION_INVALID_FORMAT)=>new n(e,{code:a,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",s.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},v=(e,t)=>{const r=(e=>_(e))(t);return`${U(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},S=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},C=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],O=d(u,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),x=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=S(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const o=r.applyUserInfoNotifyPatch(n);if(!o.applied)return void a.debug("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:o.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[o.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",o.record.profile);const i=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(g.CONTACT_INFO_UPDATED,{userInfo:o.record.profile,contact:i})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=c(l(e.userIds,"params.userIds")),n=p(t);a.debug("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=h(l(e.userIds,"params.userIds"),f(e.attributes,"params.attributes")),n=p(t);a.debug("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>U(e))(t),n=w(e.userIds);a.debug("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=v(t,e.userIds);a.debug("UserInfoManager unsubscribeUsersInfo",{userIds:l(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>U(e))(e);a.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=/* @__PURE__ */new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=b(e),n=m(t);a.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const o=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),i=this.normalizeUpdateEnvelope(o,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([i]),this.dispatchSelfUpdate(i.profile),i.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=y(e,t),o=m(r);a.debug("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const i=await s.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),d=this.normalizeUpdateEnvelope(i,r.userId,{userId:r.userId,[e]:t});return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof o?t:(a.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new o(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new n("UserInfoManager is not bound to client",{code:s.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new i(e.restBaseUrl,{errorMap:O,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return I(e,t)}normalizeUpdateEnvelope(t,r,s){const n=e(t)?t:null,a=(n&&e(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of C)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return C.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:s,lastSyncAt:r,lastAccess:r,lastUpdate:e.lastModified??r}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};x.key="userInfoManager";let T=x;export{T as UserInfoManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easemob-websdk",
3
- "version": "5.0.1",
3
+ "version": "5.1.0",
4
4
  "description": "High-performance, type-safe, extensible instant messaging SDK",
5
5
  "homepage": "https://www.easemob.com/",
6
6
  "type": "module",
@@ -5,6 +5,7 @@ import type { DnsConfig } from '../types/chat-client';
5
5
  import type { RequestAdapter } from '../platform/types';
6
6
  export declare const DEFAULT_DNS_CONFIG_URLS: string[];
7
7
  export interface DnsConfigResult {
8
+ appKey: string;
8
9
  websocketUrl: string;
9
10
  websocketUrls: string[];
10
11
  syncWebsocketUrls: string[];
@@ -12,9 +13,16 @@ export interface DnsConfigResult {
12
13
  restBaseUrl: string;
13
14
  dnsConfig: DnsConfig;
14
15
  }
15
- export declare function resolveDnsConfig(options: {
16
- appKey: string;
16
+ type DnsConfigIdentity = {
17
+ readonly appKey: string;
18
+ readonly appId?: never;
19
+ } | {
20
+ readonly appId: string;
21
+ readonly appKey?: never;
22
+ };
23
+ export declare function resolveDnsConfig(options: DnsConfigIdentity & {
17
24
  baseUrls?: string[];
18
25
  pageProtocol?: 'http' | 'https';
19
26
  requestAdapter?: RequestAdapter;
20
27
  }): Promise<DnsConfigResult>;
28
+ export {};