easemob-websdk 5.1.3 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-types.d.ts +2 -2
  3. package/chat-client.d.ts +17 -2
  4. package/chunks/chat-manager-BB7wYWYG.js +2 -0
  5. package/chunks/chat-manager-auF_3s3R.cjs +1 -0
  6. package/chunks/common-Cg-lTASK.cjs +1 -0
  7. package/chunks/common-gbNWJrBc.js +1 -0
  8. package/chunks/{group-user-info-resolver-B-dyr__b.cjs → group-user-info-resolver-BNwtC7dY.cjs} +1 -1
  9. package/chunks/{group-user-info-resolver-D6AQAHEE.js → group-user-info-resolver-rs5Fnr0l.js} +1 -1
  10. package/chunks/index-BUNbI8gf.cjs +1 -0
  11. package/chunks/index-BxMCMoWN.js +1 -0
  12. package/chunks/index-C7fO2X0x.cjs +1 -0
  13. package/chunks/index-C_EMU0-3.js +1 -0
  14. package/chunks/index-CsqE2tfH.js +1 -0
  15. package/chunks/index-DeJuR3uW.cjs +1 -0
  16. package/chunks/index-Dknccp9Q.js +1 -0
  17. package/chunks/index-P1vnLSK2.cjs +1 -0
  18. package/chunks/multibody-content-BHb-Au8Q.js +1 -0
  19. package/chunks/multibody-content-BmdQukoX.cjs +1 -0
  20. package/chunks/{push-manager-CSIKhoPe.js → push-manager-BO3xq-7O.js} +1 -1
  21. package/chunks/{push-manager-D7RDsKuv.cjs → push-manager-DMI0G9v9.cjs} +1 -1
  22. package/chunks/reflection-proto-codec-B1apL0ws.js +1 -0
  23. package/chunks/reflection-proto-codec-CYglS_mx.cjs +1 -0
  24. package/chunks/session-list-query-DMe2GZ4v.cjs +1 -0
  25. package/chunks/session-list-query-Inseic9m.js +1 -0
  26. package/chunks/{user-info-DH3aE1gm.cjs → user-info-B5St7axd.cjs} +1 -1
  27. package/chunks/{user-info-7QzMa7bR.js → user-info-BkqJHgja.js} +1 -1
  28. package/core/index.d.ts +1 -1
  29. package/core/message/attachment-downloader.d.ts +4 -1
  30. package/core/message/message-sender.d.ts +19 -4
  31. package/core/message/prepare-text-translation.d.ts +7 -0
  32. package/index.cjs +1 -1
  33. package/index.d.ts +3 -2
  34. package/index.js +2 -2
  35. package/managers/chat/index.cjs +1 -1
  36. package/managers/chat/index.js +1 -1
  37. package/managers/chat-manager.d.ts +128 -7
  38. package/managers/chat-thread/index.cjs +1 -1
  39. package/managers/chat-thread/index.js +1 -1
  40. package/managers/chatroom/index.cjs +1 -1
  41. package/managers/chatroom/index.js +1 -1
  42. package/managers/contact/index.cjs +1 -1
  43. package/managers/contact/index.js +1 -1
  44. package/managers/group/index.cjs +1 -1
  45. package/managers/group/index.js +1 -1
  46. package/managers/presence/index.cjs +1 -1
  47. package/managers/presence/index.js +1 -1
  48. package/managers/push/index.cjs +1 -1
  49. package/managers/push/index.js +1 -1
  50. package/managers/user-info/index.cjs +1 -1
  51. package/managers/user-info/index.js +1 -1
  52. package/message/combine-payload-codec.d.ts +2 -2
  53. package/message/combine-payload-file.d.ts +11 -0
  54. package/message/create-message.d.ts +16 -4
  55. package/message/create-multibody-message.d.ts +31 -0
  56. package/message/message-snapshot.d.ts +2 -1
  57. package/message/multibody-content.d.ts +35 -0
  58. package/message/translations.d.ts +7 -0
  59. package/package.json +1 -1
  60. package/platform/image/miniapp-image-processor.d.ts +10 -6
  61. package/protocol/msync/codec.d.ts +3 -0
  62. package/protocol/msync/message-payload-decoder.d.ts +5 -1
  63. package/protocol/session-list/payload-decoder.d.ts +2 -2
  64. package/types/chat-manager.d.ts +2 -2
  65. package/types/conversation.d.ts +2 -2
  66. package/types/index.d.ts +33 -9
  67. package/types/message-create.d.ts +130 -2
  68. package/upload/attachment-uploader.d.ts +8 -0
  69. package/validators/message-create.d.ts +25 -2
  70. package/chunks/chat-manager-BI-6bEor.cjs +0 -1
  71. package/chunks/chat-manager-nXOTpJ01.js +0 -2
  72. package/chunks/common-DHQukb7J.js +0 -1
  73. package/chunks/common-tHGz9VBk.cjs +0 -1
  74. package/chunks/index-CneY58NJ.js +0 -1
  75. package/chunks/index-DJPAjXAp.cjs +0 -1
  76. package/chunks/index-DtWkVcfb.cjs +0 -1
  77. package/chunks/index-DxjmfFL7.js +0 -1
  78. package/chunks/reflection-proto-codec-7r8Sei3y.js +0 -1
  79. package/chunks/reflection-proto-codec-CwrIKT1L.cjs +0 -1
  80. package/chunks/session-list-query-C3iQvQxK.cjs +0 -1
  81. package/chunks/session-list-query-Cdpiw_IZ.js +0 -1
