easemob-websdk 5.1.2 → 5.1.3

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 (41) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-manager.d.ts +11 -3
  3. package/cache/cache-types.d.ts +13 -2
  4. package/chat-client.d.ts +6 -0
  5. package/chunks/{chat-manager-BFd2Z4oY.cjs → chat-manager-BI-6bEor.cjs} +1 -1
  6. package/chunks/{chat-manager-CId_M_e5.js → chat-manager-nXOTpJ01.js} +2 -2
  7. package/chunks/{common-BvlDAw4a.js → common-DHQukb7J.js} +1 -1
  8. package/chunks/{event-system-B62vbKqG.js → event-system-DguqwFpc.js} +1 -1
  9. package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-D6AQAHEE.js} +1 -1
  10. package/chunks/{index-BBFJYOM8.js → index-CneY58NJ.js} +1 -1
  11. package/chunks/index-DxjmfFL7.js +1 -0
  12. package/chunks/push-manager-CSIKhoPe.js +1 -0
  13. package/chunks/push-manager-D7RDsKuv.cjs +1 -0
  14. package/chunks/session-list-query-C3iQvQxK.cjs +1 -0
  15. package/chunks/session-list-query-Cdpiw_IZ.js +1 -0
  16. package/chunks/{user-info-AlshAvdy.js → user-info-7QzMa7bR.js} +1 -1
  17. package/core/session-list-sync/session-list-message-events.d.ts +9 -0
  18. package/index.cjs +1 -1
  19. package/index.js +2 -2
  20. package/managers/chat/index.cjs +1 -1
  21. package/managers/chat/index.js +1 -1
  22. package/managers/chat-thread/index.js +1 -1
  23. package/managers/chatroom/index.js +1 -1
  24. package/managers/contact/index.js +1 -1
  25. package/managers/group/index.js +1 -1
  26. package/managers/presence/index.js +1 -1
  27. package/managers/push/index.cjs +1 -1
  28. package/managers/push/index.js +1 -1
  29. package/managers/user-info/index.js +1 -1
  30. package/message/message-snapshot.d.ts +8 -0
  31. package/package.json +1 -1
  32. package/protocol/msync/codec.d.ts +1 -21
  33. package/protocol/msync/message-identity.d.ts +2 -0
  34. package/protocol/msync/message-payload-decoder.d.ts +35 -0
  35. package/protocol/session-list/gateway.d.ts +8 -1
  36. package/protocol/session-list/payload-decoder.d.ts +12 -0
  37. package/types/conversation.d.ts +27 -20
  38. package/utils/session-message-recipient.d.ts +11 -0
  39. package/chunks/index-l_BUKi77.js +0 -1
  40. package/chunks/session-list-query-Cvr6rlme.js +0 -1
  41. package/chunks/session-list-query-Dslj2k3t.cjs +0 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/chat-manager-BFd2Z4oY.cjs");exports.ChatManager=e.ChatManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/chat-manager-BI-6bEor.cjs");exports.ChatManager=e.ChatManager;
