easemob-websdk 5.1.2 → 5.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-manager.d.ts +11 -3
- package/cache/cache-types.d.ts +13 -2
- package/chat-client.d.ts +6 -0
- package/chunks/{chat-manager-BFd2Z4oY.cjs → chat-manager-BI-6bEor.cjs} +1 -1
- package/chunks/{chat-manager-CId_M_e5.js → chat-manager-nXOTpJ01.js} +2 -2
- package/chunks/{common-BvlDAw4a.js → common-DHQukb7J.js} +1 -1
- package/chunks/{event-system-B62vbKqG.js → event-system-DguqwFpc.js} +1 -1
- package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-D6AQAHEE.js} +1 -1
- package/chunks/{index-BBFJYOM8.js → index-CneY58NJ.js} +1 -1
- package/chunks/index-DxjmfFL7.js +1 -0
- package/chunks/push-manager-CSIKhoPe.js +1 -0
- package/chunks/push-manager-D7RDsKuv.cjs +1 -0
- package/chunks/session-list-query-C3iQvQxK.cjs +1 -0
- package/chunks/session-list-query-Cdpiw_IZ.js +1 -0
- package/chunks/{user-info-AlshAvdy.js → user-info-7QzMa7bR.js} +1 -1
- package/core/session-list-sync/session-list-message-events.d.ts +9 -0
- package/index.cjs +1 -1
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.js +1 -1
- package/message/message-snapshot.d.ts +8 -0
- package/package.json +1 -1
- package/protocol/msync/codec.d.ts +1 -21
- package/protocol/msync/message-identity.d.ts +2 -0
- package/protocol/msync/message-payload-decoder.d.ts +35 -0
- package/protocol/session-list/gateway.d.ts +8 -1
- package/protocol/session-list/payload-decoder.d.ts +12 -0
- package/types/conversation.d.ts +27 -20
- package/utils/session-message-recipient.d.ts +11 -0
- package/chunks/index-l_BUKi77.js +0 -1
- package/chunks/session-list-query-Cvr6rlme.js +0 -1
- package/chunks/session-list-query-Dslj2k3t.cjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e}from"./cache-utils-B99glc0H.js";import{p as t,V as r,E as o,S as s,A as n,aa as a,l as i,n as u,aM as p,o as d,q as c,L as m,aN as l,R as h,m as g,C as I}from"./common-DHQukb7J.js";import{a as y}from"./profile-version-DLMz8lqW.js";import{m as f,g as _,r as w,a as G}from"./group-user-info-resolver-D6AQAHEE.js";import{G as b}from"./event-system-DguqwFpc.js";import{c as v}from"./query-params-Bu3Xq4b6.js";import{b as R,a as S,n as A}from"./user-info-7QzMa7bR.js";import{l as U}from"./light-DImBnNes.js";import{L as E,a as C,b as O}from"./reflection-proto-codec-7r8Sei3y.js";const T=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],M=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),D=e=>({userId:e}),N=(e,t,r)=>{const o={userId:r};for(const s of T){const r=t?.[s]??e?.[s];void 0!==r&&(o[s]=r)}return o},L=async(e,t)=>{const r=(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})(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const s=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const a of s)o.set(a.userId,M(a));const n=r.filter(e=>!o.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)o.set(t.userId,t)}for(const a of r)o.has(a)||o.set(a,D(a));return o},F=t=>e(t)?t:null,P=e=>{if("string"==typeof e)return e},$=e=>{const t=P(e)?.trim();return t||void 0},j=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}},x=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},k=e=>{const t=F(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},J=e=>{const t=F(e);return t?F(t.data)?t.data:t:null},q=(e,t)=>{const r=F(e),o=r&&F(r.params),s=o?.[t];if(Array.isArray(s)&&0!==s.length)return j(s[0])},B=(e,t)=>{const r=(e=>{const t=F(e);return t?j(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},H=e=>$(e.groupId)??$(e.groupid)??$(e.id)??"",V=e=>P(e.name)??P(e.groupname)??P(e.groupName)??"",K=e=>{const t=k(e),r=F(t[0])??J(e)??{},o=(e=>{const t=F(e);if(!t)return null;const r=H(t);return r?{groupId:r,name:V(t),description:P(t.description),memberCount:j(t.memberCount)??j(t.affiliations_count),public:x(t.public),joinApprovalRequired:x(t.joinApprovalRequired)??x(t.approval)??x(t.membersonly)??x(t.members_only),allowInvites:x(t.allowInvites)??x(t.allowinvites)??x(t.allow_user_invites),maxMembers:j(t.maxMembers)??j(t.maxusers),role:$(t.role)??$(t.permission),disabled:x(t.disabled)}:null})(r)??{groupId:H(r),name:V(r)},s=$(r.owner)??$(r.admin)??$(r.member),n=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>F(e)).filter(e=>null!==e).map(e=>j(e.joined_time)).find(e=>void 0!==e);return{...o,owner:s?D(s):void 0,inviteNeedConfirm:x(r.inviteNeedConfirm)??x(r.invite_need_confirm),muteAllMembers:x(r.mute),ext:P(r.ext)??P(r.custom),createdAt:j(r.createdAt)??j(r.created),joinedAt:n,avatarUrl:P(r.avatar),messageBlocked:x(r.messageBlocked)??x(r.isMessageBlocked)??x(r.shieldgroup)}},z=e=>D(e),W=e=>k(e).map(e=>$(e)).filter(e=>Boolean(e)).map(e=>z(e)),Q=e=>{const t=F(e);if(!t)return null;const r=$(t.fileId)??$(t.file_id);if(!r)return null;const o=P(t.fileName)??P(t.file_name)??r,s=$(t.fileOwner)??$(t.file_owner);return{fileId:r,fileName:o,fileOwner:s?z(s):void 0,fileSize:j(t.fileSize)??j(t.file_size),createdAt:j(t.createdAt)??j(t.created)}},Y=100,X=3e3,Z=e=>({...e}),ee=e=>"object"==typeof e&&null!==e,te=e=>"DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e?e:"mentionOnly"===e?"AT":"mute"===e?"NONE":"default"===e?"DEFAULT":2===e?"AT":3===e?"NONE":0===e?"DEFAULT":1===e?"ALL":void 0;class re{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return ee(t=e)&&"string"==typeof t.groupId&&0!==t.groupId.length?{groupId:t.groupId,name:"string"==typeof t.name?t.name:"",description:"string"==typeof t.description?t.description:void 0,memberCount:"number"==typeof t.memberCount?t.memberCount:void 0,role:"owner"===t.role||"admin"===t.role||"member"===t.role?t.role:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,ownerId:"string"==typeof t.ownerId?t.ownerId:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:void 0,muteAllMembers:"boolean"==typeof t.muteAllMembers?t.muteAllMembers:void 0,muteExpiration:"number"==typeof t.muteExpiration?t.muteExpiration:void 0,remindType:te(t.remindType),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,updatedAt:"number"==typeof t.updatedAt?t.updatedAt:void 0,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null;var t}).filter(e=>null!==e):[];this.items=t.slice(0,Y),this.meta=(e=>{const t=ee(e)?e:{};return{integrity:"synced"===t.integrity||"limited"===t.integrity||"incomplete"===t.integrity||"unknown"===t.integrity?t.integrity:"preview",limited:!0===t.limited,storageLimit:"number"==typeof t.storageLimit?t.storageLimit:Y,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:X,source:"localPreview",lastSyncFinishedTs:"number"==typeof t.lastSyncFinishedTs?t.lastSyncFinishedTs:void 0,lastSuccessfulAt:"number"==typeof t.lastSuccessfulAt?t.lastSuccessfulAt:void 0,reason:"string"==typeof t.reason?t.reason:void 0}})(e.meta)}setSnapshot(e){this.items=e.items.map(e=>Z(e)).slice(0,Y),this.meta={...e.meta,source:"localPreview",storageLimit:Y,serverLimit:X,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}}class oe{constructor(e,t){this.groupId=e,this.manager=t}getSummary(){return this.manager.getGroupSummaryForHandle(this.groupId)}getDetail(){return this.manager.getGroupDetailForHandle(this.groupId)}refresh(){return this.manager.refreshGroupDetailForHandle(this.groupId)}updateInfo(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}updateConfigs(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}changeOwner(e){return this.manager.changeGroupOwner({groupId:this.groupId,newOwner:e.newOwner})}destroy(){return this.manager.destroyGroup(this.toTarget())}leave(){return this.manager.leaveGroup(this.toTarget())}getMembers(e={}){return this.manager.getGroupMemberList({groupId:this.groupId,...e})}removeMembers(e){return this.manager.removeGroupMembers(this.toUserBatchParams(e))}getAdmins(){return this.manager.getGroupAdminList(this.toTarget())}addAdmin(e){return this.manager.addGroupAdmin({groupId:this.groupId,userId:e.userId})}removeAdmin(e){return this.manager.removeGroupAdmin({groupId:this.groupId,userId:e.userId})}getMuteList(e){return this.manager.getGroupMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteGroupMembers({groupId:this.groupId,userIds:e.userIds,muteDuration:e.muteDuration})}unmuteMembers(e){return this.manager.unmuteGroupMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllGroupMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllGroupMembers(this.toTarget())}getBlocklist(e){return this.manager.getGroupBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockGroupMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockGroupMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getGroupAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToGroupAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromGroupAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInGroupAllowList({groupId:this.groupId})}checkIfInMuteList(){return this.manager.checkIfInGroupMuteList(this.toTarget())}getAnnouncement(){return this.manager.getGroupAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateGroupAnnouncement({groupId:this.groupId,announcement:e.announcement})}getSharedFileList(e={}){return this.manager.getGroupSharedFileList({groupId:this.groupId,...e})}uploadSharedFile(e){return this.manager.uploadGroupSharedFile({groupId:this.groupId,...e})}deleteSharedFile(e){return this.manager.deleteGroupSharedFile({groupId:this.groupId,fileId:e.fileId})}downloadSharedFile(e){return this.manager.downloadGroupSharedFile({groupId:this.groupId,...e})}setMemberAttributes(e){return this.manager.setGroupMemberAttributes({groupId:this.groupId,userId:e.userId,memberAttributes:e.memberAttributes})}getMembersAttributes(e){return this.manager.getGroupMembersAttributes({groupId:this.groupId,userIds:e.userIds,keys:e.keys})}toTarget(){return{groupId:this.groupId}}toUserBatchParams(e){return{groupId:this.groupId,userIds:e.userIds}}}const se=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},ne=e=>new r(`${e} is required`,{code:o.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),ae=(e,t)=>new r(t,{code:o.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),ie=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw ne(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,s)=>{if("string"!=typeof e)throw ae(`${t}[${s}]`,`${t}[${s}] must be a string`);const n=e.trim();n&&!o.has(n)&&(o.add(n),r.push(n))}),0===r.length)throw ne(t);return r},ue=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw ne(t);return e.trim()},pe=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw ae(t,`${t} must be a string`);return e}},de=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw ae(t,`${t} must be a boolean`);return e}},ce=(e,t)=>`/${e.orgName}/${e.appName}${t}`,me=/* @__PURE__ */new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),le=e=>{const t=v();"number"==typeof e?.pageNum&&t.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize));const r=t.toString();return r?`?${r}`:""},he=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups?resource=${o.encodedResource}`);return(e=>{const t=k(e),r=F(t[0]),o=J(e)??r;return{groupId:o&&H(o)||r&&H(r)||""}})(await e.post(s,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?ie(r.memberIds,"params.memberIds"):[],public:r.public,approval:r.joinApprovalRequired,allowinvites:r.allowInvites,invite_need_confirm:r.inviteNeedConfirm,maxusers:r.maxMembers,custom:r.ext,avatar:r.avatar},{operation:"createGroup"}))},ge=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ce(o,`/chatgroups/${encodeURIComponent(s)}?joined_time=true&version=v3`),a=await e.get(n,{operation:"getGroupInfo"});return K(a)},Ie=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n={},a=pe(r.name,"params.name"),i=pe(r.description,"params.description"),u=pe(r.avatar,"params.avatar"),p=pe(r.ext,"params.ext"),d=de(r.public,"params.public"),c=de(r.joinApprovalRequired,"params.joinApprovalRequired"),m=de(r.allowInvites,"params.allowInvites"),l=de(r.inviteNeedConfirm,"params.inviteNeedConfirm"),h=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw ae(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==a&&(n.groupname=a),void 0!==i&&(n.description=i),void 0!==u&&(n.avatar=u),void 0!==p&&(n.custom=p),void 0!==d&&(n.public=d),void 0!==c&&(n.membersonly=c),void 0!==m&&(n.allowinvites=m),void 0!==l&&(n.invite_need_confirm=l),void 0!==h&&(n.maxusers=h),0===Object.keys(n).length)throw ne("params");const g=ce(o,`/chatgroups/${encodeURIComponent(s)}?resource=${o.encodedResource}&version=v3`);await e.put(g,n,{operation:"updateGroupInfo"})},ye=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users${(e=>{const t=v();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const n of k(e)){const e=F(n);if(!e)continue;const r=$(e.owner),o=$(e.admin),s=$(e.member),a=r??o??s;if(!a)continue;const i=j(e.joinedAt)??j(e.joined_time);t.push({user:z(a),role:r?"owner":o?"admin":"member",...void 0===i?{}:{joinedAt:i}})}const r=q(e,"pagenum"),o=q(e,"pagesize"),s=B(e,o);return{items:t,pageNum:r,pageSize:o,...void 0===s?{}:{hasMore:s}}})(await e.get(s,{operation:"getGroupMemberList"}))},fe=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin`),n=await e.get(s,{operation:"getGroupAdminList"});return W(n)},_e=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/mute?version=v3${a}${n.replace("?","")}`);return(e=>{const t=[];for(const r of k(e)){const e=$(r);if(e){t.push({user:z(e)});continue}const o=F(r);if(!o)continue;const s=$(o.user);if(!s)continue;const n=j(o.expire);t.push({user:z(s),...void 0===n?{}:{muteExpire:n}})}return t})(await e.get(i,{operation:"getGroupMuteList"}))},we=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/blocks/users?version=v3${a}${n.replace("?","")}`),u=await e.get(i,{operation:"getGroupBlocklist"});return W(u).map(e=>({user:e}))},Ge=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users`),n=await e.get(s,{operation:"getGroupAllowlist"});return W(n).map(e=>({user:e}))},be=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=J(e)??{};return{announcement:P(t.announcement)??""}})(await e.get(s,{operation:"getGroupAnnouncement"}))},ve=async(e,t,r)=>{const o=se(t),s=v();s.set("pagenum",String(r.pageNum??1)),s.set("pagesize",String(r.pageSize??20));const n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files?${s.toString()}`);return(e=>{const t=q(e,"pagenum"),r=q(e,"pagesize"),o=B(e,r);return{items:k(e).map(e=>Q(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===o?{}:{hasMore:o}}})(await e.get(n,{operation:"getGroupSharedFileList"}))},Re=(e,t)=>{const r=se(e);return ce(r,`/chatgroups/${encodeURIComponent(ue(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(t.fileId,"params.fileId"))}`)},Se=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ue(r.userId,"params.userId"),a=((e,t,r)=>{if(t!==e.userId)return null;const o=Object.entries(r);if(0===o.length)return null;let s;for(const[n,a]of o){if(!me.has(n)||"string"!=typeof a)return null;if(void 0!==s){if(s!==a)return null}else s=a}return void 0===s?null:{nameCard:s}})(t,n,r.memberAttributes);if(a){const t=ce(o,`/sdk/chatgroups/${encodeURIComponent(s)}/nameCard`);return await e.put(t,a,{operation:"setGroupMemberAttributes"})}const i=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(s)}/user/${encodeURIComponent(n)}?resource=${o.encodedResource}`);return await e.put(i,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},Ae=async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/get`);return(e=>{const t=J(e)??{},r=F(t.data)??t,o={};for(const[s,n]of Object.entries(r)){const e=F(n);e&&(o[s]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:o}})(await e.post(s,{targets:ie(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},Ue=t=>{const r=e(t)?t:{},o=r.data,s=e(o)?o.data:void 0,n=Array.isArray(o)?o:Array.isArray(s)?s:null;if(Array.isArray(n))return Ee(n);const a=e(o)?o:r,i=e(a.namecards)?a.namecards:a,u={};for(const[p,d]of Object.entries(i)){if("string"==typeof d){u[p]={namecard:d};continue}if(!e(d))continue;const t=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof t&&(u[p]={namecard:t,namecardUpdateTime:Ce(d)})}return u},Ee=t=>{const r={};return t.forEach(t=>{if(!e(t))return;const o=t.username??t.userId??t.userid??t.user_id,s=t.name_card??t.namecard??t.nameCard??t.groupNamecard??t.group_namecard??t.group_name_card;"string"==typeof o&&o.trim()&&"string"==typeof s&&(r[o.trim()]={namecard:s,namecardUpdateTime:Ce(t)})}),r},Ce=e=>y("number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.timestamp?e.timestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0),Oe=t=>{if(e(t))return y("number"==typeof t.timestamp?t.timestamp:"number"==typeof t.update_timestamp?t.update_timestamp:"number"==typeof t.updateTimestamp?t.updateTimestamp:"number"==typeof t.lastModified?t.lastModified:"number"==typeof t.last_modified?t.last_modified:void 0)};class Te{constructor(e){this.repository=e}applyPatch(e){e.shouldMarkStale&&this.repository.markStale(e.groupId);const t=this.repository.getDetailSnapshot(e.groupId);if(!e.groupPatch)return t;const r=t??{groupId:e.groupId,name:e.groupPatch.name??e.groupName??""};return this.repository.mergeDetail({...r,...e.groupPatch,groupId:e.groupId})}}const Me=e=>({...e}),De=e=>({...e,owner:e.owner?{...e.owner}:void 0});class Ne{constructor(e){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null,this.groupId=e}mergeSummary(e){e.groupId===this.groupId&&(this.summarySnapshot=Me({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=De({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=Me(this.toSummaryFromDetail(this.detailSnapshot)),this.loadedSummary=!0,this.loadedDetail=!0,this.stale=!1,this.lastPatchedAt=Date.now(),this.lastHydratedAt=Date.now())}markStale(){this.stale=!0,this.lastPatchedAt=Date.now()}clear(){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null}getSummarySnapshot(){return this.summarySnapshot?Me(this.summarySnapshot):this.detailSnapshot?Me(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?De(this.detailSnapshot):null}isStale(){return this.stale}hasLoadedSummary(){return this.loadedSummary}hasLoadedDetail(){return this.loadedDetail}getLastPatchedAt(){return this.lastPatchedAt}getLastHydratedAt(){return this.lastHydratedAt}toSummaryFromDetail(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,public:e.public,joinApprovalRequired:e.joinApprovalRequired,allowInvites:e.allowInvites,maxMembers:e.maxMembers,role:e.role,disabled:e.disabled}}}class Le{toSummary(e){const t=e.getSummarySnapshot();return t?(e=>({...e}))(t):null}toDetail(e){const t=e.getDetailSnapshot();return t?(e=>({...e,owner:e.owner?{...e.owner}:void 0}))(t):null}}class Fe{constructor(){this.groups=/* @__PURE__ */new Map,this.joinedGroupById=/* @__PURE__ */new Map,this.removedJoinedGroupIds=/* @__PURE__ */new Set,this.snapshotMapper=new Le,this.joinedGroupSnapshot=null,this.sessionKey=null}ensureSession(e){return this.sessionKey!==e&&(this.sessionKey=e,this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null,!0)}getSessionKey(){return this.sessionKey}getOrCreate(e){const t=this.groups.get(e);if(t)return t;const r=new Ne(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const o=t?.items.find(t=>t.groupId===e);return o?{...o}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const o={...r,...t,groupId:e};return this.joinedGroupById.set(e,o),this.mergeSummary(this.toGroupSummary(o)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...o}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const Pe=0,$e=5,je=12,xe=13,ke=0,Je=1,qe=2,Be=0,He=1,Ve=2,Ke=3,ze=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(o=e.role,o===ke?"owner":o===Je?"admin":o===qe?"member":void 0),disabled:e.disabled,ownerId:e.group_owner,avatarUrl:e.group_avatar,muteAllMembers:e.mute_all,muteExpiration:e.mute_expiration,remindType:(r=e.remind_type,r===Be?"DEFAULT":r===He?"ALL":r===Ve?"AT":r===Ke?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,o},We=e=>e.updatedAt??0,Qe=(e,t)=>{if(!e)return!0;return We(t)>=We(e)},Ye={nested:{easemob:{nested:{joinedgroups:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},GetJoinedGroupsRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},cursor:{type:"string",id:7}}},GroupItem:{fields:{group_id:{type:"string",id:1},group_name:{type:"string",id:2},group_owner:{type:"string",id:3},members_count:{type:"int64",id:4},mute_all:{type:"bool",id:5},disabled:{type:"bool",id:6},description:{type:"string",id:7},group_avatar:{type:"string",id:8},role:{type:"uint32",id:9},mute_expiration:{type:"int64",id:10},remind_type:{type:"int32",id:11},create_at:{type:"uint64",id:12},update_at:{type:"uint64",id:13},joined_timestamp:{type:"int64",id:14}}},GetJoinedGroupsResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},groups:{rule:"repeated",type:"GroupItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5},cursor:{type:"string",id:6}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let Xe=null,Ze=!1;const et=()=>Xe||(Ze||(U.util.Long=E,U.configure(),Ze=!0),C(),Xe=U.Root.fromJSON(Ye),O(Xe),Xe),tt=e=>et().lookupType(e),rt=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(E.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},ot=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:rt(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:rt(t.protocol_version)??rt(t.protocolVersion)??0}};class st{constructor(){this.requestType=tt("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=tt("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=tt("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const o=this.tryDecodeRequest(e);return o||{type:Pe}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==je?null:{type:r,header:ot(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:rt(t.last_sync_time)??rt(t.lastSyncTime)??0,cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==xe?null:{type:r,header:ot(t.header),groups:Array.isArray(t.groups)?t.groups.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{group_id:"string"==typeof t.group_id?t.group_id:"string"==typeof t.groupId?t.groupId:void 0,group_name:"string"==typeof t.group_name?t.group_name:"string"==typeof t.groupName?t.groupName:void 0,group_owner:"string"==typeof t.group_owner?t.group_owner:"string"==typeof t.groupOwner?t.groupOwner:void 0,members_count:rt(t.members_count)??rt(t.membersCount),mute_all:"boolean"==typeof t.mute_all?t.mute_all:"boolean"==typeof t.muteAll?t.muteAll:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,description:"string"==typeof t.description?t.description:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:"string"==typeof t.groupAvatar?t.groupAvatar:void 0,role:rt(t.role),mute_expiration:rt(t.mute_expiration)??rt(t.muteExpiration),remind_type:rt(t.remind_type)??rt(t.remindType),create_at:rt(t.create_at)??rt(t.createAt),update_at:rt(t.update_at)??rt(t.updateAt),joined_timestamp:rt(t.joined_timestamp)??rt(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:rt(t.last_sync_finished_ts)??rt(t.lastSyncFinishedTs),cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==$e?null:{type:r,header:ot(t.header),code:rt(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class nt{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==xe)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new s("Joined groups response received after completion",o.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new s("Joined groups final batch missing lastSyncFinishedTs",o.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const at=e=>e.type===xe,it=e=>e.type===$e;class ut{constructor(e){this.codec=new st,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new nt(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,t,r){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:t,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,t,r.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:at(t)||it(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(at(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(it(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new s(e.message,o.VALIDATION_REQUIRED,{details:t("request_send",!1)});case 1602:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("batch_merge",!0)});case 1002:return new n(e.message,{code:o.AUTH_UNAUTHORIZED,details:t("auth",!1)});case 1003:return new s(e.message,o.SERVICE_LIMIT_EXCEEDED,{details:t("server_limit",!0)});default:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof s?t:new s("Joined groups frame decode failed",o.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class pt{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const r=await this.dependencies.getSyncUrls();if(0===r.length)throw new s("Group sync websocket urls are unavailable",o.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const n=this.buildRequest(),u=await new ut(this.dependencies.getSharedSyncSession()).sync({urls:r,request:n}),p=u.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=ze(r);e&&t.push(e)}return t})(e.groups)),d=this.dependencies.getRuntimeSnapshot(),c=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=/* @__PURE__ */new Map;for(const s of e.incomingItems){const e=r.get(s.groupId)??t.get(s.groupId);Qe(e,s)?r.set(s.groupId,{...e??{},...s,groupId:s.groupId}):e&&r.set(s.groupId,{...e})}const o=r.size>=X;return{items:Array.from(o?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:o?"limited":"synced",limited:o,storageLimit:Y,serverLimit:X,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:d?.items??[],incomingItems:p,lastSyncFinishedTs:u.lastSyncFinishedTs}),m=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(c);const l=this.dependencies.getRuntimeSnapshot()??c;try{await m.commitJoinedGroupPreviewSnapshot(l);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(l,e)&&await m.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw d&&this.dependencies.applyRuntimeSnapshot(d),new a("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}i.warn("Group sync finished",{durationMs:Date.now()-e,itemCount:c.items.length,limited:c.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof s?e:new s("Group sync failed",o.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},n=r.serverCode;return{dataType:"group",code:t.code,stage:(a=r.stage,"config"===a||"socket_connect"===a||"request_send"===a||"response_decode"===a||"batch_merge"===a||"preview_persist"===a||"completion_meta"===a||"auth"===a||"server_limit"===a||"cancelled"===a?a:"socket_connect"),message:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof n||"string"==typeof n?n:void 0};var a})(t);i.warn("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:r,appName:o}=t(e.appKey);return{type:je,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:r,app:o,username:e.userId,lastSyncTime:0}}}const dt=g(I,{common:{},apis:{createGroup:{range:"4,110,204,608",errors:{invalid_parameter:{code:110,httpStatus:400,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:4,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1,aliases:["INVALID_GROUP_NAME"]},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]}}},getJoinedGroupList:{range:"",errors:{}},getGroupInfo:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupInfoList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupInfo:{range:"110,603,606,607,608",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},forbidden_op:{code:603,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:110,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},changeGroupOwner:{range:"603,606",errors:{forbidden_op:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},destroyGroup:{range:"603,606,607",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},leaveGroup:{range:"602,603,606",errors:{not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},owner_cannot_leave:{code:603,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"owner can not quit group"},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},joinGroup:{range:"600-607,613",errors:{group_invalid_id:{code:600,retryable:!1,aliases:["GROUP_INVALID_ID"]},already_joined:{code:601,retryable:!1,aliases:["ALREADY_JOINED","GROUP_ALREADY_JOINED","group_already_joined"]},not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},group_authorization:{code:603,httpStatus:403,retryable:!1,aliases:["NEED_APPROVAL","GROUP_PERMISSION_DENIED"]},group_full:{code:604,httpStatus:403,retryable:!1,aliases:["GROUP_FULL","GROUP_MEMBERS_FULL"],matchField:"error_description",matchPattern:"member list is full"},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["GROUP_NOT_FOUND","service_resource_not_found"]},group_disabled:{code:607,retryable:!1,aliases:["GROUP_DISABLED"]},group_user_in_blocklist:{code:613,httpStatus:403,retryable:!1,aliases:["GROUP_USER_IN_BLOCKLIST"],matchField:"error_description",matchPattern:"is in the blacklist"}}},inviteUsersToGroup:{range:"204,603,606,607",errors:{group_authorization:{code:603,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]},group_not_found:{code:606,retryable:!1,aliases:["GROUP_NOT_FOUND"]},group_disabled:{code:607,retryable:!1}}},acceptGroupJoinRequest:{range:"",errors:{}},rejectGroupJoinRequest:{range:"",errors:{}},acceptInvitation:{range:"",errors:{}},rejectInvitation:{range:"",errors:{}},removeGroupMembers:{range:"",errors:{}},addGroupAdmin:{range:"",errors:{}},removeGroupAdmin:{range:"",errors:{}},muteGroupMembers:{range:"",errors:{}},unmuteGroupMembers:{range:"",errors:{}},muteAllGroupMembers:{range:"",errors:{}},unmuteAllGroupMembers:{range:"",errors:{}},blockGroupMembers:{range:"",errors:{}},unblockGroupMembers:{range:"",errors:{}},addUsersToGroupAllowlist:{range:"",errors:{}},removeUsersFromGroupAllowlist:{range:"",errors:{}},checkIfInGroupAllowList:{range:"",errors:{}},getGroupMemberList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},getGroupAdminList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},checkIfInGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupBlocklist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAllowlist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAnnouncement:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupAnnouncement:{range:"110",errors:{announcement_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce into length exceeds limit"},announcement_info_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce info length exceeds limit"}}},getGroupSharedFileList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["RestGroupFeignException"]}}},deleteGroupSharedFile:{range:"603,605,606",errors:{group_authorization:{code:603,retryable:!1},file_not_found:{code:605,retryable:!1,aliases:["GROUP_SHARED_FILE_INVALID_ID"]},resource_not_found:{code:606,retryable:!1}}},setGroupMemberAttributes:{range:"4,210,302,305,602,609-612",errors:{attributes_reach_limit:{code:609,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT"],matchField:"error_code",matchValue:60006},attributes_update_failed:{code:610,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED"],matchField:"error_code",matchValue:60005},attributes_key_reach_limit:{code:611,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT"],matchField:"error_code",matchValue:60009},attributes_value_reach_limit:{code:612,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT"],matchField:"error_code",matchValue:600010},not_joined:{code:602,httpStatus:404,retryable:!1,matchField:"error_code",matchValue:60003},permission_denied:{code:210,httpStatus:401,retryable:!1,matchField:"error_code",matchValue:60001},permission_denied_403:{code:210,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60002},exceed_service_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60007},service_disabled:{code:305,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60004}}},getGroupMembersAttributes:{range:"606",errors:{resource_not_found:{code:606,retryable:!1}}},getGroupNamecards:{range:"",errors:{}}}}),ct=class{constructor(){this.capabilities=["rawNotify:group","group:namecard"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.groupRegistry=/* @__PURE__ */new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new Fe,this.groupEventSync=new Te(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,o=await this.buildIncomingEventPayload(r,t);if(!o)return;if(this.eventContext?.dispatch?.(r,o),r!==b.GROUP_MEMBER_ATTRIBUTE_CHANGED)return;if(!("attribute"in o)||!("user"in o))return;const s=this.extractGroupNamecard(o.attribute);if(void 0===s||!o.user?.userId)return;const n=this.client?.getCurrentUserId();o.user.userId!==n&&(this.getCacheManager()?.setGroupNamecards([{groupId:o.groupId,userId:o.user.userId,namecard:s,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:o.groupId,userId:o.user.userId,namecard:s}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await he(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const t=e.trim();if(0===t.length)throw new r("groupId is required",{code:o.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const s=this.groupRegistry.get(t);if(s)return s;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const n=new oe(t,this);return this.groupRegistry.set(t,n),n}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,e),o=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(o)})}async getGroupInfoList(t){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const r=this.getRestContextOrThrow(),o=await(async(t,r,o)=>{const s=se(r),n=ie(o.groupIds,"params.groupIds"),a=ce(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),i=await t.get(a,{operation:"getGroupInfoList"});return(e(i)&&Array.isArray(i.data)?i.data:[]).map(e=>K({data:[e]}))})(this.getRestClient(r),r,t),s=await this.hydrateGroupDetailsUsers(o);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,o=e===b.GROUP_DESTROYED?this.resolveLocalGroupName(r.groupId):void 0,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,s),e){case b.INVITATION_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,s),reason:r.reason};case b.REQUEST_TO_JOIN_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.REQUEST_TO_JOIN_ACCEPTED:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,s)};case b.REQUEST_TO_JOIN_DECLINED:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,s),applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.INVITATION_ACCEPTED:case b.INVITATION_DECLINED:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,s),reason:r.reason};case b.USER_REMOVED:return{groupId:r.groupId,groupName:r.groupName};case b.GROUP_DESTROYED:return{groupId:r.groupId,groupName:r.groupName??o};case b.AUTO_ACCEPT_INVITATION:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,s),inviteMessage:r.reason};case b.MUTE_LIST_ADDED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s),muteExpire:r.muteExpire};case b.MUTE_LIST_REMOVED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s)};case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,s)};case b.ALL_MEMBER_MUTE_STATE_CHANGED:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,s)};case b.OWNER_CHANGED:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case b.MEMBERS_JOINED:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,s)};case b.MEMBERS_EXITED:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,s)};case b.ANNOUNCEMENT_CHANGED:return{groupId:r.groupId,announcement:r.announcement??""};case b.SHARED_FILE_ADDED:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,s)};case b.SHARED_FILE_DELETED:return{groupId:r.groupId,fileId:r.fileId??""};case b.GROUP_INFO_CHANGED:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case b.GROUP_DISABLED_CHANGED:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case b.GROUP_MEMBER_ATTRIBUTE_CHANGED:return{groupId:r.groupId,user:this.pickEventUser(r.userId,s),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(s){i.warn("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:s})}if(r)return r;const o=this.getGroupRepository().getDetailSnapshot(e.groupId);return o||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await Ie(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?resource=${o.encodedResource}`);await e.put(s,{newowner:ue(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?version=v3&resource=${o.encodedResource}`);await e.delete(s,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/quit?resource=${o.encodedResource}`);await e.delete(s,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply?resource=${o.encodedResource}`);await e.post(s,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await ye(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await fe(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin?resource=${o.encodedResource}`);await e.post(s,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${o.encodedResource}`);await e.delete(s,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await _e(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await we(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await Ge(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(t){return this.runOperation("checkIfInGroupAllowList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async checkIfInGroupMuteList(t){return this.runOperation("checkIfInGroupMuteList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/sdk/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return be(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement?resource=${o.encodedResource}`);await e.post(s,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await ve(this.getRestClient(t),t,e),o=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?o.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=Re(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),n=u({file:e.file}),a=m({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=a?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const u=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[d]:c()},source:n.source,timeoutMs:p,onProgress:e.onFileUploadProgress}));if(!u)throw new Error("platform upload adapter is unavailable");if(u.status<200||u.status>=300)throw new s("uploadGroupSharedFile failed",o.REST_HTTP_ERROR,{details:{status:u.status}});i?.finish({code:u.status,success:!0}),a?.finish({code:0,success:!0}),e.onFileUploadComplete?.(u.body)}catch(l){const t=f(l);throw i?.finish({code:t.code,success:!1,description:t.message}),a?.finish({code:t.code,success:!1,description:t.message}),t.code===o.UPLOAD_ABORTED&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(r.fileId,"params.fileId"))}?resource=${o.encodedResource}`);await e.delete(s,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const n=this.getRestContextOrThrow(),a=`${n.restBaseUrl}${Re(n,e)}`;t=m({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:a});const i=this.requireClient().getRequestAdapter();if(!i)throw new s("downloadGroupSharedFile request adapter is unavailable",o.REST_NETWORK_ERROR);const u=await i.request({url:a,method:"GET",headers:{Authorization:`Bearer ${n.token}`,...e.secret?{"Share-Secret":e.secret}:{},[d]:c()},responseType:"arraybuffer",timeoutMs:l});if(u.status<200||u.status>=300)throw r?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),new s("downloadGroupSharedFile failed",o.REST_HTTP_ERROR);r?.finish({code:u.status,success:!0}),t?.finish({code:0,success:!0});const p="undefined"!=typeof Blob?new Blob([u.data]):u.data;e.onFileDownloadComplete?.(p)}catch(n){const a=n instanceof s?n.code:o.REST_NETWORK_ERROR,i=n instanceof Error?n.message:String(n);throw r?.finish({code:a,success:!1,description:i}),t?.finish({code:a,success:!1,description:i}),e.onFileDownloadError?.(n),n}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await Se(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return Ae(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),o=t.map(e=>e.userId),s=await(async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/nameCard/batch/get`),n=await e.post(s,{members:ie(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:Ue(n),responseTimestamp:Oe(n)}})(this.getRestClient(r),r,{groupId:e,userIds:o}),n=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),a=[],u=/* @__PURE__ */new Set;for(const[t,i]of Object.entries(s.items))u.add(t),a.push({groupId:e,userId:t,namecard:i.namecard,namecardUpdateTime:n.get(t)??i.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const p=o.filter(e=>!u.has(e));p.length>0&&"number"==typeof s.responseTimestamp&&a.push(...p.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:s.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(a);for(const e of a)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});p.length>0&&"number"!=typeof s.responseTimestamp&&i.warn("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:o,missingUserIds:p})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw i.warn(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof s?t:t instanceof Error?new s(`GroupManager ${e} failed: ${t.message}`,o.UNKNOWN):new s(`GroupManager ${e} failed`,o.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new h(e.restBaseUrl,{errorMap:dt,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 s("GroupManager is not bound to client",o.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new Fe),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new Te(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const o=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return o||void 0}async resolveMembersJoinedGroupName(e){const t=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(t)return t;const r=this.resolveUsableGroupName(e.groupName,e.groupId);if(r)return r;const o=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,{groupId:e.groupId}),s=this.getGroupRepository();if(s.getSessionKey()!==o)return;return s.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(s){return void i.warn("Members joined group detail enrichment failed",{groupId:e.groupId,error:s})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,t,r){if(t.userId!==e)return;const o=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof o)return;const s=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof s&&i.warn("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:o,namecardUpdateTime:s,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const o of r){const e=y("number"==typeof o?o:Number(o));if("number"==typeof e)return e}}collectUpdateTimeCandidates(t,r,o){if(!e(t))return;o.push(t.lastModified,t.last_modified,t.timestamp,t.updateTime,t.update_time,t.updatedAt,t.updated_at);const s=t.data;if(e(s)){this.collectUpdateTimeCandidates(s,r,o);const t=s[r];e(t)&&this.collectUpdateTimeCandidates(t,r,o)}const n=t.lastModified??t.last_modified;e(n)&&o.push(n[r])}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 L(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 i.warn("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],o=[],s=/* @__PURE__ */new Set;for(const n of r){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return N(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>N(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:N(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case b.ALL_MEMBER_MUTE_STATE_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case b.OWNER_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case b.REQUEST_TO_JOIN_ACCEPTED:case b.AUTO_ACCEPT_INVITATION:return void this.addCurrentUserJoinedGroupFromEvent(t);case b.MEMBERS_JOINED:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case b.MEMBERS_EXITED:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case b.USER_REMOVED:case b.GROUP_DESTROYED:return void(await this.removeJoinedGroupLocal(t.groupId));case b.MUTE_LIST_ADDED:case b.MUTE_LIST_REMOVED:case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case b.MEMBERS_JOINED:case b.MEMBERS_EXITED:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const o=this.getGroupRepository().getDetailSnapshot(e);return!(!o||"number"!=typeof o.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,o.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(o){return i.warn("Joined group detail enrichment skipped",{groupId:e.groupId,error:o}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(o){return i.warn("Joined group detail enrichment failed",{groupId:e.groupId,error:o}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const o=await ge(this.getRestClient(r),r,{groupId:e}),s=this.getGroupRepository();if(s.getSessionKey()!==t)return!1;s.mergeDetail(o);const n=s.getJoinedGroupSummarySnapshot(e);if(!n)return!1;const a=s.mergeJoinedGroupSummary(e,{...n.name||!o.name?{}:{name:o.name},...void 0!==n.description||void 0===o.description?{}:{description:o.description},...void 0!==n.memberCount||void 0===o.memberCount?{}:{memberCount:o.memberCount},...void 0!==n.role||void 0===o.role?{}:{role:o.role},...void 0!==n.disabled||void 0===o.disabled?{}:{disabled:o.disabled},...n.ownerId||!o.owner?.userId?{}:{ownerId:o.owner.userId},...void 0!==n.avatarUrl||void 0===o.avatarUrl?{}:{avatarUrl:o.avatarUrl},...void 0!==n.muteAllMembers||void 0===o.muteAllMembers?{}:{muteAllMembers:o.muteAllMembers},...void 0!==n.createdAt||void 0===o.createdAt?{}:{createdAt:o.createdAt},...void 0!==n.joinedAt||void 0===o.joinedAt?{}:{joinedAt:o.joinedAt}});if(a){this.persistJoinedGroupSnapshot(a);const t=s.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:o.name||t.name,avatarUrl:o.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void i.warn("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{i.warn("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=R(e),o=await this.getRestClient(t).request(S(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return A(o,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(_(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),o=await w({groupId:e,users:t,includeNameCard:r,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return r&&this.dispatchFetchedUserInfoUpdates(o.fetchedUserInfos),o.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await G({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),o=e.find(e=>e.userId===r),s=e.filter(e=>e.userId!==r);o&&t.dispatchOwnInfoUpdated?.(o),t.dispatchUserInfoUpdated?.(s),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new pt(e)}};ct.key="groupManager";let mt=ct;export{oe as G,re as J,mt as a,Q as n};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{V as e,E as t,S as i,N as n,b as s,c as r,d as o,e as a,f as l,l as u,R as d,m as h,C as c}from"./common-DHQukb7J.js";import{P as g}from"./event-system-DguqwFpc.js";import{q as m}from"./session-list-query-Cdpiw_IZ.js";const p=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],v=(i,n,s="invalid_format")=>new e(n,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:i,message:n,rule:s}]}}),y=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw v(t,`${t} must be a non-empty string`);return e.trim()}},f=e=>8===e?"normal":p[e]??"normal",T=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class R{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=/* @__PURE__ */new Set}configure(i){const n=(e=>{if(!e||"object"!=typeof e)throw v("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw v("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw v("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw v("plugin.unRegister","plugin.unRegister must be a function");const n=e.certificates;if(!n||"object"!=typeof n)throw v("certificates","certificates is required","required");const s=n,r={apns:y(s.apns,"certificates.apns"),fcm:y(s.fcm,"certificates.fcm"),huawei:y(s.huawei,"certificates.huawei"),xiaomi:y(s.xiaomi,"certificates.xiaomi"),meizu:y(s.meizu,"certificates.meizu"),vivo:y(s.vivo,"certificates.vivo"),oppo:y(s.oppo,"certificates.oppo"),honor:y(s.honor,"certificates.honor")};if(!p.some(e=>void 0!==r[e]))throw v("certificates","at least one native push certificate is required");return{plugin:t,certificates:r,signature:p.map(e=>`${e}:${r[e]??""}`).join("|")}})(i),s=null!==this.config&&"disabled"!==this.state,r=this.config?.plugin===n.plugin&&this.config.signature===n.signature;if(s&&!r)throw new e("Native push is enabled; call removePushToken() before replacing its configuration",{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});s&&r&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=n,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const t of this.collectRemovalTargets(e.generation)){const i=await this.removeWithRetry(t,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!i){this.emitFailure(g.TOKEN_REMOVE_FAILED,"remove",t.channel,t.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new i("User is not logged in",t.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,t=this.session.generation,i=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(n=>{if(!this.isRegistrationActive(t,i))return;const s=((e,t)=>{if(!T(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=f(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(n,e);if(!s){this.state="failed";const t=T(n)?f(n.push_type):void 0,i=T(n)&&200===n.code&&n.push_token.trim().length>0&&void 0!==t&&"normal"!==t&&void 0===e.certificates[t];return void this.emitFailure(g.TOKEN_BIND_FAILED,i?"bind":"register",t)}this.enqueueBinding(s)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(g.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const t=this.session.generation,i=this.createBindingKey(e);this.activeBindingKey=i,this.state="binding";const n=await this.bindWithRetry(e,t);if(this.activeBindingKey=null,!this.session||this.session.generation!==t||this.disabledByUser)return;n?(this.binding={...e,generation:t,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=i,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.dependencies.dispatch(g.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=i,this.state="failed",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.emitFailure(g.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(e,t){this.lastBindingError=null;for(let o=0;o<=n;o+=1)try{const i=this.session;return!(!i||i.generation!==t)&&(this.lastAttemptedBinding={...e,generation:t,userId:i.userId,deviceId:i.clientResource},await this.dependencies.requestToken({deviceId:i.clientResource,deviceToken:e.token,notifierName:e.notifierName,timeout:s}),!0)}catch(i){if(this.lastBindingError=this.toSdkError(i),!this.session||this.session.generation!==t)return!1;if(!this.isRetryable(i)||o===n)return!1;const e=r[o]??0;if(!(await this.wait(e)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new i("User is not logged in",t.AUTH_NOT_LOGIN);const e=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(e))throw this.manualRemovalInProgress=!1,new i("User is not logged in",t.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(e);if(0!==n.length)try{for(const t of n)if(await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName}),!this.isSessionGenerationActive(e))return;this.disableByUser()}catch(s){const t=this.toSdkError(s),i=n[0];throw i&&this.isSessionGenerationActive(e)&&this.emitFailure(g.TOKEN_REMOVE_FAILED,"remove",i.channel,i.notifierName,t),this.manualRemovalInProgress=!1,this.resumePendingBinding(e),t}else this.disableByUser()}async removeWithRetry(e,t){this.lastRemovalError=null;for(let n=0;n<=o;n+=1)try{return await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName,timeout:a}),!0}catch(i){if(this.lastRemovalError=this.toSdkError(i),!this.isSessionGenerationActive(t))return!1;if(!this.isRetryable(i)||n===o)return!1;if(!(await this.wait(l)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{u.warn("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(e){return!(e instanceof i)||(!0===e.details?.retryable||[t.REST_NETWORK_ERROR,t.REST_TIMEOUT,t.REST_HTTP_ERROR,t.SERVER_BUSY].includes(e.code))}toSdkError(e){return e instanceof i?e:new i("Native push operation failed",t.UNKNOWN)}emitFailure(e,t,i,n,s){const r=!!s&&this.isRetryable(s);this.dependencies.dispatchFailure(e,{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r}),u.warn("Native push operation failed",{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r})}}const b=h(c,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),I=["singleChat","groupChat"],N=["ALL","AT","NONE","DEFAULT"],E=["ALL","AT","NONE"],C=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),w=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new R({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(e){const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey);u.debug("Call native push token operation",{deviceId:e.deviceId,notifierName:e.notifierName,removing:0===e.deviceToken.length}),await i.request(`/${n}/${s}/users/${t.userId}`,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken",...void 0!==e.timeout?{timeout:e.timeout}:{}})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);u.debug("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await i.request(r,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/user/${e.userId}`;u.debug("Call getGlobalSilentMode");const r=await t.request(s,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(r))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);u.debug("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const l=await i.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}`;u.debug("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;u.debug("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${n}/${s}/users/${t.userId}/notification?user=${r}&group=${o}`;u.debug("Call getConversationSilentModes",{count:e.conversationList.length});const l=await i.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(l,"user"),h=this.resolveConversationRuleMap(l,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;u.debug("Call setPushLanguage",{language:e.language}),await i.request(r,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/language`;u.debug("Call getPushLanguage");const r=await t.request(s,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(r,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{u.debug("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),i=m({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(i)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof i?e:e instanceof Error?new i(`PushManager operation failed: ${e.message}`,t.UNKNOWN):new i("PushManager operation failed",t.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new d(e.restBaseUrl,{errorMap:b,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new i("PushManager is not bound to client",t.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!I.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!C(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!E.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!C(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!C(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(C(e.data)){const i=e.data[t];if(C(i))return i}const i=e[t];return C(i)?i:{}}resolveSilentModeRuleSource(e){if(!C(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return C(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":N.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(C(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(i,n){return new e(i,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:n}})}};w.key="pushManager";let S=w;export{S as P};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e=require("./common-tHGz9VBk.cjs"),t=require("./event-system-TYhmgy4K.cjs"),i=require("./session-list-query-C3iQvQxK.cjs"),n=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],s=(t,i,n="invalid_format")=>new e.ValidationError(i,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:i,rule:n}]}}),r=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw s(t,`${t} must be a non-empty string`);return e.trim()}},o=e=>8===e?"normal":n[e]??"normal",a=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class l{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=new Set}configure(t){const i=(e=>{if(!e||"object"!=typeof e)throw s("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw s("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw s("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw s("plugin.unRegister","plugin.unRegister must be a function");const o=e.certificates;if(!o||"object"!=typeof o)throw s("certificates","certificates is required","required");const a=o,l={apns:r(a.apns,"certificates.apns"),fcm:r(a.fcm,"certificates.fcm"),huawei:r(a.huawei,"certificates.huawei"),xiaomi:r(a.xiaomi,"certificates.xiaomi"),meizu:r(a.meizu,"certificates.meizu"),vivo:r(a.vivo,"certificates.vivo"),oppo:r(a.oppo,"certificates.oppo"),honor:r(a.honor,"certificates.honor")};if(!n.some(e=>void 0!==l[e]))throw s("certificates","at least one native push certificate is required");return{plugin:t,certificates:l,signature:n.map(e=>`${e}:${l[e]??""}`).join("|")}})(t),o=null!==this.config&&"disabled"!==this.state,a=this.config?.plugin===i.plugin&&this.config.signature===i.signature;if(o&&!a)throw new e.ValidationError("Native push is enabled; call removePushToken() before replacing its configuration",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});o&&a&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=i,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const i of this.collectRemovalTargets(e.generation)){const n=await this.removeWithRetry(i,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!n){this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",i.channel,i.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,i=this.session.generation,n=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(s=>{if(!this.isRegistrationActive(i,n))return;const r=((e,t)=>{if(!a(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=o(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(s,e);if(!r){this.state="failed";const i=a(s)?o(s.push_type):void 0,n=a(s)&&200===s.code&&s.push_token.trim().length>0&&void 0!==i&&"normal"!==i&&void 0===e.certificates[i];return void this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,n?"bind":"register",i)}this.enqueueBinding(r)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const i=this.session.generation,n=this.createBindingKey(e);this.activeBindingKey=n,this.state="binding";const s=await this.bindWithRetry(e,i);if(this.activeBindingKey=null,!this.session||this.session.generation!==i||this.disabledByUser)return;s?(this.binding={...e,generation:i,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=n,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.dependencies.dispatch(t.PushEventName.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=n,this.state="failed",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(t,i){this.lastBindingError=null;for(let s=0;s<=e.NATIVE_PUSH_BIND_MAX_RETRIES;s+=1)try{const n=this.session;return!(!n||n.generation!==i)&&(this.lastAttemptedBinding={...t,generation:i,userId:n.userId,deviceId:n.clientResource},await this.dependencies.requestToken({deviceId:n.clientResource,deviceToken:t.token,notifierName:t.notifierName,timeout:e.NATIVE_PUSH_BIND_REQUEST_TIMEOUT}),!0)}catch(n){if(this.lastBindingError=this.toSdkError(n),!this.session||this.session.generation!==i)return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_BIND_MAX_RETRIES)return!1;const t=e.NATIVE_PUSH_BIND_RETRY_DELAYS[s]??0;if(!(await this.wait(t)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const i=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(i))throw this.manualRemovalInProgress=!1,new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(i);if(0!==n.length)try{for(const e of n)if(await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName}),!this.isSessionGenerationActive(i))return;this.disableByUser()}catch(s){const e=this.toSdkError(s),r=n[0];throw r&&this.isSessionGenerationActive(i)&&this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",r.channel,r.notifierName,e),this.manualRemovalInProgress=!1,this.resumePendingBinding(i),e}else this.disableByUser()}async removeWithRetry(t,i){this.lastRemovalError=null;for(let s=0;s<=e.NATIVE_PUSH_REMOVE_MAX_RETRIES;s+=1)try{return await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName,timeout:e.NATIVE_PUSH_REMOVE_REQUEST_TIMEOUT}),!0}catch(n){if(this.lastRemovalError=this.toSdkError(n),!this.isSessionGenerationActive(i))return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_REMOVE_MAX_RETRIES)return!1;if(!(await this.wait(e.NATIVE_PUSH_REMOVE_RETRY_DELAY)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{e.logger.warn("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(t){return!(t instanceof e.SDKError)||(!0===t.details?.retryable||[e.ERROR_CODES.REST_NETWORK_ERROR,e.ERROR_CODES.REST_TIMEOUT,e.ERROR_CODES.REST_HTTP_ERROR,e.ERROR_CODES.SERVER_BUSY].includes(t.code))}toSdkError(t){return t instanceof e.SDKError?t:new e.SDKError("Native push operation failed",e.ERROR_CODES.UNKNOWN)}emitFailure(t,i,n,s,r){const o=!!r&&this.isRetryable(r);this.dependencies.dispatchFailure(t,{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o}),e.logger.warn("Native push operation failed",{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o})}}const u=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),d=["singleChat","groupChat"],h=["ALL","AT","NONE","DEFAULT"],c=["ALL","AT","NONE"],g=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),m=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new l({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(t){const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey);e.logger.debug("Call native push token operation",{deviceId:t.deviceId,notifierName:t.notifierName,removing:0===t.deviceToken.length}),await n.request(`/${s}/${r}/users/${i.userId}`,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken",...void 0!==t.timeout?{timeout:t.timeout}:{}})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/user/${i.userId}?resource=${encodeURIComponent(i.clientResource)}`,a=this.buildSilentModePayload(t.rule);e.logger.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await n.request(o,{method:"PUT",body:a,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}`;e.logger.debug("Call getGlobalSilentMode");const o=await i.request(r,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(o))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.logger.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await n.request(a,{method:"PUT",body:l,operation:"setConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(u),t.rule)}})}async getConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}`;e.logger.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l))}})}async clearConversationRemindType(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`;e.logger.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),{remindType:"DEFAULT"})}})}async getConversationSilentModes(t){return this.runOperation(async()=>{this.validateConversationList(t.conversationList,"conversationList");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${s}/${r}/users/${i.userId}/notification?user=${o}&group=${a}`;e.logger.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await n.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),h=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(t){await this.runOperation(async()=>{this.validateLanguage(t.language,"language");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/language`;e.logger.debug("Call setPushLanguage",{language:t.language}),await n.request(o,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;e.logger.debug("Call getPushLanguage");const o=await i.request(r,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(o,"")}})}getConversationListByRemindType(t){return this.runOperation(()=>{e.logger.debug("Call getConversationListByRemindType",{pageSize:t.pageSize,hasCursor:Boolean(t.cursor)});const n=this.getClientOrThrow(),s=i.queryMutedConversationsFromSessionList({items:n.getCacheManager()?.loadSessionList()??[],pageSize:t.pageSize,cursor:t.cursor});return Promise.resolve(s)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(t){return t instanceof e.SDKError?t:t instanceof Error?new e.SDKError(`PushManager operation failed: ${t.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError("PushManager operation failed",e.ERROR_CODES.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:u,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}getClientOrThrow(){if(!this.client)throw new e.SDKError("PushManager is not bound to client",e.ERROR_CODES.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!d.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!g(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!c.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!g(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!g(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(g(e.data)){const i=e.data[t];if(g(i))return i}const i=e[t];return g(i)?i:{}}resolveSilentModeRuleSource(e){if(!g(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return g(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":h.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(g(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(t,i){return new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:i}})}};m.key="pushManager";let p=m;exports.PushManager=p;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e=require("zod"),t=require("./common-tHGz9VBk.cjs"),o=e.z.record(e.z.unknown()),n={text:e.z.object({content:e.z.string()}),image:e.z.object({isGif:e.z.boolean(),isOriginalImage:e.z.boolean()}),video:e.z.object({duration:e.z.number()}),voice:e.z.object({duration:e.z.number()}),file:o,location:e.z.object({latitude:e.z.number(),longitude:e.z.number()}),cmd:e.z.object({action:e.z.string()}),custom:e.z.object({event:e.z.string()}),combine:e.z.object({title:e.z.string(),summary:e.z.string(),filename:e.z.string(),filetype:e.z.string(),combineLevel:e.z.number()})},r=e.z.object({msgServerId:e.z.string(),msgLocalId:e.z.string(),from:e.z.string(),to:e.z.string(),sender:e.z.object({userId:e.z.string(),nickname:e.z.string().optional(),avatarUrl:e.z.string().optional()}),conversationId:e.z.string(),conversationType:e.z.enum(["singleChat","groupChat","chatRoom"]),type:e.z.enum(["text","image","video","voice","file","location","cmd","custom","combine"]),sendStatus:e.z.enum(["sending","sent","failed"]),timestamp:e.z.number(),ext:o,body:o});const i=e.z.boolean().optional().catch(void 0),a=e.z.number().finite().optional().catch(void 0),s=e.z.string().optional().catch(void 0),c=e.z.object({msgLocalId:s,sendStatus:e.z.enum(["sending","sent","failed"]).optional().catch(void 0),direct:e.z.enum(["SEND","RECEIVE"]).optional().catch(void 0),isOnline:i,receiverList:e.z.array(e.z.string()).optional().catch(void 0),deliverOnlineOnly:i,webhookEnv:s,priority:e.z.enum(["high","normal","low"]).optional().catch(void 0),isBroadcast:i,isContentReplaced:i,combineLevel:a,modifiedInfo:e.z.object({operatorId:e.z.string(),operationCount:e.z.number().finite(),operationTime:e.z.number().finite()}).optional().catch(void 0),reactions:e.z.array(e.z.object({reaction:e.z.string(),count:e.z.number(),userList:e.z.array(e.z.string()),isAddedBySelf:e.z.boolean().optional(),op:e.z.array(e.z.object({operator:e.z.string(),reactionType:e.z.enum(["create","delete"])})).optional()})).optional().catch(void 0),groupReadCount:e.z.number().int().nonnegative().optional().catch(void 0),isPeerRead:i,needReadReceipt:i,isChatThread:i,chatThread:e.z.object({messageId:e.z.string(),parentId:e.z.string(),chatThreadName:e.z.string().optional()}).optional().catch(void 0),chatThreadOverview:e.z.object({chatThreadId:e.z.string(),parentId:e.z.string(),name:e.z.string().optional(),lastMessage:e.z.custom(e=>{const t=r.safeParse(e);return t.success&&n[t.data.type].safeParse(t.data.body).success}).transform(function(e){return{...r.parse(e),body:e.body,...d(e)}}).nullable().optional().catch(null),createdAt:e.z.number().optional(),updatedAt:e.z.number().optional(),messageCount:e.z.number().optional()}).optional().catch(void 0),stream:e.z.object({customType:e.z.string().optional(),seq:e.z.number(),status:e.z.enum(["STREAM_START","STREAM_START_COMPLETED","STREAM_IN_PROGRESS","STREAM_COMPLETED","STREAM_FULL","STREAM_ERROR"]),errorType:e.z.number(),finishReason:e.z.number().optional(),deltaText:e.z.string(),fullText:e.z.string()}).optional().catch(void 0),userInfoUpdateTime:a,namecardUpdateTime:a}),d=e=>{const t=c.safeParse(e);if(!t.success)return{};for(const[o,n]of Object.entries(t.data))void 0===n&&Reflect.deleteProperty(t.data,o);return t.data},m=e=>{const t={...e};return delete t.type,delete t.messageList,t},l=e=>new t.ValidationError(`${e} must be a local paging cursor returned by SDK`,{code:t.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),u=(e,t,o)=>{const n=e+t;return n<o?String(n):""},p=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null;exports.hasSessionMark=(e,t)=>e.marks.includes(t),exports.messageSnapshotSignature=e=>JSON.stringify(e,(e,t)=>t&&"object"==typeof t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t))):t),exports.projectMessageBody=m,exports.projectMessageMetadata=d,exports.queryMutedConversationsFromSessionList=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new t.ValidationError("pageSize must be a positive integer",{code:t.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const o=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw l(t);const o=Number.parseInt(e,10);if(!Number.isSafeInteger(o)||o<0)throw l(t);return o})(e.cursor,"cursor"),n=[];for(const t of e.items){if("chatRoom"===t.conversationType)continue;const e=p(t.remindType);e&&n.push({conversationId:t.conversationId,conversationType:t.conversationType,remindType:e})}return{conversations:n.slice(o,o+e.pageSize),cursor:u(o,e.pageSize,n.length)}},exports.toConversationItem=e=>({...e}),exports.toConversationSummary=e=>{const t=(e=>e?{...d(e),msgId:e.msgServerId,from:e.from,to:e.to,sender:{...e.sender},type:e.type??"unknown",body:m(e.body),ext:e.ext,timestamp:e.timestamp}:null)(e.lastMessage),o=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:o,lastUpdate:o}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z as e}from"zod";import{V as t,E as n}from"./common-DHQukb7J.js";const o=e.record(e.unknown()),a={text:e.object({content:e.string()}),image:e.object({isGif:e.boolean(),isOriginalImage:e.boolean()}),video:e.object({duration:e.number()}),voice:e.object({duration:e.number()}),file:o,location:e.object({latitude:e.number(),longitude:e.number()}),cmd:e.object({action:e.string()}),custom:e.object({event:e.string()}),combine:e.object({title:e.string(),summary:e.string(),filename:e.string(),filetype:e.string(),combineLevel:e.number()})},i=e.object({msgServerId:e.string(),msgLocalId:e.string(),from:e.string(),to:e.string(),sender:e.object({userId:e.string(),nickname:e.string().optional(),avatarUrl:e.string().optional()}),conversationId:e.string(),conversationType:e.enum(["singleChat","groupChat","chatRoom"]),type:e.enum(["text","image","video","voice","file","location","cmd","custom","combine"]),sendStatus:e.enum(["sending","sent","failed"]),timestamp:e.number(),ext:o,body:o});const r=e.boolean().optional().catch(void 0),s=e.number().finite().optional().catch(void 0),c=e.string().optional().catch(void 0),d=e.object({msgLocalId:c,sendStatus:e.enum(["sending","sent","failed"]).optional().catch(void 0),direct:e.enum(["SEND","RECEIVE"]).optional().catch(void 0),isOnline:r,receiverList:e.array(e.string()).optional().catch(void 0),deliverOnlineOnly:r,webhookEnv:c,priority:e.enum(["high","normal","low"]).optional().catch(void 0),isBroadcast:r,isContentReplaced:r,combineLevel:s,modifiedInfo:e.object({operatorId:e.string(),operationCount:e.number().finite(),operationTime:e.number().finite()}).optional().catch(void 0),reactions:e.array(e.object({reaction:e.string(),count:e.number(),userList:e.array(e.string()),isAddedBySelf:e.boolean().optional(),op:e.array(e.object({operator:e.string(),reactionType:e.enum(["create","delete"])})).optional()})).optional().catch(void 0),groupReadCount:e.number().int().nonnegative().optional().catch(void 0),isPeerRead:r,needReadReceipt:r,isChatThread:r,chatThread:e.object({messageId:e.string(),parentId:e.string(),chatThreadName:e.string().optional()}).optional().catch(void 0),chatThreadOverview:e.object({chatThreadId:e.string(),parentId:e.string(),name:e.string().optional(),lastMessage:e.custom(e=>{const t=i.safeParse(e);return t.success&&a[t.data.type].safeParse(t.data.body).success}).transform(function(e){return{...i.parse(e),body:e.body,...m(e)}}).nullable().optional().catch(null),createdAt:e.number().optional(),updatedAt:e.number().optional(),messageCount:e.number().optional()}).optional().catch(void 0),stream:e.object({customType:e.string().optional(),seq:e.number(),status:e.enum(["STREAM_START","STREAM_START_COMPLETED","STREAM_IN_PROGRESS","STREAM_COMPLETED","STREAM_FULL","STREAM_ERROR"]),errorType:e.number(),finishReason:e.number().optional(),deltaText:e.string(),fullText:e.string()}).optional().catch(void 0),userInfoUpdateTime:s,namecardUpdateTime:s}),m=e=>{const t=d.safeParse(e);if(!t.success)return{};for(const[n,o]of Object.entries(t.data))void 0===o&&Reflect.deleteProperty(t.data,n);return t.data},l=e=>JSON.stringify(e,(e,t)=>t&&"object"==typeof t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t))):t),u=e=>{const t={...e};return delete t.type,delete t.messageList,t},p=e=>new t(`${e} must be a local paging cursor returned by SDK`,{code:n.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),g=(e,t,n)=>{const o=e+t;return o<n?String(o):""},b=e=>({...e}),v=e=>{const t=(e=>e?{...m(e),msgId:e.msgServerId,from:e.from,to:e.to,sender:{...e.sender},type:e.type??"unknown",body:u(e.body),ext:e.ext,timestamp:e.timestamp}:null)(e.lastMessage),n=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:n,lastUpdate:n}},f=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,h=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new t("pageSize must be a positive integer",{code:n.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const o=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw p(t);const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n)||n<0)throw p(t);return n})(e.cursor,"cursor"),a=[];for(const t of e.items){if("chatRoom"===t.conversationType)continue;const e=f(t.remindType);e&&a.push({conversationId:t.conversationId,conversationType:t.conversationType,remindType:e})}return{conversations:a.slice(o,o+e.pageSize),cursor:g(o,e.pageSize,a.length)}},T=(e,t)=>e.marks.includes(t);export{m as a,v as b,T as h,l as m,u as p,h as q,b as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e}from"./cache-utils-B99glc0H.js";import{p as r,V as t,E as a}from"./common-
|
|
1
|
+
import{i as e}from"./cache-utils-B99glc0H.js";import{p as r,V as t,E as a}from"./common-DHQukb7J.js";const n={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},i=(e,r,n)=>new t(e,{code:"required"===n?a.VALIDATION_REQUIRED:a.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:e,rule:n}]}}),s=(e,r)=>{if("string"!=typeof e)throw i(`${r} must be a string`,r,"invalid_format");return e},o=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw i(`${r} must be a string, number, or boolean`,r,"invalid_format")},p=(e,r="attribute")=>{const t=n[e];if(!t)throw i(`${r} is invalid`,r,"invalid_format");return t},m=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[n,i]of e.entries()){const e=s(i,`${r}[${n}]`).trim();e&&(a.has(e)||(a.add(e),t.push(e)))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[o,p]of e.entries()){const e=s(p,`${r}[${o}]`);if(!(e in n))throw i(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");a.has(e)||(a.add(e),t.push(e))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},u=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/get`},f=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/${encodeURIComponent(e.userId)}`},l=e=>({targets:m(e)}),g=(e,r)=>({targets:m(e),properties:d(r).map(e=>p(e,"params.attributes"))}),c=r=>!!e(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),h=(r,t)=>{if(Array.isArray(r))for(const a of r){if(!e(a))continue;const r="string"==typeof a.username?a.username:"";r&&t.set(r,a)}},b=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},y=(r,t)=>{const a=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(a?.data&&e(a.data))for(const[e,n]of Object.entries(a.data))c(n)&&t.set(e,n);return h(a?.entities,t),h(a?.data&&e(a.data)?a.data.entities:void 0,t),t})(r),n=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(!a?.lastModified||!e(a.lastModified))return t;for(const[e,n]of Object.entries(a.lastModified))"number"==typeof n&&t.set(e,n);return t})(r),i=[];for(const e of t){const r=a.get(e);r&&i.push({profile:b(e,r),lastModified:n.get(e)})}return i},v=(e,r)=>y(e,r).map(e=>e.profile),$=(e,r,t,a)=>{void 0!==t&&("gender"!==r?e.push([r,s(t,a)]):e.push([r,String(o(t,a))]))},w=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"),I=e=>{const r=[];if($(r,"nickname",e.nickname,"params.nickname"),$(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),$(r,"mail",e.mail,"params.mail"),$(r,"phone",e.phone,"params.phone"),$(r,"gender",e.gender,"params.gender"),$(r,"sign",e.sign,"params.sign"),$(r,"birth",e.birth,"params.birth"),$(r,"ext",e.ext,"params.ext"),0===r.length)throw i("params must include at least one updatable field","params","required");return w(r)},A=(e,r)=>{const t=p(e,"attribute"),a=o(r,"value");if("gender"!==t&&"string"!=typeof a)throw i("value must be a string","value","invalid_format");return w([[t,String(a)]])};export{u as a,l as b,m as c,g as d,d as e,I as f,f as g,A as h,y as i,v as n};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ConversationItem, SessionMessageSnippet } from '../../types/conversation';
|
|
2
|
+
import type { ChatThreadRawNotifyPayload } from '../../types/chat-thread';
|
|
3
|
+
/** @internal Updates a parent message overview only when the notification identifies that message/thread. */
|
|
4
|
+
export declare const resolveThreadLastMessagePatch: (payload: ChatThreadRawNotifyPayload, items: ReadonlyArray<ConversationItem>, userId: string, useCustomAttachmentUpload?: boolean) => {
|
|
5
|
+
readonly conversationId: string;
|
|
6
|
+
readonly conversationType: "groupChat";
|
|
7
|
+
readonly messageId: string;
|
|
8
|
+
readonly patch: Partial<SessionMessageSnippet>;
|
|
9
|
+
} | null;
|