@@ -1 +1 @@
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
+ 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-gbNWJrBc.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-BkqJHgja.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
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-DtWkVcfb.cjs");exports.ContactManager=e.ContactManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-DeJuR3uW.cjs");exports.ContactManager=e.ContactManager;
@@ -1 +1 @@
1
- import{C as a}from"../../chunks/index-CneY58NJ.js";export{a as ContactManager};
1
+ import{C as a}from"../../chunks/index-C_EMU0-3.js";export{a as ContactManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-DJPAjXAp.cjs");exports.Group=e.Group,exports.GroupManager=e.GroupManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-C7fO2X0x.cjs");exports.Group=e.Group,exports.GroupManager=e.GroupManager;
@@ -1 +1 @@
1
- import{G as r,a as o}from"../../chunks/index-DxjmfFL7.js";export{r as Group,o as GroupManager};
1
+ import{G as r,a as o}from"../../chunks/index-BxMCMoWN.js";export{r as Group,o as GroupManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-tHGz9VBk.cjs"),t=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{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}}}}}),r=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:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${r.clientResource}/1`,o={ext:t.customStatus};e.logger.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:o,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:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${t.expiry}`,o={usernames:t.userIds};e.logger.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const u=await s.request(n,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(u)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`;e.logger.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:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.logger.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const o=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`,o={usernames:t.userIds};e.logger.debug("Call getPresenceStatus",{userIds:t.userIds});const u=await s.request(n,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(u)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.logger.warn(`PresenceManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(t,r){return r instanceof e.SDKError?r:r instanceof Error?new e.SDKError(`PresenceManager ${t} failed: ${r.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`PresenceManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("PresenceManager is not bound to event context",{code:e.ERROR_CODES.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 e.ValidationError("PresenceManager is not bound to client",{code:e.ERROR_CODES.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(r){return this.restClient&&this.restBaseUrl===r.restBaseUrl&&this.restToken===r.token||(this.restClient=new e.RestClient(r.restBaseUrl,{errorMap:t,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(r.token),this.restBaseUrl=r.restBaseUrl,this.restToken=r.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,i]of Object.entries(e))if("number"==typeof i&&Number.isFinite(i))r[s]=Math.trunc(i);else if("string"==typeof i&&i.trim().length>0){const e=Number(i);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(t){return new e.ValidationError("Invalid parameters",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};r.key="presenceManager";let s=r;exports.PresenceManager=s;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-Cg-lTASK.cjs"),t=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{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}}}}}),r=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:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${r.clientResource}/1`,o={ext:t.customStatus};e.logger.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:o,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:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${t.expiry}`,o={usernames:t.userIds};e.logger.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const u=await s.request(n,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(u)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`;e.logger.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:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.logger.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const o=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`,o={usernames:t.userIds};e.logger.debug("Call getPresenceStatus",{userIds:t.userIds});const u=await s.request(n,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(u)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.logger.warn(`PresenceManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(t,r){return r instanceof e.SDKError?r:r instanceof Error?new e.SDKError(`PresenceManager ${t} failed: ${r.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`PresenceManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("PresenceManager is not bound to event context",{code:e.ERROR_CODES.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 e.ValidationError("PresenceManager is not bound to client",{code:e.ERROR_CODES.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(r){return this.restClient&&this.restBaseUrl===r.restBaseUrl&&this.restToken===r.token||(this.restClient=new e.RestClient(r.restBaseUrl,{errorMap:t,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(r.token),this.restBaseUrl=r.restBaseUrl,this.restToken=r.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,i]of Object.entries(e))if("number"==typeof i&&Number.isFinite(i))r[s]=Math.trunc(i);else if("string"==typeof i&&i.trim().length>0){const e=Number(i);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(t){return new e.ValidationError("Invalid parameters",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};r.key="presenceManager";let s=r;exports.PresenceManager=s;
@@ -1 +1 @@
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
+ 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-gbNWJrBc.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/push-manager-D7RDsKuv.cjs");exports.PushManager=e.PushManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/push-manager-DMI0G9v9.cjs");exports.PushManager=e.PushManager;
@@ -1 +1 @@
1
- import{P as a}from"../../chunks/push-manager-CSIKhoPe.js";export{a as PushManager};
1
+ import{P as a}from"../../chunks/push-manager-BO3xq-7O.js";export{a as PushManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/cache-utils-gowrxNr8.cjs"),t=require("../../chunks/profile-version-njNs7R5-.cjs"),r=require("../../chunks/common-tHGz9VBk.cjs"),s=require("../../chunks/user-info-DH3aE1gm.cjs"),n=require("../../chunks/event-system-TYhmgy4K.cjs"),a=e=>{const{orgName:t,appName:s}=r.parseAppKey(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},o=(e,t="params.userIds")=>s.normalizeUserInfoTargetIds(e,t),i=e=>{const t=o(e);if(t.length>100)throw((e,t,s,n=r.ERROR_CODES.VALIDATION_INVALID_FORMAT)=>new r.ValidationError(e,{code:n,details:{fields:[{path:t,message:e,rule:s}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",r.ERROR_CODES.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},d=(e,t)=>{const r=(e=>o(e))(t);return`${a(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},u=(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"],l=r.mergeRuntimeErrorMaps(r.COMMON_ERROR_MAP,{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}}}}}),p=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,s=t?.getCacheManager();if(!t||!s||!t.getCurrentUserId())return;const a=e.payload,o=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=u(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"}})(a);if(!o)return;const i=s.applyUserInfoNotifyPatch(o);if(!i.applied)return void r.logger.debug("User-info notify ignored",{userId:o.userId,notifyType:a.notifyType,reason:i.reason,lastModified:o.lastModified});if(s.updateUserInfoSummaryFromRuntime(o.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:o.userId,lastModified:o.lastModified}]),"subscription"===o.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===o.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const d=t.getContactSnapshot()?.items.find(e=>e.userId===o.userId);this.eventContext?.dispatch?.(n.ContactEventName.CONTACT_INFO_UPDATED,{userInfo:i.record.profile,contact:d})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByUserIdRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByUserId",{userIds:a.targets});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByUserId"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),this.completeFetchedProfiles(d,a.targets)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByAttributeRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds"),s.normalizeUserInfoAttributes(e.attributes,"params.attributes")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByAttribute",{userIds:a.targets,attributes:a.properties});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByAttribute"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),this.completeFetchedProfiles(d,a.targets)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),s=this.getRestClient(t),n=(e=>a(e))(t),o=i(e.userIds);r.logger.debug("UserInfoManager subscribeUsersInfo",{userIds:o.usernames}),await s.request(n,{method:"POST",body:o,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=d(t,e.userIds);r.logger.debug("UserInfoManager unsubscribeUsersInfo",{userIds:s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")}),await n.request(a,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),s=(e=>a(e))(e);r.logger.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const n=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(s,{method:"GET",operation:"getSubscribedUsers"}));return 0===n.length?[]:await this.getUserInfoByUserId({userIds:n})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildUpdateOwnInfoFormBody(e),o=s.buildUserInfoUpdateEndpoint(t);r.logger.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await n.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a,operation:"updateOwnInfo"}),d=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const n=this.getRestContextOrThrow(),a=this.getRestClient(n),o=s.buildUpdateOwnInfoByAttributeFormBody(e,t),i=s.buildUserInfoUpdateEndpoint(n);r.logger.debug("UserInfoManager updateOwnInfoByAttribute",{userId:n.userId,attribute:e});const d=await a.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o,operation:"updateOwnInfoByAttribute"}),u=this.normalizeUpdateEnvelope(d,n.userId,{userId:n.userId,[e]:t});return this.writeCache([u]),this.dispatchSelfUpdate(u.profile),u.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof r.SDKError?t:(r.logger.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new r.SDKError(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new r.ValidationError("UserInfoManager is not bound to client",{code:r.ERROR_CODES.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 r.RestClient(e.restBaseUrl,{errorMap:l,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 s.normalizeUserInfoFetchRecords(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 n=e.isRecord(t)?t:null,a=(n&&e.isRecord(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e.isRecord(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of c)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return c.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t.normalizeProfileVersionFromTimestamp(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)}};p.key="userInfoManager";let h=p;exports.UserInfoManager=h;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/cache-utils-gowrxNr8.cjs"),t=require("../../chunks/profile-version-njNs7R5-.cjs"),r=require("../../chunks/common-Cg-lTASK.cjs"),s=require("../../chunks/user-info-B5St7axd.cjs"),n=require("../../chunks/event-system-TYhmgy4K.cjs"),a=e=>{const{orgName:t,appName:s}=r.parseAppKey(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},o=(e,t="params.userIds")=>s.normalizeUserInfoTargetIds(e,t),i=e=>{const t=o(e);if(t.length>100)throw((e,t,s,n=r.ERROR_CODES.VALIDATION_INVALID_FORMAT)=>new r.ValidationError(e,{code:n,details:{fields:[{path:t,message:e,rule:s}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",r.ERROR_CODES.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},d=(e,t)=>{const r=(e=>o(e))(t);return`${a(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},u=(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"],l=r.mergeRuntimeErrorMaps(r.COMMON_ERROR_MAP,{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}}}}}),p=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,s=t?.getCacheManager();if(!t||!s||!t.getCurrentUserId())return;const a=e.payload,o=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=u(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"}})(a);if(!o)return;const i=s.applyUserInfoNotifyPatch(o);if(!i.applied)return void r.logger.debug("User-info notify ignored",{userId:o.userId,notifyType:a.notifyType,reason:i.reason,lastModified:o.lastModified});if(s.updateUserInfoSummaryFromRuntime(o.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:o.userId,lastModified:o.lastModified}]),"subscription"===o.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===o.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const d=t.getContactSnapshot()?.items.find(e=>e.userId===o.userId);this.eventContext?.dispatch?.(n.ContactEventName.CONTACT_INFO_UPDATED,{userInfo:i.record.profile,contact:d})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByUserIdRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByUserId",{userIds:a.targets});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByUserId"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),this.completeFetchedProfiles(d,a.targets)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByAttributeRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds"),s.normalizeUserInfoAttributes(e.attributes,"params.attributes")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByAttribute",{userIds:a.targets,attributes:a.properties});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByAttribute"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),this.completeFetchedProfiles(d,a.targets)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),s=this.getRestClient(t),n=(e=>a(e))(t),o=i(e.userIds);r.logger.debug("UserInfoManager subscribeUsersInfo",{userIds:o.usernames}),await s.request(n,{method:"POST",body:o,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=d(t,e.userIds);r.logger.debug("UserInfoManager unsubscribeUsersInfo",{userIds:s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")}),await n.request(a,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),s=(e=>a(e))(e);r.logger.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const n=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(s,{method:"GET",operation:"getSubscribedUsers"}));return 0===n.length?[]:await this.getUserInfoByUserId({userIds:n})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildUpdateOwnInfoFormBody(e),o=s.buildUserInfoUpdateEndpoint(t);r.logger.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await n.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a,operation:"updateOwnInfo"}),d=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const n=this.getRestContextOrThrow(),a=this.getRestClient(n),o=s.buildUpdateOwnInfoByAttributeFormBody(e,t),i=s.buildUserInfoUpdateEndpoint(n);r.logger.debug("UserInfoManager updateOwnInfoByAttribute",{userId:n.userId,attribute:e});const d=await a.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o,operation:"updateOwnInfoByAttribute"}),u=this.normalizeUpdateEnvelope(d,n.userId,{userId:n.userId,[e]:t});return this.writeCache([u]),this.dispatchSelfUpdate(u.profile),u.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof r.SDKError?t:(r.logger.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new r.SDKError(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new r.ValidationError("UserInfoManager is not bound to client",{code:r.ERROR_CODES.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 r.RestClient(e.restBaseUrl,{errorMap:l,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 s.normalizeUserInfoFetchRecords(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 n=e.isRecord(t)?t:null,a=(n&&e.isRecord(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e.isRecord(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of c)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return c.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t.normalizeProfileVersionFromTimestamp(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)}};p.key="userInfoManager";let h=p;exports.UserInfoManager=h;
@@ -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,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};
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-gbNWJrBc.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-BkqJHgja.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};
@@ -1,4 +1,4 @@
1
- import type { ChatConversationType, Message, MessageType, Sender } from '../types';
1
+ import type { ChatConversationType, Message, MessageBody, MessageType, Sender } from '../types';
2
2
  /** 合并消息解码后的子消息结构(内部类型) */
3
3
  interface CombineMessageItem {
4
4
  msgServerId?: string;
@@ -8,7 +8,7 @@ interface CombineMessageItem {
8
8
  conversationId: string;
9
9
  conversationType: ChatConversationType;
10
10
  timestamp: number;
11
- body: Record<string, unknown>;
11
+ body: MessageBody;
12
12
  ext?: Record<string, unknown>;
13
13
  combineLevel?: number;
14
14
  }
@@ -0,0 +1,11 @@
1
+ import { type RuntimeDetectionInput } from '../platform/env';
2
+ import type { CompatibleFile } from '../types';
3
+ export interface MaterializeCombinePayloadFileOptions {
4
+ readonly payload: Uint8Array;
5
+ readonly filename: string;
6
+ readonly filetype: string;
7
+ readonly fileId: string;
8
+ readonly runtime?: RuntimeDetectionInput;
9
+ }
10
+ export declare const materializeCombinePayloadFile: (options: MaterializeCombinePayloadFileOptions) => Promise<CompatibleFile>;
11
+ export declare const removeCombinePayloadFile: (file: CompatibleFile | undefined, runtime?: RuntimeDetectionInput) => Promise<void>;
@@ -1,21 +1,33 @@
1
1
  /**
2
2
  * 消息创建方法
3
3
  */
4
- import type { // 跨端文件类型
4
+ import type { // 合并消息体
5
+ CompatibleFile, // 跨端文件类型
5
6
  CreateCmdMessageParams, // 命令消息入参
6
7
  CreateCombineMessageParams, // 合并消息入参
7
8
  CreateCustomMessageParams, // 自定义消息入参
8
9
  CreateFileMessageParams, // 文件消息入参
9
10
  CreateImageMessageParams, // 图片消息入参
10
- CreateLocationMessageParams, // 创建消息基础入参
11
+ CreateLocationMessageParams, // 位置消息入参
12
+ CreateMessageBaseParams, // 创建消息基础入参
11
13
  CreateTextMessageParams, // 文本消息入参
12
14
  CreateVideoMessageParams, // 视频消息入参
13
15
  CreateVoiceMessageParams, // 位置消息体
14
- Message, // 消息类型联合
15
- Sender } from '../types';
16
+ Message, // 消息类型
17
+ MessageBody, // 消息体联合类型
18
+ MessageType, // 消息类型联合
19
+ MultiBodySegment, Sender } from '../types';
20
+ export declare const ensureSender: (sender?: Sender) => Sender;
21
+ export declare const resolveMediaUrl: (url: string | undefined, data?: CompatibleFile) => string;
16
22
  interface CreateImageMessageOptions {
17
23
  useCustomAttachmentUpload?: boolean;
18
24
  }
25
+ export declare const buildMessage: (params: CreateMessageBaseParams, // 通用入参
26
+ sender: Sender, // 发送者信息
27
+ type: Exclude<MessageType, "multi_body">, // 消息类型
28
+ body: MessageBody, // 消息体
29
+ msgLocalId?: string) => Message;
30
+ export declare const buildMultiBodyMessage: (params: CreateMessageBaseParams, sender: Sender, bodies: ReadonlyArray<MultiBodySegment>, msgLocalId?: string) => Message;
19
31
  /**
20
32
  * 创建文本消息
21
33
  */
@@ -0,0 +1,31 @@
1
+ import type { CreateMultiBodyMessageParams, CreateCustomMessageBodyParams, CreateFileMessageBodyParams, CreateImageMessageBodyParams, CreateLocationMessageBodyParams, CreateTextMessageBodyParams, CreateVideoMessageBodyParams, CreateVoiceMessageBodyParams, CustomMessageBody, FileMessageBody, ImageMessageBody, LocationMessageBody, Message, Sender, TextMessageBody, VideoMessageBody, VoiceMessageBody } from '../types';
2
+ interface CreateImageMessageBodyOptions {
3
+ readonly useCustomAttachmentUpload?: boolean;
4
+ }
5
+ export declare const createTextMessageBody: (params: CreateTextMessageBodyParams) => {
6
+ type: "text";
7
+ } & TextMessageBody;
8
+ export declare const createImageMessageBody: (params: CreateImageMessageBodyParams, options?: CreateImageMessageBodyOptions) => {
9
+ type: "image";
10
+ } & ImageMessageBody;
11
+ export declare const createFileMessageBody: (params: CreateFileMessageBodyParams) => {
12
+ type: "file";
13
+ } & FileMessageBody;
14
+ export declare const createVoiceMessageBody: (params: CreateVoiceMessageBodyParams) => {
15
+ type: "voice";
16
+ } & VoiceMessageBody;
17
+ export declare const createVideoMessageBody: (params: CreateVideoMessageBodyParams) => {
18
+ type: "video";
19
+ } & VideoMessageBody;
20
+ export declare const createLocationMessageBody: (params: CreateLocationMessageBodyParams) => {
21
+ type: "location";
22
+ } & LocationMessageBody;
23
+ export declare const createCustomMessageBody: (params: CreateCustomMessageBodyParams) => {
24
+ type: "custom";
25
+ } & CustomMessageBody;
26
+ /**
27
+ * 组装复合消息。校验不通过时不取走本地文件。
28
+ * 通过后把文件从分段对象挪到 `msgLocalId:bodyIndex`,发送时按这个 key 找文件。
29
+ */
30
+ export declare const createMultiBodyMessage: (params: CreateMultiBodyMessageParams, sender?: Sender) => Message;
31
+ export {};
@@ -5,4 +5,5 @@ export declare const projectMessageMetadata: (value: unknown) => Omit<Partial<Me
5
5
  /** @internal Stable comparison for message snapshots; object key order has no business meaning. */
6
6
  export declare const messageSnapshotSignature: (value: unknown) => string;
7
7
  /** @internal A shallow serializable body projection without expanding combined-message details. */
8
- export declare const projectMessageBody: (body: MessageBody | Record<string, unknown>) => Record<string, unknown>;
8
+ export declare const projectMessageSegments: (bodies: ReadonlyArray<Record<string, unknown>>) => ReadonlyArray<Record<string, unknown>>;
9
+ export declare const projectMessageBody: (body: MessageBody | Record<string, unknown> | ReadonlyArray<Record<string, unknown>>) => Record<string, unknown> | ReadonlyArray<Record<string, unknown>>;