@@ -1 +1 @@
1
- import{C as a}from"../../chunks/chat-manager-CId_M_e5.js";export{a as ChatManager};
1
+ import{C as a}from"../../chunks/chat-manager-nXOTpJ01.js";export{a as ChatManager};
@@ -1 +1 @@
1
- import{p as e,V as t,E as r,h as a,S as s,m as o,j as n}from"../../chunks/common-BvlDAw4a.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,R as a,S as s,m as o,C as n}from"../../chunks/common-DHQukb7J.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 +1 @@
1
- import{E as e,p as t,V as r,l as o,S as a,M as s,h as n,m as i,j as c}from"../../chunks/common-BvlDAw4a.js";import{c as m}from"../../chunks/event-system-B62vbKqG.js";import{c as u}from"../../chunks/query-params-Bu3Xq4b6.js";import{i as h}from"../../chunks/cache-utils-B99glc0H.js";import{b as d,a as l,n as p}from"../../chunks/user-info-AlshAvdy.js";class R{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 g=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],I=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},y=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),f=e=>({userId:e}),b=(e,t,r)=>{const o={userId:r};for(const a of g){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},C=async(e,t)=>{const r=I(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,y(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,f(n));return o},w=e=>h(e)?e:null,_=e=>"string"==typeof e?e:void 0,A=e=>{const t=_(e)?.trim();return t||void 0},M=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}},v=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},U=e=>{const t=w(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},O=e=>{const t=w(e);return t?w(t.data)?t.data:t:null},E=(e,t)=>{const r=w(e),o=r&&w(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return M(a[0])},S=e=>A(e.chatRoomId)??A(e.chatroomid)??A(e.id)??"",T=e=>_(e.name)??_(e.title)??_(e.groupname)??"",x=e=>f(e),k=(e,t)=>{const r=(e=>{const t=_(e);return"owner"===t||"admin"===t||"member"===t||"none"===t?t:void 0})(e.permission);if(void 0!==r)return r;if(!t)return;if(A(e.owner)===t)return"owner";const o=Array.isArray(e.affiliations)?e.affiliations:[];for(const a of o){const e=w(a);if(e){if(A(e.owner)===t)return"owner";if(A(e.admin)===t)return"admin";if(A(e.member)===t)return"member"}}},$=(e,t)=>{const r=w(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)})(A(r.owner)):A(r.owner);return{chatRoomId:o,name:T(r),owner:a?x(a):void 0,memberCount:M(r.memberCount)??M(r.affiliations_count),disabled:v(r.disabled)}},L=(e,t)=>{const r=(e=>{const t=w(e);return t?M(t.count):void 0})(e),o=U(e).map(e=>$(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}},N=e=>U(e).map(e=>A(e)).filter(e=>Boolean(e)).map(e=>x(e)),D=(e,t)=>{const r=O(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=w(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:B(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},F=e=>{const t=w(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=w(e),r=(e=>{const t=w(e);if(!t)return null;const r=A(t.user),o=A(t.chatRoomId)??A(t.chatroomid)??A(t.id),a=_(t.action),s=v(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:x(r),action:a,reason:_(t.reason),...s?{}:{reason:_(t.reason)??"failed"}}:null})(e);if(!r||!t)return;v(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},B=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,j=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"}]}}),V=(t,o)=>new r(o,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:o,rule:"invalid_format"}]}}),P=(e,t)=>`/${e.orgName}/${e.appName}${t}`,q=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw V(t,`${t} must be a string`);return e}},H=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw V(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}`:""},K=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw z(t);return e.trim()},G=(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 V(`${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},X=(e,t)=>G(e,t),Q=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true&version=v3`);return((e,t)=>{const r=U(e),o=w(r[0])??O(e)??{},a=$(o)??{chatRoomId:S(o),name:T(o)},s=k(o,t);return{...a,description:_(o.description),maxMembers:M(o.maxMembers)??M(o.maxusers)??M(o.max_users),createdAt:M(o.createdAt)??M(o.created),ext:_(o.ext)??_(o.custom),muteAllMembers:v(o.mute),permissionType:s}})(await e.get(s,{operation:"getChatRoomInfo"}),t.userId)},J=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s={},n=q(r.name,"params.name"),i=q(r.description,"params.description"),c=H(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 m=P(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=O(e)??{};return{nameUpdated:v(t.groupname),descriptionUpdated:v(t.description),maxMembersUpdated:v(t.maxusers)}})(await e.put(m,s,{operation:"updateChatRoomInfo"}))},Y=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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 U(e)){const e=w(a);if(!e)continue;const r=A(e.owner),o=A(e.admin),s=A(e.member),n=r??o??s;n&&t.push({user:x(n),role:r?"owner":o?"admin":"member",joinedAt:M(e.joinedAt)??M(e.joined_time)})}const r=w(e),o=r?A(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(s,{operation:"getChatRoomMemberList"}))},Z=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return N(n)},ee=async(e,t,r)=>{const o=j(t),a=K(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=P(o,`/chatrooms/${encodeURIComponent(a)}/mute?${s.toString()}`);return(e=>{const t=U(e);if(t.every(e=>"string"==typeof e))return N(e).map(e=>({user:e}));const r=[];for(const o of t){const e=w(o);if(!e)continue;const t=A(e.user)??A(e.member)??A(e.owner)??A(e.admin);t&&r.push({user:x(t),muteExpire:M(e.muteExpire)??M(e.expire)??M(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(n,{operation:"getChatRoomMuteList"}))},te=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=O(e)??{};return{muted:v(t.muted)??v(t.value)??Boolean(t.data),muteExpireAt:M(t.muteExpireAt)??M(t.expire)??M(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},re=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=W(r),n=s?"&":"",i=P(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return N(c).map(e=>({user:e}))},oe=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return N(n).map(e=>({user:e}))},ae=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=O(e)??{};return v(t.value)??v(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},se=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=O(e)??{};return{announcement:_(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},ne=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=O(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?X(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},ie=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw V(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 V(t,`${t} contains invalid key`);if("string"!=typeof r)throw V(`${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":"",m=P(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),u=await e.put(m,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return D(u,a)},ce={onChatRoomDestroyed:m.CHAT_ROOM_DESTROYED,onMembersJoined:m.MEMBERS_JOINED,onMembersExited:m.MEMBERS_EXITED,onRemovedFromChatRoom:m.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:m.MUTE_LIST_ADDED,onMuteListRemoved:m.MUTE_LIST_REMOVED,onAllowListAdded:m.ALLOW_LIST_ADDED,onAllowListRemoved:m.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:m.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:m.ADMIN_ADDED,onAdminRemoved:m.ADMIN_REMOVED,onOwnerChanged:m.OWNER_CHANGED,onAnnouncementChanged:m.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:m.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:m.ATTRIBUTES_UPDATE,onAttributesRemoved:m.ATTRIBUTES_REMOVED},me=i(c,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},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,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},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,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["30005"]}}},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}}}}}),ue=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=ce[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=ce[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=j(t),a=P(o,`/chatrooms${W(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return L(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 R(o,this);return this.chatRoomRegistry.set(o,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await Q(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return J(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=K(e.chatRoomId,"params.chatRoomId"),o=this.normalizeOptionalString(e.ext,"params.ext"),a=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");try{return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:o,leaveOtherRooms:a})).chatRoomInfo??{}}catch(s){throw this.remapChatRoomOperationError("joinChatRoom",s)}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=K(e.chatRoomId,"params.chatRoomId");try{await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})}catch(o){throw this.remapChatRoomOperationError("leaveChatRoom",o)}})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await Y(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await Z(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=K(r.userId,"params.userId"),n=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=K(r.userId,"params.userId"),n=P(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 ee(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=H(r.duration,"params.duration"),i=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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 te(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await re(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=1===s.length,i=P(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 F(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await oe(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return F(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return ae(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return se(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=q(r.announcement,"params.announcement");if(void 0===s)throw z("params.announcement");const n=P(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 ne(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await ie(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=X(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=P(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),m=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return D(m,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)}remapChatRoomOperationError(t,r){return r instanceof a&&r.code===e.GROUP_NOT_EXIST?new s("Chat room does not exist",{code:e.CHATROOM_NOT_EXIST,details:{...r.details,api:t,originalCode:r.code,canonicalCode:e.CHATROOM_NOT_EXIST,retryable:!1}}):r}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 n(e.restBaseUrl,{errorMap:me,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 C(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=I(e),o=await C(r,t);return r.map(e=>b(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=d(e),o=await this.getRestClient(t).request(l(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return p(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 b(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>b(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:b(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:b(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:b(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ue.key="chatRoomManager";let he=ue;export{R as ChatRoom,he as ChatRoomManager};
1
+ import{E as e,p as t,V as r,l as o,S as a,M as s,R as n,m as i,C as c}from"../../chunks/common-DHQukb7J.js";import{c as m}from"../../chunks/event-system-DguqwFpc.js";import{c as u}from"../../chunks/query-params-Bu3Xq4b6.js";import{i as h}from"../../chunks/cache-utils-B99glc0H.js";import{b as d,a as l,n as p}from"../../chunks/user-info-7QzMa7bR.js";class R{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 g=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],I=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},y=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),f=e=>({userId:e}),b=(e,t,r)=>{const o={userId:r};for(const a of g){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},C=async(e,t)=>{const r=I(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,y(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,f(n));return o},w=e=>h(e)?e:null,_=e=>"string"==typeof e?e:void 0,A=e=>{const t=_(e)?.trim();return t||void 0},M=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}},v=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},U=e=>{const t=w(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},O=e=>{const t=w(e);return t?w(t.data)?t.data:t:null},E=(e,t)=>{const r=w(e),o=r&&w(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return M(a[0])},S=e=>A(e.chatRoomId)??A(e.chatroomid)??A(e.id)??"",T=e=>_(e.name)??_(e.title)??_(e.groupname)??"",x=e=>f(e),k=(e,t)=>{const r=(e=>{const t=_(e);return"owner"===t||"admin"===t||"member"===t||"none"===t?t:void 0})(e.permission);if(void 0!==r)return r;if(!t)return;if(A(e.owner)===t)return"owner";const o=Array.isArray(e.affiliations)?e.affiliations:[];for(const a of o){const e=w(a);if(e){if(A(e.owner)===t)return"owner";if(A(e.admin)===t)return"admin";if(A(e.member)===t)return"member"}}},$=(e,t)=>{const r=w(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)})(A(r.owner)):A(r.owner);return{chatRoomId:o,name:T(r),owner:a?x(a):void 0,memberCount:M(r.memberCount)??M(r.affiliations_count),disabled:v(r.disabled)}},L=(e,t)=>{const r=(e=>{const t=w(e);return t?M(t.count):void 0})(e),o=U(e).map(e=>$(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}},N=e=>U(e).map(e=>A(e)).filter(e=>Boolean(e)).map(e=>x(e)),D=(e,t)=>{const r=O(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=w(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:B(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},F=e=>{const t=w(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=w(e),r=(e=>{const t=w(e);if(!t)return null;const r=A(t.user),o=A(t.chatRoomId)??A(t.chatroomid)??A(t.id),a=_(t.action),s=v(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:x(r),action:a,reason:_(t.reason),...s?{}:{reason:_(t.reason)??"failed"}}:null})(e);if(!r||!t)return;v(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},B=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,z=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},j=t=>new r(`${t} is required`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),V=(t,o)=>new r(o,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:o,rule:"invalid_format"}]}}),P=(e,t)=>`/${e.orgName}/${e.appName}${t}`,q=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw V(t,`${t} must be a string`);return e}},H=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw V(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}`:""},K=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw j(t);return e.trim()},G=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw j(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw V(`${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 j(t);return r},X=(e,t)=>G(e,t),Q=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true&version=v3`);return((e,t)=>{const r=U(e),o=w(r[0])??O(e)??{},a=$(o)??{chatRoomId:S(o),name:T(o)},s=k(o,t);return{...a,description:_(o.description),maxMembers:M(o.maxMembers)??M(o.maxusers)??M(o.max_users),createdAt:M(o.createdAt)??M(o.created),ext:_(o.ext)??_(o.custom),muteAllMembers:v(o.mute),permissionType:s}})(await e.get(s,{operation:"getChatRoomInfo"}),t.userId)},J=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s={},n=q(r.name,"params.name"),i=q(r.description,"params.description"),c=H(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 j("params");const m=P(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=O(e)??{};return{nameUpdated:v(t.groupname),descriptionUpdated:v(t.description),maxMembersUpdated:v(t.maxusers)}})(await e.put(m,s,{operation:"updateChatRoomInfo"}))},Y=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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 U(e)){const e=w(a);if(!e)continue;const r=A(e.owner),o=A(e.admin),s=A(e.member),n=r??o??s;n&&t.push({user:x(n),role:r?"owner":o?"admin":"member",joinedAt:M(e.joinedAt)??M(e.joined_time)})}const r=w(e),o=r?A(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(s,{operation:"getChatRoomMemberList"}))},Z=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return N(n)},ee=async(e,t,r)=>{const o=z(t),a=K(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=P(o,`/chatrooms/${encodeURIComponent(a)}/mute?${s.toString()}`);return(e=>{const t=U(e);if(t.every(e=>"string"==typeof e))return N(e).map(e=>({user:e}));const r=[];for(const o of t){const e=w(o);if(!e)continue;const t=A(e.user)??A(e.member)??A(e.owner)??A(e.admin);t&&r.push({user:x(t),muteExpire:M(e.muteExpire)??M(e.expire)??M(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(n,{operation:"getChatRoomMuteList"}))},te=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=O(e)??{};return{muted:v(t.muted)??v(t.value)??Boolean(t.data),muteExpireAt:M(t.muteExpireAt)??M(t.expire)??M(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},re=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=W(r),n=s?"&":"",i=P(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return N(c).map(e=>({user:e}))},oe=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return N(n).map(e=>({user:e}))},ae=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=O(e)??{};return v(t.value)??v(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},se=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=O(e)??{};return{announcement:_(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},ne=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=O(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?X(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},ie=async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw V(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw j(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw V(t,`${t} contains invalid key`);if("string"!=typeof r)throw V(`${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":"",m=P(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),u=await e.put(m,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return D(u,a)},ce={onChatRoomDestroyed:m.CHAT_ROOM_DESTROYED,onMembersJoined:m.MEMBERS_JOINED,onMembersExited:m.MEMBERS_EXITED,onRemovedFromChatRoom:m.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:m.MUTE_LIST_ADDED,onMuteListRemoved:m.MUTE_LIST_REMOVED,onAllowListAdded:m.ALLOW_LIST_ADDED,onAllowListRemoved:m.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:m.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:m.ADMIN_ADDED,onAdminRemoved:m.ADMIN_REMOVED,onOwnerChanged:m.OWNER_CHANGED,onAnnouncementChanged:m.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:m.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:m.ATTRIBUTES_UPDATE,onAttributesRemoved:m.ATTRIBUTES_REMOVED},me=i(c,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},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,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},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,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["30005"]}}},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}}}}}),ue=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=ce[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=ce[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=z(t),a=P(o,`/chatrooms${W(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return L(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 R(o,this);return this.chatRoomRegistry.set(o,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await Q(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return J(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=K(e.chatRoomId,"params.chatRoomId"),o=this.normalizeOptionalString(e.ext,"params.ext"),a=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");try{return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:o,leaveOtherRooms:a})).chatRoomInfo??{}}catch(s){throw this.remapChatRoomOperationError("joinChatRoom",s)}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=K(e.chatRoomId,"params.chatRoomId");try{await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})}catch(o){throw this.remapChatRoomOperationError("leaveChatRoom",o)}})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await Y(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await Z(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=K(r.userId,"params.userId"),n=P(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=K(r.userId,"params.userId"),n=P(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 ee(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=H(r.duration,"params.duration"),i=P(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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 te(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await re(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=1===s.length,i=P(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 F(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await oe(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return F(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return ae(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return se(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=q(r.announcement,"params.announcement");if(void 0===s)throw j("params.announcement");const n=P(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 ne(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await ie(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=z(t),a=K(r.chatRoomId,"params.chatRoomId"),s=X(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=P(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),m=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return D(m,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)}remapChatRoomOperationError(t,r){return r instanceof a&&r.code===e.GROUP_NOT_EXIST?new s("Chat room does not exist",{code:e.CHATROOM_NOT_EXIST,details:{...r.details,api:t,originalCode:r.code,canonicalCode:e.CHATROOM_NOT_EXIST,retryable:!1}}):r}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 n(e.restBaseUrl,{errorMap:me,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 C(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=I(e),o=await C(r,t);return r.map(e=>b(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=d(e),o=await this.getRestClient(t).request(l(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return p(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 b(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>b(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:b(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:b(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:b(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ue.key="chatRoomManager";let he=ue;export{R as ChatRoom,he as ChatRoomManager};
@@ -1 +1 @@
1
- import{C as a}from"../../chunks/index-BBFJYOM8.js";export{a as ContactManager};
1
+ import{C as a}from"../../chunks/index-CneY58NJ.js";export{a as ContactManager};
@@ -1 +1 @@
1
- import{G as r,a as o}from"../../chunks/index-l_BUKi77.js";export{r as Group,o as GroupManager};
1
+ import{G as r,a as o}from"../../chunks/index-DxjmfFL7.js";export{r as Group,o as GroupManager};
@@ -1 +1 @@
1
- import{l as e,S as t,E as r,V as s,h as a,m as i,j as n}from"../../chunks/common-BvlDAw4a.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,R as a,m as i,C as n}from"../../chunks/common-DHQukb7J.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
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-tHGz9VBk.cjs"),t=require("../../chunks/event-system-TYhmgy4K.cjs"),i=require("../../chunks/session-list-query-Dslj2k3t.cjs"),n=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],s=(t,i,n="invalid_format")=>new e.ValidationError(i,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:i,rule:n}]}}),r=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw s(t,`${t} must be a non-empty string`);return e.trim()}},o=e=>8===e?"normal":n[e]??"normal",a=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class l{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=new Set}configure(t){const i=(e=>{if(!e||"object"!=typeof e)throw s("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw s("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw s("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw s("plugin.unRegister","plugin.unRegister must be a function");const o=e.certificates;if(!o||"object"!=typeof o)throw s("certificates","certificates is required","required");const a=o,l={apns:r(a.apns,"certificates.apns"),fcm:r(a.fcm,"certificates.fcm"),huawei:r(a.huawei,"certificates.huawei"),xiaomi:r(a.xiaomi,"certificates.xiaomi"),meizu:r(a.meizu,"certificates.meizu"),vivo:r(a.vivo,"certificates.vivo"),oppo:r(a.oppo,"certificates.oppo"),honor:r(a.honor,"certificates.honor")};if(!n.some(e=>void 0!==l[e]))throw s("certificates","at least one native push certificate is required");return{plugin:t,certificates:l,signature:n.map(e=>`${e}:${l[e]??""}`).join("|")}})(t),o=null!==this.config&&"disabled"!==this.state,a=this.config?.plugin===i.plugin&&this.config.signature===i.signature;if(o&&!a)throw new e.ValidationError("Native push is enabled; call removePushToken() before replacing its configuration",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});o&&a&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=i,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const i of this.collectRemovalTargets(e.generation)){const n=await this.removeWithRetry(i,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!n){this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",i.channel,i.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,i=this.session.generation,n=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(s=>{if(!this.isRegistrationActive(i,n))return;const r=((e,t)=>{if(!a(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=o(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(s,e);if(!r){this.state="failed";const i=a(s)?o(s.push_type):void 0,n=a(s)&&200===s.code&&s.push_token.trim().length>0&&void 0!==i&&"normal"!==i&&void 0===e.certificates[i];return void this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,n?"bind":"register",i)}this.enqueueBinding(r)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const i=this.session.generation,n=this.createBindingKey(e);this.activeBindingKey=n,this.state="binding";const s=await this.bindWithRetry(e,i);if(this.activeBindingKey=null,!this.session||this.session.generation!==i||this.disabledByUser)return;s?(this.binding={...e,generation:i,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=n,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.dependencies.dispatch(t.PushEventName.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=n,this.state="failed",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(t,i){this.lastBindingError=null;for(let s=0;s<=e.NATIVE_PUSH_BIND_MAX_RETRIES;s+=1)try{const n=this.session;return!(!n||n.generation!==i)&&(this.lastAttemptedBinding={...t,generation:i,userId:n.userId,deviceId:n.clientResource},await this.dependencies.requestToken({deviceId:n.clientResource,deviceToken:t.token,notifierName:t.notifierName,timeout:e.NATIVE_PUSH_BIND_REQUEST_TIMEOUT}),!0)}catch(n){if(this.lastBindingError=this.toSdkError(n),!this.session||this.session.generation!==i)return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_BIND_MAX_RETRIES)return!1;const t=e.NATIVE_PUSH_BIND_RETRY_DELAYS[s]??0;if(!(await this.wait(t)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const i=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(i))throw this.manualRemovalInProgress=!1,new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(i);if(0!==n.length)try{for(const e of n)if(await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName}),!this.isSessionGenerationActive(i))return;this.disableByUser()}catch(s){const e=this.toSdkError(s),r=n[0];throw r&&this.isSessionGenerationActive(i)&&this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",r.channel,r.notifierName,e),this.manualRemovalInProgress=!1,this.resumePendingBinding(i),e}else this.disableByUser()}async removeWithRetry(t,i){this.lastRemovalError=null;for(let s=0;s<=e.NATIVE_PUSH_REMOVE_MAX_RETRIES;s+=1)try{return await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName,timeout:e.NATIVE_PUSH_REMOVE_REQUEST_TIMEOUT}),!0}catch(n){if(this.lastRemovalError=this.toSdkError(n),!this.isSessionGenerationActive(i))return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_REMOVE_MAX_RETRIES)return!1;if(!(await this.wait(e.NATIVE_PUSH_REMOVE_RETRY_DELAY)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{e.logger.warn("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(t){return!(t instanceof e.SDKError)||(!0===t.details?.retryable||[e.ERROR_CODES.REST_NETWORK_ERROR,e.ERROR_CODES.REST_TIMEOUT,e.ERROR_CODES.REST_HTTP_ERROR,e.ERROR_CODES.SERVER_BUSY].includes(t.code))}toSdkError(t){return t instanceof e.SDKError?t:new e.SDKError("Native push operation failed",e.ERROR_CODES.UNKNOWN)}emitFailure(t,i,n,s,r){const o=!!r&&this.isRetryable(r);this.dependencies.dispatchFailure(t,{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o}),e.logger.warn("Native push operation failed",{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o})}}const u=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{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,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,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}}}}}),d=["singleChat","groupChat"],h=["ALL","AT","NONE","DEFAULT"],c=["ALL","AT","NONE"],g=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),m=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new l({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(t){const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey);e.logger.debug("Call native push token operation",{deviceId:t.deviceId,notifierName:t.notifierName,removing:0===t.deviceToken.length}),await n.request(`/${s}/${r}/users/${i.userId}`,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken",...void 0!==t.timeout?{timeout:t.timeout}:{}})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/user/${i.userId}?resource=${encodeURIComponent(i.clientResource)}`,a=this.buildSilentModePayload(t.rule);e.logger.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await n.request(o,{method:"PUT",body:a,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}`;e.logger.debug("Call getGlobalSilentMode");const o=await i.request(r,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(o))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.logger.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await n.request(a,{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 i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}`;e.logger.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{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 i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`;e.logger.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{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 i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${s}/${r}/users/${i.userId}/notification?user=${o}&group=${a}`;e.logger.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await n.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),h=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[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 i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/language`;e.logger.debug("Call setPushLanguage",{language:t.language}),await n.request(o,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;e.logger.debug("Call getPushLanguage");const o=await i.request(r,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(o,"")}})}getConversationListByRemindType(t){return this.runOperation(()=>{e.logger.debug("Call getConversationListByRemindType",{pageSize:t.pageSize,hasCursor:Boolean(t.cursor)});const n=this.getClientOrThrow(),s=i.queryMutedConversationsFromSessionList({items:n.getCacheManager()?.loadSessionList()??[],pageSize:t.pageSize,cursor:t.cursor});return Promise.resolve(s)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(t){return t instanceof e.SDKError?t:t instanceof Error?new e.SDKError(`PushManager operation failed: ${t.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError("PushManager operation failed",e.ERROR_CODES.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(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:u,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}getClientOrThrow(){if(!this.client)throw new e.SDKError("PushManager is not bound to client",e.ERROR_CODES.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||!d.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,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].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(!g(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(!c.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,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!g(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 i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!g(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);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 i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}: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(g(e.data)){const i=e.data[t];if(g(i))return i}const i=e[t];return g(i)?i:{}}resolveSilentModeRuleSource(e){if(!g(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return g(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":h.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(g(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(t,i){return new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:i}})}};m.key="pushManager";let p=m;exports.PushManager=p;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/push-manager-D7RDsKuv.cjs");exports.PushManager=e.PushManager;
@@ -1 +1 @@
1
- import{V as e,E as t,S as i,aI as n,aJ as s,aK as r,aL as o,aM as a,aN as l,l as u,h as d,m as h,j as c}from"../../chunks/common-BvlDAw4a.js";import{b as g}from"../../chunks/event-system-B62vbKqG.js";import{q as m}from"../../chunks/session-list-query-Cvr6rlme.js";const p=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],v=(i,n,s="invalid_format")=>new e(n,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:i,message:n,rule:s}]}}),y=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw v(t,`${t} must be a non-empty string`);return e.trim()}},f=e=>8===e?"normal":p[e]??"normal",T=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class R{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=/* @__PURE__ */new Set}configure(i){const n=(e=>{if(!e||"object"!=typeof e)throw v("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw v("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw v("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw v("plugin.unRegister","plugin.unRegister must be a function");const n=e.certificates;if(!n||"object"!=typeof n)throw v("certificates","certificates is required","required");const s=n,r={apns:y(s.apns,"certificates.apns"),fcm:y(s.fcm,"certificates.fcm"),huawei:y(s.huawei,"certificates.huawei"),xiaomi:y(s.xiaomi,"certificates.xiaomi"),meizu:y(s.meizu,"certificates.meizu"),vivo:y(s.vivo,"certificates.vivo"),oppo:y(s.oppo,"certificates.oppo"),honor:y(s.honor,"certificates.honor")};if(!p.some(e=>void 0!==r[e]))throw v("certificates","at least one native push certificate is required");return{plugin:t,certificates:r,signature:p.map(e=>`${e}:${r[e]??""}`).join("|")}})(i),s=null!==this.config&&"disabled"!==this.state,r=this.config?.plugin===n.plugin&&this.config.signature===n.signature;if(s&&!r)throw new e("Native push is enabled; call removePushToken() before replacing its configuration",{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});s&&r&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=n,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const t of this.collectRemovalTargets(e.generation)){const i=await this.removeWithRetry(t,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!i){this.emitFailure(g.TOKEN_REMOVE_FAILED,"remove",t.channel,t.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new i("User is not logged in",t.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,t=this.session.generation,i=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(n=>{if(!this.isRegistrationActive(t,i))return;const s=((e,t)=>{if(!T(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=f(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(n,e);if(!s){this.state="failed";const t=T(n)?f(n.push_type):void 0,i=T(n)&&200===n.code&&n.push_token.trim().length>0&&void 0!==t&&"normal"!==t&&void 0===e.certificates[t];return void this.emitFailure(g.TOKEN_BIND_FAILED,i?"bind":"register",t)}this.enqueueBinding(s)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(g.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const t=this.session.generation,i=this.createBindingKey(e);this.activeBindingKey=i,this.state="binding";const n=await this.bindWithRetry(e,t);if(this.activeBindingKey=null,!this.session||this.session.generation!==t||this.disabledByUser)return;n?(this.binding={...e,generation:t,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=i,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.dependencies.dispatch(g.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=i,this.state="failed",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.emitFailure(g.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(e,t){this.lastBindingError=null;for(let o=0;o<=n;o+=1)try{const i=this.session;return!(!i||i.generation!==t)&&(this.lastAttemptedBinding={...e,generation:t,userId:i.userId,deviceId:i.clientResource},await this.dependencies.requestToken({deviceId:i.clientResource,deviceToken:e.token,notifierName:e.notifierName,timeout:s}),!0)}catch(i){if(this.lastBindingError=this.toSdkError(i),!this.session||this.session.generation!==t)return!1;if(!this.isRetryable(i)||o===n)return!1;const e=r[o]??0;if(!(await this.wait(e)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new i("User is not logged in",t.AUTH_NOT_LOGIN);const e=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(e))throw this.manualRemovalInProgress=!1,new i("User is not logged in",t.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(e);if(0!==n.length)try{for(const t of n)if(await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName}),!this.isSessionGenerationActive(e))return;this.disableByUser()}catch(s){const t=this.toSdkError(s),i=n[0];throw i&&this.isSessionGenerationActive(e)&&this.emitFailure(g.TOKEN_REMOVE_FAILED,"remove",i.channel,i.notifierName,t),this.manualRemovalInProgress=!1,this.resumePendingBinding(e),t}else this.disableByUser()}async removeWithRetry(e,t){this.lastRemovalError=null;for(let n=0;n<=o;n+=1)try{return await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName,timeout:a}),!0}catch(i){if(this.lastRemovalError=this.toSdkError(i),!this.isSessionGenerationActive(t))return!1;if(!this.isRetryable(i)||n===o)return!1;if(!(await this.wait(l)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{u.warn("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(e){return!(e instanceof i)||(!0===e.details?.retryable||[t.REST_NETWORK_ERROR,t.REST_TIMEOUT,t.REST_HTTP_ERROR,t.SERVER_BUSY].includes(e.code))}toSdkError(e){return e instanceof i?e:new i("Native push operation failed",t.UNKNOWN)}emitFailure(e,t,i,n,s){const r=!!s&&this.isRetryable(s);this.dependencies.dispatchFailure(e,{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r}),u.warn("Native push operation failed",{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r})}}const b=h(c,{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,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,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}}}}}),I=["singleChat","groupChat"],N=["ALL","AT","NONE","DEFAULT"],E=["ALL","AT","NONE"],C=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),w=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new R({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(e){const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey);u.debug("Call native push token operation",{deviceId:e.deviceId,notifierName:e.notifierName,removing:0===e.deviceToken.length}),await i.request(`/${n}/${s}/users/${t.userId}`,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken",...void 0!==e.timeout?{timeout:e.timeout}:{}})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);u.debug("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await i.request(r,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/user/${e.userId}`;u.debug("Call getGlobalSilentMode");const r=await t.request(s,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(r))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);u.debug("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const l=await i.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}`;u.debug("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;u.debug("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${n}/${s}/users/${t.userId}/notification?user=${r}&group=${o}`;u.debug("Call getConversationSilentModes",{count:e.conversationList.length});const l=await i.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(l,"user"),h=this.resolveConversationRuleMap(l,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;u.debug("Call setPushLanguage",{language:e.language}),await i.request(r,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/language`;u.debug("Call getPushLanguage");const r=await t.request(s,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(r,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{u.debug("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),i=m({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(i)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof i?e:e instanceof Error?new i(`PushManager operation failed: ${e.message}`,t.UNKNOWN):new i("PushManager operation failed",t.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 d(e.restBaseUrl,{errorMap:b,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 i("PushManager is not bound to client",t.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||!I.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,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].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(!E.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,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} 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 i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!C(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);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 i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}: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 i=e.data[t];if(C(i))return i}const i=e[t];return C(i)?i:{}}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":N.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 i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(i,n){return new e(i,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:n}})}};w.key="pushManager";let S=w;export{S as PushManager};
1
+ import{P as a}from"../../chunks/push-manager-CSIKhoPe.js";export{a 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 a,l as n,S as o,h as i,m as d,j as u}from"../../chunks/common-BvlDAw4a.js";import{c,b as l,a as p,d as h,e as f,f as m,g as b,h as y,i as I}from"../../chunks/user-info-AlshAvdy.js";import{a as g}from"../../chunks/event-system-B62vbKqG.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")=>c(e,t),w=e=>{const t=_(e);if(t.length>100)throw((e,t,r,n=s.VALIDATION_INVALID_FORMAT)=>new a(e,{code:n,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"],x=d(u,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},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}}}}}),O=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,a=(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(!a)return;const o=r.applyUserInfoNotifyPatch(a);if(!o.applied)return void n.debug("User-info notify ignored",{userId:a.userId,notifyType:s.notifyType,reason:o.reason,lastModified:a.lastModified});if(r.updateUserInfoSummaryFromRuntime(a.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:a.userId,lastModified:a.lastModified}]),"subscription"===a.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[o.record.profile]);if("own"===a.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",o.record.profile);const i=t.getContactSnapshot()?.items.find(e=>e.userId===a.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=l(c(e.userIds,"params.userIds")),a=p(t);n.debug("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const o=await r.request(a,{method:"POST",body:s,operation:"getUserInfoByUserId"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),this.completeFetchedProfiles(i,s.targets)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=h(c(e.userIds,"params.userIds"),f(e.attributes,"params.attributes")),a=p(t);n.debug("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const o=await r.request(a,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),this.completeFetchedProfiles(i,s.targets)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>U(e))(t),a=w(e.userIds);n.debug("UserInfoManager subscribeUsersInfo",{userIds:a.usernames}),await r.request(s,{method:"POST",body:a,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=v(t,e.userIds);n.debug("UserInfoManager unsubscribeUsersInfo",{userIds:c(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);n.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 a of t.data){if("string"!=typeof a)continue;const e=a.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=m(e),a=b(t);n.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const o=await r.request(a,{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),a=y(e,t),o=b(r);n.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:a,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:(n.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 a("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:x,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)}completeFetchedProfiles(e,t){const r=new Map(e.map(e=>[e.profile.userId,e.profile]));return t.map(e=>r.get(e)??{userId:e})}normalizeUpdateEnvelope(t,r,s){const a=e(t)?t:null,n=(a&&e(a.data)?a.data:null)??(a&&this.looksLikeUserInfoAttributes(a)?a:null),o=a&&"number"==typeof a.lastModified?a.lastModified:void 0;return{profile:n?this.toUserInfo(r,n):{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 a of C)a in t&&(s[a]=t[a]);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)}};O.key="userInfoManager";let T=O;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 a,l as n,S as o,R as i,m as d,C as u}from"../../chunks/common-DHQukb7J.js";import{c,b as l,a as p,d as h,e as f,f as m,g as b,h as y,i as I}from"../../chunks/user-info-7QzMa7bR.js";import{a as g}from"../../chunks/event-system-DguqwFpc.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")=>c(e,t),w=e=>{const t=_(e);if(t.length>100)throw((e,t,r,n=s.VALIDATION_INVALID_FORMAT)=>new a(e,{code:n,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"],x=d(u,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},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}}}}}),O=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,a=(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(!a)return;const o=r.applyUserInfoNotifyPatch(a);if(!o.applied)return void n.debug("User-info notify ignored",{userId:a.userId,notifyType:s.notifyType,reason:o.reason,lastModified:a.lastModified});if(r.updateUserInfoSummaryFromRuntime(a.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:a.userId,lastModified:a.lastModified}]),"subscription"===a.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[o.record.profile]);if("own"===a.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",o.record.profile);const i=t.getContactSnapshot()?.items.find(e=>e.userId===a.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=l(c(e.userIds,"params.userIds")),a=p(t);n.debug("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const o=await r.request(a,{method:"POST",body:s,operation:"getUserInfoByUserId"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),this.completeFetchedProfiles(i,s.targets)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=h(c(e.userIds,"params.userIds"),f(e.attributes,"params.attributes")),a=p(t);n.debug("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const o=await r.request(a,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),this.completeFetchedProfiles(i,s.targets)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>U(e))(t),a=w(e.userIds);n.debug("UserInfoManager subscribeUsersInfo",{userIds:a.usernames}),await r.request(s,{method:"POST",body:a,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=v(t,e.userIds);n.debug("UserInfoManager unsubscribeUsersInfo",{userIds:c(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);n.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 a of t.data){if("string"!=typeof a)continue;const e=a.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=m(e),a=b(t);n.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const o=await r.request(a,{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),a=y(e,t),o=b(r);n.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:a,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:(n.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 a("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:x,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)}completeFetchedProfiles(e,t){const r=new Map(e.map(e=>[e.profile.userId,e.profile]));return t.map(e=>r.get(e)??{userId:e})}normalizeUpdateEnvelope(t,r,s){const a=e(t)?t:null,n=(a&&e(a.data)?a.data:null)??(a&&this.looksLikeUserInfoAttributes(a)?a:null),o=a&&"number"==typeof a.lastModified?a.lastModified:void 0;return{profile:n?this.toUserInfo(r,n):{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 a of C)a in t&&(s[a]=t[a]);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)}};O.key="userInfoManager";let T=O;export{T as UserInfoManager};